Programs & Examples On #Dblinq

How to convert NSData to byte array in iPhone?

Already answered, but to generalize to help other readers:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

In Laravel, the best way to pass different types of flash messages in the session

For my application i made a helper function:

function message( $message , $status = 'success', $redirectPath = null )
{
     $redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );

     return $redirectPath->with([
         'message'   =>  $message,
         'status'    =>  $status,
    ]);
}

message layout, main.layouts.message:

@if($status)
   <div class="center-block affix alert alert-{{$status}}">
     <i class="fa fa-{{ $status == 'success' ? 'check' : $status}}"></i>
     <span>
        {{ $message }}
     </span>
   </div>
@endif

and import every where to show message:

@include('main.layouts.message', [
    'status'    =>  session('status'),
    'message'   =>  session('message'),
])

How to make flexbox items the same size?

The accepted answer by Adam (flex: 1 1 0) works perfectly for flexbox containers whose width is either fixed, or determined by an ancestor. Situations where you want the children to fit the container.

However, you may have a situation where you want the container to fit the children, with the children equally sized based on the largest child. You can make a flexbox container fit its children by either:

  • setting position: absolute and not setting width or right, or
  • place it inside a wrapper with display: inline-block

For such flexbox containers, the accepted answer does NOT work, the children are not sized equally. I presume that this is a limitation of flexbox, since it behaves the same in Chrome, Firefox and Safari.

The solution is to use a grid instead of a flexbox.

Demo: https://codepen.io/brettdonald/pen/oRpORG

<p>Normal scenario — flexbox where the children adjust to fit the container — and the children are made equal size by setting {flex: 1 1 0}</p>

<div id="div0">
  <div>
    Flexbox
  </div>
  <div>
    Width determined by viewport
  </div>
  <div>
    All child elements are equal size with {flex: 1 1 0}
  </div>
</div>

<p>Now we want to have the container fit the children, but still have the children all equally sized, based on the largest child. We can see that {flex: 1 1 0} has no effect.</p>

<div class="wrap-inline-block">
<div id="div1">
  <div>
    Flexbox
  </div>
  <div>
    Inside inline-block
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
</div>

<div id="div2">
  <div>
    Flexbox
  </div>
  <div>
    Absolutely positioned
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>

<br><br><br><br><br><br>
<p>So let's try a grid instead. Aha! That's what we want!</p>

<div class="wrap-inline-block">
<div id="div3">
  <div>
    Grid
  </div>
  <div>
    Inside inline-block
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
</div>

<div id="div4">
  <div>
    Grid
  </div>
  <div>
    Absolutely positioned
  </div>
  <div>
    We want all children to be the size of this text
  </div>
</div>
body {
  margin: 1em;
}

.wrap-inline-block {
  display: inline-block;
}

#div0, #div1, #div2, #div3, #div4 {
  border: 1px solid #888;
  padding: 0.5em;
  text-align: center;
  white-space: nowrap;
}

#div2, #div4 {
  position: absolute;
  left: 1em;
}

#div0>*, #div1>*, #div2>*, #div3>*, #div4>* {
  margin: 0.5em;
  color: white;
  background-color: navy;
  padding: 0.5em;
}

#div0, #div1, #div2 {
  display: flex;
}

#div0>*, #div1>*, #div2>* {
  flex: 1 1 0;
}

#div0 {
  margin-bottom: 1em;
}

#div2 {
  top: 15.5em;
}

#div3, #div4 {
  display: grid;
  grid-template-columns: repeat(3,1fr);
}

#div4 {
  top: 28.5em;
}

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

Building up on @peeol's excellent answer, you can also remove the frame by doing

for spine in plt.gca().spines.values():
    spine.set_visible(False)

To give an example (the entire code sample can be found at the end of this post), let's say you have a bar plot like this,

enter image description here

you can remove the frame with the commands above and then either keep the x- and ytick labels (plot not shown) or remove them as well doing

plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

In this case, one can then label the bars directly; the final plot could look like this (code can be found below):

enter image description here

Here is the entire code that is necessary to generate the plots:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

xvals = list('ABCDE')
yvals = np.array(range(1, 6))

position = np.arange(len(xvals))

mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)

plt.title('My great data')
# plt.show()

# get rid of the frame
for spine in plt.gca().spines.values():
    spine.set_visible(False)

# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

# plt.show()

# direct label each bar with Y axis values
for bari in mybars:
    height = bari.get_height()
    plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
                 ha='center', color='white', fontsize=15)
plt.show()

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

Is it possible to have SSL certificate for IP address, not domain name?

It entirely depends upon the Certificate Authority who issuing a certificate.

As far as Let's Encrypt CA, they wont issue TLS certificate on public IP address. https://community.letsencrypt.org/t/certificate-for-public-ip-without-domain-name/6082

To know your Certificate authority , you can execute following command and look for an entry marked below.

curl -v -u <username>:<password> "https://IPaddress/.."

enter image description here

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

For my issue, I didn't want my images scaled to 100% when they weren't intended to be as large as the container.

For my xs container (<768px as .container), not having a fixed width drove the issue, so I put one back on to it (less the 15px col padding).

// Helps bootstrap 3.0 keep images constrained to container width when width isn't set a fixed value (below 768px), while avoiding all images at 100% width.
// NOTE: proper function relies on there being no inline styling on the element being given a defined width ( '.container'  )

function setWidth() {
    width_val = $( window ).width();
    if( width_val < 768 ) {
        $( '.container' ).width( width_val - 30 );
    } else {
        $( '.container' ).removeAttr( 'style' );
    }
}

setWidth();
$( window ).resize( setWidth );

Scripting SQL Server permissions

Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:

SELECT
  CASE
      WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'DATABASE' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'SCHEMA' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'TYPE' THEN
        dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS + 
        ' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
            + ' TO [' + dpr.name + ']'
      WHEN dp.class_desc = 'CERTIFICATE' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']' 
      WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
      ' TO ' + '[' + dpr.name + ']' 
      ELSE 
        'ERROR: Unhandled class_desc: ' + dp.class_desc
  END
 AS GRANT_STMT
FROM sys.database_permissions AS dp 
  JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
  LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
  LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE 
dpr.name NOT IN ('public','guest') 
--  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
--  AND (o.name NOT IN ('My_Procedure') or o.name is null)  -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
--  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
--  AND dpr.name LIKE '%user_name%'     -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

select the index then select the ones needed then select sql and click action then click rebuild

enter image description here

File Upload with Angular Material

You can change the style by wrapping the input inside a label and change the input display to none. Then, you can specify the text you want to be displayed inside a span element. Note: here I used bootstrap 4 button style (btn btn-outline-primary). You can use any style you want.

<label class="btn btn-outline-primary">
      <span>Select File</span>
      <input type="file">
</label>

input {
  display: none;
}

Why javascript getTime() is not a function?

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

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

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

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

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

Solution

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

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

Edit:

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

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

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

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

and to perform the mapping:

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

for arrays use:

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

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

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

What is the significance of 1/1/1753 in SQL Server?

Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

Nodejs send file in response

You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.

There is an example function that do it:

const fs = require('fs');

// Where fileName is name of the file and response is Node.js Reponse. 
responseFile = (fileName, response) => {
  const filePath =  "/path/to/archive.rar" // or any file format

  // Check if file specified by the filePath exists 
  fs.exists(filePath, function(exists){
      if (exists) {     
        // Content-type is very interesting part that guarantee that
        // Web browser will handle response in an appropriate manner.
        response.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "attachment; filename=" + fileName
        });
        fs.createReadStream(filePath).pipe(response);
      } else {
        response.writeHead(400, {"Content-Type": "text/plain"});
        response.end("ERROR File does not exist");
      }
    });
  }
}

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.

"filename=[name of file]" specifies name of file which will be downloaded.

For more information please see this stackoverflow topic.

How to hide html source & disable right click and text copy?

If you are using jQuery, it is possible to disable rightclick on the whole page like this:

$( document ).ready(function() {
    $("html").on("contextmenu",function(){
        return false;});}

The openssl extension is required for SSL/TLS protection

enter image description here You are running Composer with SSL/TLS protection disabled.

 composer config --global disable-tls true
 composer config --global disable-tls false

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

Solution to "subquery returns more than 1 row" error

Adding my answer, because it elaborates the idea that you can SELECT multiple columns from the table from which you subquery.

Here I needed the the most recently cast cote and it's associated information.

I first tried simply to SELECT the max(votedate) along with vote, itemid, userid etc., but while the query would return the max votedate, it would also return the a random row for the other information. Hard to see among a bunch of 1s and 0s.

This worked well:

$query = "  
    SELECT t1.itemid, t1.itemtext, t2.vote, t2.votedate, t2.userid 
    FROM
        (
        SELECT itemid, itemtext FROM oc_item ) t1
    LEFT JOIN 
        (
        SELECT vote, votedate, itemid,userid FROM oc_votes
        WHERE votedate IN 
        (select max(votedate) FROM oc_votes group by itemid)
        AND userid=:userid) t2
    ON (t1.itemid = t2.itemid)
    order by itemid ASC
";

The subquery in the WHERE clause WHERE votedate IN (select max(votedate) FROM oc_votes group by itemid) returns one record - the record with the max vote date.

Exclude all transitive dependencies of a single dependency

What is your reason for excluding all transitive dependencies?

If there is a particular artifact (such as commons-logging) which you need to exclude from every dependency, the Version 99 Does Not Exist approach might help.


Update 2012: Don't use this approach. Use maven-enforcer-plugin and exclusions. Version 99 produces bogus dependencies and the Version 99 repository is offline (there are similar mirrors but you can't rely on them to stay online forever either; it's best to use only Maven Central).

What is the size limit of a post request?

The url portion of a request (GET and POST) can be limited by both the browser and the server - generally the safe size is 2KB as there are almost no browsers or servers that use a smaller limit.

The body of a request (POST) is normally* limited by the server on a byte size basis in order to prevent a type of DoS attack (note that this means character escaping can increase the byte size of the body). The most common server setting is 10MB, though all popular servers allow this to be increased or decreased via a setting file or panel.

*Some exceptions exist with older cell phone or other small device browsers - in those cases it is more a function of heap space reserved for this purpose on the device then anything else.

In javascript, how do you search an array for a substring match

Another possibility is

var res = /!id-[^!]*/.exec("!"+windowArray.join("!"));
return res && res[0].substr(1);

that IMO may make sense if you can have a special char delimiter (here i used "!"), the array is constant or mostly constant (so the join can be computed once or rarely) and the full string isn't much longer than the prefix searched for.

Polygon Drawing and Getting Coordinates with Google Map API v3

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

WHERE vs HAVING

Why is it that you need to place columns you create yourself (for example "select 1 as number") after HAVING and not WHERE in MySQL?

WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates).

In general, you can reference aliases in neither of these clauses, but MySQL allows referencing SELECT level aliases in GROUP BY, ORDER BY and HAVING.

And are there any downsides instead of doing "WHERE 1" (writing the whole definition instead of a column name)

If your calculated expression does not contain any aggregates, putting it into the WHERE clause will most probably be more efficient.

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

Function passed as template argument

Template parameters can be either parameterized by type (typename T) or by value (int X).

The "traditional" C++ way of templating a piece of code is to use a functor - that is, the code is in an object, and the object thus gives the code unique type.

When working with traditional functions, this technique doesn't work well, because a change in type doesn't indicate a specific function - rather it specifies only the signature of many possible functions. So:

template<typename OP>
int do_op(int a, int b, OP op)
{
  return op(a,b);
}
int add(int a, int b) { return a + b; }
...

int c = do_op(4,5,add);

Isn't equivalent to the functor case. In this example, do_op is instantiated for all function pointers whose signature is int X (int, int). The compiler would have to be pretty aggressive to fully inline this case. (I wouldn't rule it out though, as compiler optimization has gotten pretty advanced.)

One way to tell that this code doesn't quite do what we want is:

int (* func_ptr)(int, int) = add;
int c = do_op(4,5,func_ptr);

is still legal, and clearly this is not getting inlined. To get full inlining, we need to template by value, so the function is fully available in the template.

typedef int(*binary_int_op)(int, int); // signature for all valid template params
template<binary_int_op op>
int do_op(int a, int b)
{
 return op(a,b);
}
int add(int a, int b) { return a + b; }
...
int c = do_op<add>(4,5);

In this case, each instantiated version of do_op is instantiated with a specific function already available. Thus we expect the code for do_op to look a lot like "return a + b". (Lisp programmers, stop your smirking!)

We can also confirm that this is closer to what we want because this:

int (* func_ptr)(int,int) = add;
int c = do_op<func_ptr>(4,5);

will fail to compile. GCC says: "error: 'func_ptr' cannot appear in a constant-expression. In other words, I can't fully expand do_op because you haven't given me enough info at compiler time to know what our op is.

So if the second example is really fully inlining our op, and the first is not, what good is the template? What is it doing? The answer is: type coercion. This riff on the first example will work:

template<typename OP>
int do_op(int a, int b, OP op) { return op(a,b); }
float fadd(float a, float b) { return a+b; }
...
int c = do_op(4,5,fadd);

That example will work! (I am not suggesting it is good C++ but...) What has happened is do_op has been templated around the signatures of the various functions, and each separate instantiation will write different type coercion code. So the instantiated code for do_op with fadd looks something like:

convert a and b from int to float.
call the function ptr op with float a and float b.
convert the result back to int and return it.

By comparison, our by-value case requires an exact match on the function arguments.

Current date without time

Try this:

   var mydtn = DateTime.Today;
   var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

how to get the attribute value of an xml node using java

use

document.getElementsByTagName(" * ");

to get all XML elements from within an XML file, this does however return repeating attributes

example:

NodeList list = doc.getElementsByTagName("*");


System.out.println("XML Elements: ");

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }

What is the maximum number of edges in a directed graph with n nodes?

Putting it another way:

A complete graph is an undirected graph where each distinct pair of vertices has an unique edge connecting them. This is intuitive in the sense that, you are basically choosing 2 vertices from a collection of n vertices.

nC2 = n!/(n-2)!*2! = n(n-1)/2

This is the maximum number of edges an undirected graph can have. Now, for directed graph, each edge converts into two directed edges. So just multiply the previous result with two. That gives you the result: n(n-1)

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

git command to move a folder inside another

I had a similar problem with git mv where I wanted to move the contents of one folder into an existing folder, and ended up with this "simple" script:

pushd common; for f in $(git ls-files); do newdir="../include/$(dirname $f)"; mkdir -p $newdir; git mv $f $newdir/$(basename "$f"); done; popd

Explanation

  • git ls-files: Find all files (in the common folder) checked into git
  • newdir="../include/$(dirname $f)"; mkdir -p $newdir;: Make a new folder inside the include folder, with the same directory structure as common
  • git mv $f $newdir/$(basename "$f"): Move the file into the newly created folder

The reason for doing this is that git seems to have problems moving files into existing folders, and it will also fail if you try to move a file into a non-existing folder (hence mkdir -p).

The nice thing about this approach is that it only touches files that are already checked in to git. By simply using git mv to move an entire folder, and the folder contains unstaged changes, git will not know what to do.

After moving the files you might want to clean the repository to remove any remaining unstaged changes - just remember to dry-run first!

git clean -fd -n

How can I read and parse CSV files in C++?

As all the CSV questions seem to get redirected here, I thought I'd post my answer here. This answer does not directly address the asker's question. I wanted to be able to read in a stream that is known to be in CSV format, and also the types of each field was already known. Of course, the method below could be used to treat every field to be a string type.

As an example of how I wanted to be able to use a CSV input stream, consider the following input (taken from wikipedia's page on CSV):

const char input[] =
"Year,Make,Model,Description,Price\n"
"1997,Ford,E350,\"ac, abs, moon\",3000.00\n"
"1999,Chevy,\"Venture \"\"Extended Edition\"\"\",\"\",4900.00\n"
"1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\"\",\"\",5000.00\n"
"1996,Jeep,Grand Cherokee,\"MUST SELL!\n\
air, moon roof, loaded\",4799.00\n"
;

Then, I wanted to be able to read in the data like this:

std::istringstream ss(input);
std::string title[5];
int year;
std::string make, model, desc;
float price;
csv_istream(ss)
    >> title[0] >> title[1] >> title[2] >> title[3] >> title[4];
while (csv_istream(ss)
       >> year >> make >> model >> desc >> price) {
    //...do something with the record...
}

This was the solution I ended up with.

struct csv_istream {
    std::istream &is_;
    csv_istream (std::istream &is) : is_(is) {}
    void scan_ws () const {
        while (is_.good()) {
            int c = is_.peek();
            if (c != ' ' && c != '\t') break;
            is_.get();
        }
    }
    void scan (std::string *s = 0) const {
        std::string ws;
        int c = is_.get();
        if (is_.good()) {
            do {
                if (c == ',' || c == '\n') break;
                if (s) {
                    ws += c;
                    if (c != ' ' && c != '\t') {
                        *s += ws;
                        ws.clear();
                    }
                }
                c = is_.get();
            } while (is_.good());
            if (is_.eof()) is_.clear();
        }
    }
    template <typename T, bool> struct set_value {
        void operator () (std::string in, T &v) const {
            std::istringstream(in) >> v;
        }
    };
    template <typename T> struct set_value<T, true> {
        template <bool SIGNED> void convert (std::string in, T &v) const {
            if (SIGNED) v = ::strtoll(in.c_str(), 0, 0);
            else v = ::strtoull(in.c_str(), 0, 0);
        }
        void operator () (std::string in, T &v) const {
            convert<is_signed_int<T>::val>(in, v);
        }
    };
    template <typename T> const csv_istream & operator >> (T &v) const {
        std::string tmp;
        scan(&tmp);
        set_value<T, is_int<T>::val>()(tmp, v);
        return *this;
    }
    const csv_istream & operator >> (std::string &v) const {
        v.clear();
        scan_ws();
        if (is_.peek() != '"') scan(&v);
        else {
            std::string tmp;
            is_.get();
            std::getline(is_, tmp, '"');
            while (is_.peek() == '"') {
                v += tmp;
                v += is_.get();
                std::getline(is_, tmp, '"');
            }
            v += tmp;
            scan();
        }
        return *this;
    }
    template <typename T>
    const csv_istream & operator >> (T &(*manip)(T &)) const {
        is_ >> manip;
        return *this;
    }
    operator bool () const { return !is_.fail(); }
};

With the following helpers that may be simplified by the new integral traits templates in C++11:

template <typename T> struct is_signed_int { enum { val = false }; };
template <> struct is_signed_int<short> { enum { val = true}; };
template <> struct is_signed_int<int> { enum { val = true}; };
template <> struct is_signed_int<long> { enum { val = true}; };
template <> struct is_signed_int<long long> { enum { val = true}; };

template <typename T> struct is_unsigned_int { enum { val = false }; };
template <> struct is_unsigned_int<unsigned short> { enum { val = true}; };
template <> struct is_unsigned_int<unsigned int> { enum { val = true}; };
template <> struct is_unsigned_int<unsigned long> { enum { val = true}; };
template <> struct is_unsigned_int<unsigned long long> { enum { val = true}; };

template <typename T> struct is_int {
    enum { val = (is_signed_int<T>::val || is_unsigned_int<T>::val) };
};

Try it online!

How to see if an object is an array without using reflection?

You can use instanceof.

JLS 15.20.2 Type Comparison Operator instanceof

 RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

That means you can do something like this:

Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"        

You'd have to check if the object is an instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], or Object[], if you want to detect all array types.

Also, an int[][] is an instanceof Object[], so depending on how you want to handle nested arrays, it can get complicated.

For the toString, java.util.Arrays has a toString(int[]) and other overloads you can use. It also has deepToString(Object[]) for nested arrays.

public String toString(Object arr) {
   if (arr instanceof int[]) {
      return Arrays.toString((int[]) arr);
   } else //...
}

It's going to be very repetitive (but even java.util.Arrays is very repetitive), but that's the way it is in Java with arrays.

See also

Re-render React component when prop changes

You could use KEY unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.

JQuery html() vs. innerHTML

innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.

Firebug-like debugger for Google Chrome

If you are using Chromium on Ubuntu using the nightly ppa, then you should have the chromium-browser-inspector

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

So, you have a

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
java.net.ConnectException: Connection refused

I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:

If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:

  1. IP address or hostname in JDBC URL is wrong.
  2. Hostname in JDBC URL is not recognized by local DNS server.
  3. Port number is missing or wrong in JDBC URL.
  4. DB server is down.
  5. DB server doesn't accept TCP/IP connections.
  6. DB server has run out of connections.
  7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

To solve the one or the other, follow the following advices:

  1. Verify and test them with ping.
  2. Refresh DNS or use IP address in JDBC URL instead.
  3. Verify it based on my.cnf of MySQL DB.
  4. Start the DB.
  5. Verify if mysqld is started without the --skip-networking option.
  6. Restart the DB and fix your code accordingly that it closes connections in finally.
  7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

See also:

How to get the last five characters of a string using Substring() in C#?

If your input string could be less than five characters long then you should be aware that string.Substring will throw an ArgumentOutOfRangeException if the startIndex argument is negative.

To solve this potential problem you can use the following code:

string sub = input.Substring(Math.Max(0, input.Length - 5));

Or more explicitly:

public static string Right(string input, int length)
{
    if (length >= input.Length)
    {
        return input;
    }
    else
    {
        return input.Substring(input.Length - length);
    }
}

How to get child process from parent process

I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.

function getcpid() {
    cpids=`pgrep -P $1|xargs`
#    echo "cpids=$cpids"
    for cpid in $cpids;
    do
        echo "$cpid"
        getcpid $cpid
    done
}

getcpid $1

What's the "Content-Length" field in HTTP header?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 1024

Applications SHOULD use this field to indicate the transfer-length of the message-body.

In PHP you would use something like this.

header("Content-Length: ".filesize($filename));

In case of "Content-Type: application/x-www-form-urlencoded" the encoded data is sent to the processing agent designated so you can set the length or size of the data you are going to post.

How to show "Done" button on iPhone number pad

Swift 2.2 / I used Dx_'s answer. However, I wanted this functionality on all keyboards. So in my base class I put the code:

func addDoneButtonForTextFields(views: [UIView]) {
    for view in views {
        if let textField = view as? UITextField {
            let doneToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 50))

            let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            let done = UIBarButtonItem(title: "Done", style: .Done, target: self, action: #selector(dismissKeyboard))

            var items = [UIBarButtonItem]()
            items.append(flexSpace)
            items.append(done)

            doneToolbar.items = items
            doneToolbar.sizeToFit()

            textField.inputAccessoryView = doneToolbar
        } else {
            addDoneButtonForTextFields(view.subviews)
        }
    }
}

func dismissKeyboard() {
    dismissKeyboardForTextFields(self.view.subviews)
}

func dismissKeyboardForTextFields(views: [UIView]) {
    for view in views {
        if let textField = view as? UITextField {
            textField.resignFirstResponder()
        } else {
            dismissKeyboardForTextFields(view.subviews)
        }
    }
}

Then just call addDoneButtonForTextFields on self.view.subviews in viewDidLoad (or willDisplayCell if using a table view) to add the Done button to all keyboards.

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to know the version of pip itself

Just for completeness:

pip -V

pip --version

pip list and inside the list you'll find also pip with its version.

How do I convert strings between uppercase and lowercase in Java?

Assuming that all characters are alphabetic, you can do this:

From lowercase to uppercase:

// Uppercase letters. 
class UpperCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('a' + i);
      System.out.print(ch); 

      // This statement turns off the 6th bit.   
      ch = (char) ((int) ch & 65503); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

From uppercase to lowercase:

// Lowercase letters. 
class LowerCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('A' + i);
      System.out.print(ch);
      ch = (char) ((int) ch | 32); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

Angular2 set value for formGroup

As pointed out in comments, this feature wasn't supported at the time this question was asked. This issue has been resolved in angular 2 rc5

How do I write stderr to a file while using "tee" with a pipe?

The following will work for KornShell(ksh) where the process substitution is not available,

# create a combined(stdin and stdout) collector
exec 3 <> combined.log

# stream stderr instead of stdout to tee, while draining all stdout to the collector
./aaa.sh 2>&1 1>&3 | tee -a stderr.log 1>&3

# cleanup collector
exec 3>&-

The real trick here, is the sequence of the 2>&1 1>&3 which in our case redirects the stderr to stdout and redirects the stdout to descriptor 3. At this point the stderr and stdout are not combined yet.

In effect, the stderr(as stdin) is passed to tee where it logs to stderr.log and also redirects to descriptor 3.

And descriptor 3 is logging it to combined.log all the time. So the combined.log contains both stdout and stderr.

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

What does the Java assert keyword do, and when should it be used?

Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).

An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext() is called before next() in an Iterator).

Bootstrap Element 100% Width

The container class is intentionally not 100% width. It is different fixed widths depending on the width of the viewport.

If you want to work with the full width of the screen, use .container-fluid:

Bootstrap 3:

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-6"></div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
      <div class="col-lg-8"></div>
      <div class="col-lg-4"></div>
    </div>
    <div class="row">
      <div class="col-lg-12"></div>
    </div>
  </div>
</body>

Bootstrap 2:

<body>
  <div class="row">
    <div class="span6"></div>
    <div class="span6"></div>
  </div>
  <div class="row">
    <div class="span8"></div>
    <div class="span4"></div>
  </div>
  <div class="row">
    <div class="span12"></div>
  </div>
</body>

Checking if type == list in python

You should try using isinstance()

if isinstance(object, list):
       ## DO what you want

In your case

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

To elaborate:

x = [1,2,3]
if type(x) == list():
    print "This wont work"
if type(x) == list:                  ## one of the way to see if it's list
    print "this will work"           
if type(x) == type(list()):
    print "lets see if this works"
if isinstance(x, list):              ## most preferred way to check if it's list
    print "This should work just fine"

The difference between isinstance() and type() though both seems to do the same job is that isinstance() checks for subclasses in addition, while type() doesn’t.

Autoplay an audio with HTML5 embed tag while the player is invisible

<div id="music">
<audio autoplay>
  <source src="kooche.mp3" type="audio/mpeg">
  <p>If you can read this, your browser does not support the audio element.</p>
</audio>
</div>

And the css:

#music {
  display:none;
}

Like suggested above, you probably should have the controls available in some form. Maybe use a toggle link/checkbox that slides the controls in via jquery.

Source: HTML5 Audio Autoplay

PHP Get Highest Value from Array

asort() is the way to go:

$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
asort($array);
$highestValue       = end($array);
$keyForHighestValue = key($array);

DataRow: Select cell value by a given column name

Be careful on datatype. If not match it will throw an error.

var fieldName = dataRow.Field<DataType>("fieldName");

AWS : The config profile (MyName) could not be found

Use as follows

[profilename]
region=us-east-1
output=text

Example cmd

aws --profile myname CMD opts

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

Disable a Button

Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

var appMode = 0

@IBAction func mySegue(_ sender: UIButton) {

    if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
        let conflictingAction = sender as UIButton
        conflictingAction.isEnabled = false
    }
}

Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

Use of "global" keyword in Python

The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis.

Consider this, for example:

value = 42

def doit():
    print value
    value = 0

doit()
print value

You can probably guess that the value = 0 statement will be assigning to a local variable and not affect the value of the same variable declared outside the doit() function. You may be more surprised to discover that the code above won't run. The statement print value inside the function produces an UnboundLocalError.

The reason is that Python has noticed that, elsewhere in the function, you assign the name value, and also value is nowhere declared global. That makes it a local variable. But when you try to print it, the local name hasn't been defined yet. Python in this case does not fall back to looking for the name as a global variable, as some other languages do. Essentially, you cannot access a global variable if you have defined a local variable of the same name anywhere in the function.

Full-screen responsive background image

I personally dont recommend to apply style on HTML tag, it might have after effects somewhere later part of the development.

so i personally suggest to apply background-image property to the body tag.

body{
    width:100%;
    height: 100%;
    background-image: url("./images/bg.jpg");
    background-position: center;
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

This simple trick solved my problem. this works for most of the screens larger/smaller ones.

there are so many ways to do it, i found this the simpler with minimum after effects

Best way to run scheduled tasks

One option would be to set up a windows service and get that to call your scheduled task.

In winforms I've used Timers put don't think this would work well in ASP.NET

Stop Excel from automatically converting certain text values to dates

(Assuming Excel 2003...)

When using the Text-to-Columns Wizard has, in Step 3 you can dictate the data type for each of the columns. Click on the column in the preview and change the misbehaving column from "General" to "Text."

How to know if docker is already logged in to a docker registry server

For private registries, nothing is shown in docker info. However, the logout command will tell you if you were logged in:

 $ docker logout private.example.com
 Not logged in to private.example.com

(Though this will force you to log in again.)

Linux delete file with size 0

You can use the command find to do this. We can match files with -type f, and match empty files using -size 0. Then we can delete the matches with -delete.

find . -type f -size 0 -delete

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

Just run the contents through parseFloat(). It will return NaN on invalid input.

How to show empty data message in Datatables

I was finding same but lastly i found an answer. I hope this answer help you so much.

when your array is empty then you can send empty array just like

if(!empty($result))
        {
            echo json_encode($result);
        }
        else
        {
            echo json_encode(array('data'=>''));
        }

Thank you

Graphviz's executables are not found (Python 3.4)

To solve this problem,when you install graphviz2.38 successfully, then add your PATH variable to system path.Under System Variables you can click on Path and then clicked Edit and added ;C:\Program Files (x86)\Graphviz2.38\bin to the end of the string and saved.After that,restart your pythonIDE like spyper,then it works well.

Don't forget to close Spyder and then restart.

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

Express: How to pass app-instance to routes from a different file?

If you want to pass an app-instance to others in Node-Typescript :

Option 1: With the help of import (when importing)

//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';

const routing = (app: Application) => {
    app.use('/api/admin/category', categoryRoute)
    app.use('/api/admin/course', courseRoute)
}
export { routing }

Then import it and pass app:

import express, { Application } from 'express';

const app: Application = express();
import('./routes').then(m => m.routing(app))

Option 2: With the help of class

// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';


const app: Application = express();
const rotues = new Routes(app)
...

Here we will access the app in the constructor of Routes Class

// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';

class Routes {
    constructor(private app: Application) {
        this.apply();
    }

    private apply(): void {
       this.app.use('/api/admin/category', categoryRoute)
       this.app.use('/api/admin/course', courseRoute)
    }
}

export { Routes }

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

How to add default value for html <textarea>?

A few notes and clarifications:

  • placeholder='' inserts your text, but it is greyed out (in a tool-tip style format) and the moment the field is clicked, your text is replaced by an empty text field.

  • value='' is not a <textarea> attribute, and only works for <input> tags, ie, <input type='text'>, etc. I don't know why the creators of HTML5 decided not to incorporate that, but that's the way it is for now.

  • The best method for inserting text into <textarea> elements has been outlined correctly here as: <textarea> Desired text to be inserted into the field upon page load </textarea> When the user clicks the field, they can edit the text and it remains in the field (unlike placeholder='').

  • Note: If you insert text between the <textarea> and </textarea> tags, you cannot use placeholder='' as it will be overwritten by your inserted text.

Clear text field value in JQuery

    First Name: <input type="text" autocomplete="off" name="input1"/>
    <br/>
    Last Name: <input type="text" autocomplete="off" name="input2"/>
    <br/>
    <input type="submit" value="Submit" />
</form>

Display image as grayscale using matplotlib

try this:

import pylab
from scipy import misc

pylab.imshow(misc.lena(),cmap=pylab.gray())
pylab.show()

Data truncated for column?

By issuing this statement:

ALTER TABLES call MODIFY incoming_Cid CHAR;

... you omitted the length parameter. Your query was therefore equivalent to:

ALTER TABLE calls MODIFY incoming_Cid CHAR(1);

You must specify the field size for sizes larger than 1:

ALTER TABLE calls MODIFY incoming_Cid CHAR(34);

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

Are PHP Variables passed by value or by reference?

class Holder
{
    private $value;

    public function __construct( $value )
    {
        $this->value = $value;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValue( $value )
    {
        return $this->value = $value;
    }
}

class Swap
{       
    public function SwapObjects( Holder $x, Holder $y )
    {
        $tmp = $x;

        $x = $y;

        $y = $tmp;
    }

    public function SwapValues( Holder $x, Holder $y )
    {
        $tmp = $x->getValue();

        $x->setValue($y->getValue());

        $y->setValue($tmp);
    }
}


$a1 = new Holder('a');

$b1 = new Holder('b');



$a2 = new Holder('a');

$b2 = new Holder('b');


Swap::SwapValues($a1, $b1);

Swap::SwapObjects($a2, $b2);



echo 'SwapValues: ' . $a2->getValue() . ", " . $b2->getValue() . "<br>";

echo 'SwapObjects: ' . $a1->getValue() . ", " . $b1->getValue() . "<br>";

Attributes are still modifiable when not passed by reference so beware.

Output:

SwapObjects: b, a SwapValues: a, b

jQuery: Get selected element tag name

You can use the DOM's nodeName property:

$(...)[0].nodeName

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

Get JSON object from URL

$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:

ini_set("allow_url_fopen", 1);

You can also use curl to get the url. To use curl, you can use the example found here:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;

How to add external library in IntelliJ IDEA?

Easier procedure on latest versions:

  • Copy jar to libs directory in the app (you can create the directory it if not there)
  • Refresh project so libs show up in the structure (right click on project top level, refresh/synchronize)
  • Expand libs and right click on the jar
  • Select "Add as Library"

Done

Most Useful Attributes

I like [DebuggerStepThrough] from System.Diagnostics.

It's very handy for avoiding stepping into those one-line do-nothing methods or properties (if you're forced to work in an early .Net without automatic properties). Put the attribute on a short method or the getter or setter of a property, and you'll fly right by even when hitting "step into" in the debugger.

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

How do I export (and then import) a Subversion repository?

Excerpt from my Blog-Note-to-myself:

Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.

Commands for Unix-like systems (from terminal):

svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp

Commands for Microsoft Windows systems (from cmd shell):

svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump

Clone contents of a GitHub repository (without the folder itself)

to clone git repo into the current and empty folder (no git init) and if you do not use ssh:

git clone https://github.com/accountName/repoName.git .

GIT vs. Perforce- Two VCS will enter... one will leave

The Perl 5 interpreter source code is currently going through the throes of converting from Perforce to git. Maybe Sam Vilain’s git-p4raw importer is of interest.

In any case, one of the major wins you’re going to have over every centralised VCS and most distributed ones also is raw, blistering speed. You can’t imagine how liberating it is to have the entire project history at hand, mere fractions of fractions of a second away, until you have experienced it. Even generating a commit log of the whole project history that includes a full diff for each commit can be measured in fractions of a second. Git is so fast your hat will fly off. VCSs that have to roundtrip over the network simply have no chance of competing, not even over a Gigabit Ethernet link.

Also, git makes it very easy to be carefully selective when making commits, thereby allowing changes in your working copy (or even within a single file) to be spread out over multiple commits – and across different branches if you need that. This allows you to make fewer mental notes while working – you don’t need to plan out your work so carefully, deciding up front what set of changes you’ll commit and making sure to postpone anything else. You can just make any changes you want as they occur to you, and still untangle them – nearly always quite easily – when it’s time to commit. The stash can be a very big help here.

I have found that together, these facts cause me to naturally make many more and much more focused commits than before I used git. This in turn not only makes your history generally more useful, but is particularly beneficial for value-add tools such as git bisect.

I’m sure there are more things I can’t think of right now. One problem with the proposition of selling your team on git is that many benefits are interrelated and play off each other, as I hinted at above, such that it is hard to simply look at a list of features and benefits of git and infer how they are going to change your workflow, and which changes are going to be bonafide improvements. You need to take this into account, and you also need to explicitly point it out.

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

How to delete and update a record in Hive

UPDATE or DELETE a record isn't allowed in Hive, but INSERT INTO is acceptable.
A snippet from Hadoop: The Definitive Guide(3rd edition):

Updates, transactions, and indexes are mainstays of traditional databases. Yet, until recently, these features have not been considered a part of Hive's feature set. This is because Hive was built to operate over HDFS data using MapReduce, where full-table scans are the norm and a table update is achieved by transforming the data into a new table. For a data warehousing application that runs over large portions of the dataset, this works well.

Hive doesn't support updates (or deletes), but it does support INSERT INTO, so it is possible to add new rows to an existing table.

Export DataTable to Excel with Open Xml SDK in c#

I wrote this quick example. It works for me. I only tested it with one dataset with one table inside, but I guess that may be enough for you.

Take into consideration that I treated all cells as String (not even SharedStrings). If you want to use SharedStrings you might need to tweak my sample a bit.

Edit: To make this work it is necessary to add WindowsBase and DocumentFormat.OpenXml references to project.

Enjoy,

private void ExportDataSet(DataSet ds, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                foreach (System.Data.DataTable table in ds.Tables) {

                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List<String> columns = new List<string>();
                    foreach (System.Data.DataColumn column in table.Columns) {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                }
            }
        }

pandas groupby sort within groups

Try this Instead

simple way to do 'groupby' and sorting in descending order

df.groupby(['companyName'])['overallRating'].sum().sort_values(ascending=False).head(20)

How to make the main content div fill height of screen with css

No Javascript, no absolute positioning and no fixed heights are required for this one.

Here's an all CSS / CSS only method which doesn't require fixed heights or absolute positioning:

CSS

.container { 
  display: table;
}
.content { 
  display: table-row; 
  height: 100%; 
}
.content-body { 
  display: table-cell;
}

HTML

<div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <p>This is the content.</p>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div>

See it in action here: http://jsfiddle.net/AzLQY/

The benefit of this method is that the footer and header can grow to match their content and the body will automatically adjust itself. You can also choose to limit their height with css.

Change default icon

I had the same problem. I followed the steps to change the icon but it always installed the default icon.

FIX: After I did the above, I rebuilt the solution by going to build on the Visual Studio menu bar and clicking on 'rebuild solution' and it worked!

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

Check if a row exists, otherwise insert

This is something I just recently had to do:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[cjso_UpdateCustomerLogin]
    (
      @CustomerID AS INT,
      @UserName AS VARCHAR(25),
      @Password AS BINARY(16)
    )
AS 
    BEGIN
        IF ISNULL((SELECT CustomerID FROM tblOnline_CustomerAccount WHERE CustomerID = @CustomerID), 0) = 0
        BEGIN
            INSERT INTO [tblOnline_CustomerAccount] (
                [CustomerID],
                [UserName],
                [Password],
                [LastLogin]
            ) VALUES ( 
                /* CustomerID - int */ @CustomerID,
                /* UserName - varchar(25) */ @UserName,
                /* Password - binary(16) */ @Password,
                /* LastLogin - datetime */ NULL ) 
        END
        ELSE
        BEGIN
            UPDATE  [tblOnline_CustomerAccount]
            SET     UserName = @UserName,
                    Password = @Password
            WHERE   CustomerID = @CustomerID    
        END

    END

Likelihood of collision using most significant bits of a UUID in Java

According to the documentation, the static method UUID.randomUUID() generates a type 4 UUID.

This means that six bits are used for some type information and the remaining 122 bits are assigned randomly.

The six non-random bits are distributed with four in the most significant half of the UUID and two in the least significant half. So the most significant half of your UUID contains 60 bits of randomness, which means you on average need to generate 2^30 UUIDs to get a collision (compared to 2^61 for the full UUID).

So I would say that you are rather safe. Note, however that this is absolutely not true for other types of UUIDs, as Carl Seleborg mentions.

Incidentally, you would be slightly better off by using the least significant half of the UUID (or just generating a random long using SecureRandom).

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:

Cannot create an instance of OLE DB provider "(OLEDB provider name)"...

The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."

The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.

This MSDN blog post describes the reason:

MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.

The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.

While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,

Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.

The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.

C# How to determine if a number is a multiple of another?

Try

public bool IsDivisible(int x, int n)
{
   return (x % n) == 0;
}

The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.

For more information, see the % operator on MSDN.

Get installed applications in a system

While the accepted solution works, it is not complete. By far.

If you want to get all the keys, you need to take into consideration 2 more things:

x86 & x64 applications do not have access to the same registry. Basically x86 cannot normally access x64 registry. And some applications only register to the x64 registry.

and

some applications actually install into the CurrentUser registry instead of the LocalMachine

With that in mind, I managed to get ALL installed applications using the following code, WITHOUT using WMI

Here is the code:

List<string> installs = new List<string>();
List<string> keys = new List<string>() {
  @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};

// The RegistryView.Registry64 forces the application to open the registry as x64 even if the application is compiled as x86 
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64), keys, installs);
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64), keys, installs);

installs = installs.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
installs.Sort(); // The list of ALL installed applications



private void FindInstalls(RegistryKey regKey, List<string> keys, List<string> installed)
{
  foreach (string key in keys)
  {
    using (RegistryKey rk = regKey.OpenSubKey(key))
    {
      if (rk == null)
      {
        continue;
      }
      foreach (string skName in rk.GetSubKeyNames())
      {
        using (RegistryKey sk = rk.OpenSubKey(skName))
        {
          try
          {
            installed.Add(Convert.ToString(sk.GetValue("DisplayName")));
          }
          catch (Exception ex)
          { }
        }
      }
    }
  }
}

Transport endpoint is not connected

I get this error from the sshfs command from Fedora 17 linux to debian linux on the Mindstorms EV3 brick over the LAN and through a wireless connection.

Bash command:

el@defiant /mnt $ sshfs [email protected]:/root -p 22 /mnt/ev3
fuse: bad mount point `/mnt/ev3': Transport endpoint is not connected

This is remedied with the following command and trying again:

fusermount -u /mnt/ev3

These additional sshfs options prevent the above error from concurring:

sudo sshfs -d -o allow_other -o reconnect -o ServerAliveInterval=15 [email protected]:/var/lib/redmine/plugins /mnt -p 12345 -C

In order to use allow_other above, you need to uncomment the last line in /etc/fuse.conf:

# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#
user_allow_other

Source: http://slopjong.de/2013/04/26/sshfs-transport-endpoint-is-not-connected/

How to show matplotlib plots in python

You must use plt.show() at the end in order to see the plot

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

Debug JavaScript in Eclipse

It's possible to debug JavaScript by setting breakpoints in Eclipse using the AJAX Tools Framework.

How do I get the day month and year from a Windows cmd.exe script?

This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

iOS 7 - Failing to instantiate default view controller

First click on the View Controller in the right hand side Utilities bar. Next select the Attributes Inspector and make sure that under the View Controller section the 'Is Initial View Controller' checkbox is checked!

VB.Net Properties - Public Get, Private Set

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

In my case, that support libraries for ConstraintLayout were installed, but I was adding the incorrect version of ConstraintLayout Library in my build.gradle file. In order to see what version have you installed, go to Preferences > Appearance & Behavior > System Settings > Android SDK. Now, click on SDK Tools tab in right pane. Check Show Package Details and take note of the version.

enter image description here

Finally you can add the correct version in the build.gradle file

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
    testCompile 'junit:junit:4.12'
}

How do I set hostname in docker-compose?

This seems to work correctly. If I put your config into a file:

$ cat > compose.yml <<EOF
dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock
EOF

And then bring things up:

$ docker-compose -f compose.yml up
Creating tmp_dns_1...
Attaching to tmp_dns_1
dns_1 | 2015-04-28T17:47:45.423387 [dockerdns] table.add tmp_dns_1.docker -> 172.17.0.5

And then check the hostname inside the container, everything seems to be fine:

$ docker exec -it stack_dns_1 hostname
affy.affy.com

How to hide close button in WPF window?

This doesn't hide the button but will prevent the user from moving forward by shutting down the window.

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{            
    if (e.Cancel == false)
    {
        Application.Current.Shutdown();
    }
}

Creating a file name as a timestamp in a batch job

Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):

@echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html

REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
   for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
      set dow=%%i
      set %%a=%%j
      set %%b=%%k
      set %%c=%%l
      set hh=%%m
      set min=%%n
      set ss=%%o
   )
)

REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss%

I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:

setlocal

@echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err

:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : Start === >> %ERRLOG%

:: Perform some long running action and log errors to ERRLOG.

:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : End === >> %ERRLOG%

As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.

Error You must specify a region when running command aws ecs list-container-instances

"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.

For the CLI, either set the AWS_DEFAULT_REGION environment variable. e.g.

export AWS_DEFAULT_REGION=us-east-1

or add it into the command (you will need this every time you use a region-specific command)

AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default

or set it in the CLI configuration file: ~/.aws/config

[default]
region=us-east-1

or pass/override it with the CLI call:

aws ecs list-container-instances --cluster default --region us-east-1

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

GCC -fPIC option

The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.


There are two commonly used methods for dealing with this problem:

1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.

2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.


The name "position-independent code" actually implies following:

  • The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.

  • The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.

  • All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.


This so-called symbol interposition is intended to mimic the behavior of static libraries.

A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.

p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.

You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf

importing pyspark in python shell

For a Spark execution in pyspark two components are required to work together:

  • pyspark python package
  • Spark instance in a JVM

When launching things with spark-submit or pyspark, these scripts will take care of both, i.e. they set up your PYTHONPATH, PATH, etc, so that your script can find pyspark, and they also start the spark instance, configuring according to your params, e.g. --master X

Alternatively, it is possible to bypass these scripts and run your spark application directly in the python interpreter likepython myscript.py. This is especially interesting when spark scripts start to become more complex and eventually receive their own args.

  1. Ensure the pyspark package can be found by the Python interpreter. As already discussed either add the spark/python dir to PYTHONPATH or directly install pyspark using pip install.
  2. Set the parameters of spark instance from your script (those that used to be passed to pyspark).
    • For spark configurations as you'd normally set with --conf they are defined with a config object (or string configs) in SparkSession.builder.config
    • For main options (like --master, or --driver-mem) for the moment you can set them by writing to the PYSPARK_SUBMIT_ARGS environment variable. To make things cleaner and safer you can set it from within Python itself, and spark will read it when starting.
  3. Start the instance, which just requires you to call getOrCreate() from the builder object.

Your script can therefore have something like this:

from pyspark.sql import SparkSession

if __name__ == "__main__":
    if spark_main_opts:
        # Set main options, e.g. "--master local[4]"
        os.environ['PYSPARK_SUBMIT_ARGS'] = spark_main_opts + " pyspark-shell"

    # Set spark config
    spark = (SparkSession.builder
             .config("spark.checkpoint.compress", True)
             .config("spark.jars.packages", "graphframes:graphframes:0.5.0-spark2.1-s_2.11")
             .getOrCreate())

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.

An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.

See also:

C function that counts lines in file

You're opening a file, then passing the file pointer to a function that only wants a file name to open the file itself. You can simplify your call to;

void main(void)
{
  printf("LINES: %d\n",countlines("Test.txt"));
}

EDIT: You're changing the question around so it's very hard to answer; at first you got your change to main() wrong, you forgot that the first parameter is argc, so it crashed. Now you have the problem of;

if (fp == NULL);   // <-- note the extra semicolon that is the only thing 
                   //     that runs conditionally on the if 
  return 0;        // Always runs and returns 0

which will always return 0. Remove that extra semicolon, and you should get a reasonable count.

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

How can you use optional parameters in C#?

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

Optional Callback parameter:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Replacing server=localhost with server=.\SQLEXPRESS might do the job.

Type.GetType("namespace.a.b.ClassName") returns null

Try using the full type name that includes the assembly info, for example:

string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
Type myClassType = Type.GetType(typeName);

I had the same situation when I was using only the the namesspace.classname to get the type of a class in a different assembly and it would not work. Only worked when I included the assembly info in my type string as shown above.

Difference between HashSet and HashMap?

HashMaps allow one null key and null values. They are not synchronized, which increases efficiency. If it is required, you can make them synchronized using Collections.SynchronizedMap()

Hashtables don't allow null keys and are synchronized.

Get the index of a certain value in an array in PHP

If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;

If you want all (or a lot of them), a loop will prob do you better:

foreach ($list as $key => $value) {
    echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "

Swift: Display HTML data in a label or textView

IF YOU HAVE A STRING WITH HTML CODE INSIDE YOU CAN USE:

extension String {
var utfData: Data? {
        return self.data(using: .utf8)
    }

    var htmlAttributedString: NSAttributedString? {
        guard let data = self.utfData else {
            return nil
        }
        do {
            return try NSAttributedString(data: data,
                                          options: [
                                            .documentType: NSAttributedString.DocumentType.html,
                                            .characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
        } catch {
            print(error.localizedDescription)
            return nil
        }
    }

    var htmlString: String {
        return htmlAttributedString?.string ?? self 
    }
}

AND IN YOUR CODE YOU USE:

label.text = "something".htmlString

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Get battery level and state in Android

You don't have to register an actual BroadcastReceiver as Android's BatteryManager is using a sticky Intent:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

return (int)(batteryPct*100);

This is from the official docs over at https://developer.android.com/training/monitoring-device-state/battery-monitoring.html.

Set Colorbar Range in matplotlib

Using vmin and vmax forces the range for the colors. Here's an example:

enter image description here

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

How to create a number picker dialog?

To show NumberPicker in AlertDialog use this code :

final AlertDialog.Builder d = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.number_picker_dialog, null);
d.setTitle("Title");
d.setMessage("Message");
d.setView(dialogView);
final NumberPicker numberPicker = (NumberPicker) dialogView.findViewById(R.id.dialog_number_picker);
numberPicker.setMaxValue(50);
numberPicker.setMinValue(1);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i1) {
        Log.d(TAG, "onValueChange: ");
    }
});
d.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        Log.d(TAG, "onClick: " + numberPicker.getValue());
    }
});
d.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    }
});
AlertDialog alertDialog = d.create();
alertDialog.show();

number_picker_dialog.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">

<NumberPicker
    android:id="@+id/dialog_number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

how to save and read array of array in NSUserdefaults in swift?

The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults. For those people I will add a few common examples.

String array

Save array

let array = ["horse", "cow", "camel", "sheep", "goat"]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")

Retrieve array

let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()

Int array

Save array

let array = [15, 33, 36, 723, 77, 4]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray")  as? [Int] ?? [Int]()

Bool array

Save array

let array = [true, true, false, true, false]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray")  as? [Bool] ?? [Bool]()

Date array

Save array

let array = [Date(), Date(), Date(), Date()]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray")  as? [Date] ?? [Date]()

Object array

Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults. See the following links for how to do it.

Notes

  • The nil coalescing operator (??) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ?? operator will be used instead.
  • As you can see, the basic setup was the same for Int, Bool, and Date. I also tested it with Double. As far as I know, anything that you can save in a property list will work like this.

Table Naming Dilemma: Singular vs. Plural Names

Guidelines are really there as just that. It's not "set in stone" that's why you have the option of being able to ignore them.

I would say that it's more logically intuitive to have pluralized table names. A table is a collection of entity after all. In addition to other alternatives mentioned I commonly see prefixes on table names...

  • tblUser
  • tblThis
  • tblThat
  • tblTheOther

I'm not suggesting this is the way to go, I also see spaces used a LOT in table names which I abhor. I've even come across field names with idiotic characters like ? as if to say this field answers a question.

jQuery UI dialog box not positioned center screen

$('#dlg').dialog({
    title: 'My Dialog',
    left: (parseInt(jQuery(window).width())-1200)/2,
    top:(parseInt(jQuery(window).height())-720)/2,
    width: 1200,
    height: 720,
    closed: false,
    cache: false,
    modal: true,
    toolbar:'#dlg-toolbar'
});

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Get and Set Screen Resolution

If you want to collect screen resolution you can run the following code within a WPF window (the window is what the this would refer to):

System.Windows.Media.Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
Double dpiX = m.M11 * 96;
Double dpiY = m.M22 * 96;

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

How can I quickly sum all numbers in a file?

Just for fun, lets do it with PDL, Perl's array math engine!

perl -MPDL -E 'say rcols(shift)->sum' datafile

rcols reads columns into a matrix (1D in this case) and sum (surprise) sums all the element of the matrix.

How to make div appear in front of another?

I think you're missing something.

http://jsfiddle.net/ZNtKj/

<ul>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:black;">
  </div>
 </li>
</ul>
<ul>
 <li style="height:100px;">
  <div style="height:500px; background-color:red;">
  </div>
 </li>
</ul>

In FF4, this displays a 100px black bar, followed by a 500px red block.

A little bit different example:

http://jsfiddle.net/ZNtKj/1/

<ul>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:black;">
  </div>
 </li>
</ul>
<ul>
 <li style="height:100px;">
  <div style="height:500px; background-color:red;">
  </div>
 </li>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:blue;">
  </div>
 </li>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:green;">
  </div>
 </li>
</ul>

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

{ text-decoration: none !important}


EDIT 1:

For you example only a{text-decoration: none} will works

You can use a class not to interfere with the default behaviour of <a> tags.

<a href="#" class="nounderline">
  <div class="btn-group">
    <button class="btn">Text</button>
    <button class="btn">Text</button>
  </div>
</a>

CSS:

.nounderline {
  text-decoration: none !important
}

How to store arbitrary data for some HTML tags

If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.

To store something:

$('#myElId').data('nameYourData', { foo: 'bar' });

To retrieve data:

var myData = $('#myElId').data('nameYourData');

That is all that there is to it but take a look at the jQuery documentation for more info/examples.

How to use Angular4 to set focus by element id

Here is a directive that you can use in any component:

import { NgZone, Directive, ElementRef, AfterContentInit, Renderer2 } from '@angular/core';

@Directive({
    selector: '[appFocus]'
})
export class FocusDirective implements AfterContentInit {
    constructor(private el: ElementRef, private zone: NgZone, private renderer: Renderer2) {}

    ngAfterContentInit() {
        this.zone.runOutsideAngular(() => setTimeout(() => {
            this.renderer.selectRootElement(this.el.nativeElement).focus();
        }, 0));
    }
}

Use:

<input type="text" appFocus>

How to quickly and conveniently disable all console.log statements in my code?

One liner just set devMode true/false;

console.log = devMode ? console.log : () => { };

How to check if array is not empty?

len(self.table) checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):

Python 2:

if len(self.table) > 0:
    #Do code here

Python 3:

if(len(self.table) > 0):
    #Do code here

It's also possible to use

if self.table:
    #Execute if self.table is not empty
else:
    #Execute if self.table is empty

to see if the list is not empty.

How to get address of a pointer in c/c++?

To get the address of p do:

int **pp = &p;

and you can go on:

int ***ppp = &pp;
int ****pppp = &ppp;
...

or, only in C++11, you can do:

auto pp = std::addressof(p);

To print the address in C, most compilers support %p, so you can simply do:

printf("addr: %p", pp);

otherwise you need to cast it (assuming a 32 bit platform)

printf("addr: 0x%u", (unsigned)pp);

In C++ you can do:

cout << "addr: " << pp;

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

Get HTML5 localStorage keys

I like to create an easily visible object out of it like this.

Object.keys(localStorage).reduce(function(obj, str) { 
    obj[str] = localStorage.getItem(str); 
    return obj
}, {});

I do a similar thing with cookies as well.

document.cookie.split(';').reduce(function(obj, str){ 
    var s = str.split('='); 
    obj[s[0].trim()] = s[1];
    return obj;
}, {});

How to replace � in a string

That's the Unicode Replacement Character, \uFFFD. (info)

Something like this should work:

String strImport = "For some reason my ?double quotes? were lost.";
strImport = strImport.replaceAll("\uFFFD", "\"");

Finding the Eclipse Version Number

For Eclipse Java EE IDE - Indigo: Help > About Eclipse > Eclipse.org (third from last). In the 'About Eclipse Platform' locate Eclipse Platform and you'll have the version beneath the Version Column. Hope this helps J2EE Indigo Users.

Check if XML Element exists

You can validate that and much more by using an XML schema language, like XSD.

If you mean conditionally, within code, then XPath is worth a look as well.

Convert a bitmap into a byte array

Save the Image to a MemoryStream and then grab the byte array.

http://msdn.microsoft.com/en-us/library/ms142148.aspx

  Byte[] data;

  using (var memoryStream = new MemoryStream())
  {
    image.Save(memoryStream, ImageFormat.Bmp);

    data = memoryStream.ToArray();
  }

How to calculate a logistic sigmoid function in Python?

Good answer from @unwind. It however can't handle extreme negative number (throwing OverflowError).

My improvement:

def sigmoid(x):
    try:
        res = 1 / (1 + math.exp(-x))
    except OverflowError:
        res = 0.0
    return res

SQL select max(date) and corresponding value

There's no easy way to do this, but something like this will work:

SELECT ET.TrainingID, 
  ET.CompletedDate, 
  ET.Notes
FROM 
HR_EmployeeTrainings ET
inner join
(
  select TrainingID, Max(CompletedDate) as CompletedDate
  FROM HR_EmployeeTrainings
  WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
  GROUP BY AvantiRecID, TrainingID  
) ET2 
  on ET.TrainingID = ET2.TrainingID
  and ET.CompletedDate = ET2.CompletedDate

Calculate difference in keys contained in two Python dictionaries

In case you want the difference recursively, I have written a package for python: https://github.com/seperman/deepdiff

Installation

Install from PyPi:

pip install deepdiff

Example usage

Importing

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

Same object returns empty

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}

Type of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

Value of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

Item added and/or removed

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

String difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

String difference 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                '-world!\n'
                                                '-Goodbye!\n'
                                                '+world\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'
                                                    'Goodbye!\n'
                                                    '1\n'
                                                    '2\n'
                                                    'End'}}}

>>> 
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
--- 
+++ 
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
 1
 2
 End

Type change

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

List difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

List difference 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

List difference ignoring order or duplicates: (with the same dictionaries as above)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}

List that contains dictionary:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}

Sets:

>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

Named Tuples:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

Custom objects:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
... 
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> 
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

Object attribute added:

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

How to close an iframe within iframe itself

None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.

I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.

Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage

All these steps are on the GitHub link:

1- You have to inject a JS file on the parent page.

2- In this file injected on the parent, add a window event listner

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

This listener will handle the close and any other event you wish

3- Inside the Iframe page you send the close command via postMessage:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!

Hope it helps,

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

How to import Swagger APIs into Postman?

The accepted answer is correct but I will rewrite complete steps for java.

I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.

Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Step 2: Add configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
      public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
              DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());

    @Bean
    public Docket api() {
        Set<String> producesAndConsumes = new HashSet<>();
        producesAndConsumes.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(producesAndConsumes)
                .consumes(producesAndConsumes);

    }
}

Step 3: Setup complete and now you need to document APIs in controllers

    @ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @GetMapping(path = "/articles/users/{userId}")
    public List<Article> getArticlesByUser() {
       // Do your code
    }

Usage:

You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.

enter image description here

Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.

enter image description here

how to return a char array from a function in C

Daniel is right: http://ideone.com/kgbo1C#view_edit_box

Change

test=substring(i,j,*s);

to

test=substring(i,j,s);  

Also, you need to forward declare substring:

char *substring(int i,int j,char *ch);

int main // ...

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I think adding try/catch for every SaveChanges() operation is not a good practice, it's better to centralize this :

Add this class to the main DbContext class :

public override int SaveChanges()
{
    try
    {
        return base.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
        throw new DbEntityValidationException(errorMessages);
    }
}

This will overwrite your context's SaveChanges() method and you'll get a comma separated list containing all the entity validation errors.

this also can improved, to log errors in production env, instead of just throwing an error.

hope this is helpful.

Same Navigation Drawer in different Activities

update this code in baseactivity. and dont forget to include drawer_list_header in your activity xml.

super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.drawer_list_header);

and dont use request() in your activity. but still the drawer is not visible on clicking image..and by dragging it will visible without list items. i tried a lot but no success. need some workouts for this...

Can I scroll a ScrollView programmatically in Android?

Everyone is posting such complicated answers.

I found an easy answer, for scrolling to the bottom, nicely:

final ScrollView myScroller = (ScrollView) findViewById(R.id.myScrollerView);

// Scroll views can only have 1 child, so get the first child's bottom,
// which should be the full size of the whole content inside the ScrollView
myScroller.smoothScrollTo( 0, myScroller.getChildAt( 0 ).getBottom() );

And, if necessary, you can put the second line of code, above, into a runnable:

myScroller.post( new Runnable() {
    @Override
    public void run() {
        myScroller.smoothScrollTo( 0, myScroller.getChildAt( 0 ).getBottom() );
    }
}

It took me much research and playing around to find this simple solution. I hope it helps you, too! :)

How to force C# .net app to run only one instance in Windows?

to force running only one instace of a program in .net (C#) use this code in program.cs file:

public static Process PriorProcess()
    // Returns a System.Diagnostics.Process pointing to
    // a pre-existing process with the same name as the
    // current one, if any; or null if the current process
    // is unique.
    {
        Process curr = Process.GetCurrentProcess();
        Process[] procs = Process.GetProcessesByName(curr.ProcessName);
        foreach (Process p in procs)
        {
            if ((p.Id != curr.Id) &&
                (p.MainModule.FileName == curr.MainModule.FileName))
                return p;
        }
        return null;
    }

and the folowing:

[STAThread]
    static void Main()
    {
        if (PriorProcess() != null)
        {

            MessageBox.Show("Another instance of the app is already running.");
            return;
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form());
    }

How to parse XML and count instances of a particular node attribute?

If you don't want to use any external libraries or 3rd party tools, Please try below code.

  • This will parse xml into python dictionary
  • This will parse xml attrbutes as well
  • This will also parse empty tags like <tag/> and tags with only attributes like <tag var=val/>

Code

import re

def getdict(content):
    res=re.findall("<(?P<var>\S*)(?P<attr>[^/>]*)(?:(?:>(?P<val>.*?)</(?P=var)>)|(?:/>))",content)
    if len(res)>=1:
        attreg="(?P<avr>\S+?)(?:(?:=(?P<quote>['\"])(?P<avl>.*?)(?P=quote))|(?:=(?P<avl1>.*?)(?:\s|$))|(?P<avl2>[\s]+)|$)"
        if len(res)>1:
            return [{i[0]:[{"@attributes":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,i[1].strip())]},{"$values":getdict(i[2])}]} for i in res]
        else:
            return {res[0]:[{"@attributes":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,res[1].strip())]},{"$values":getdict(res[2])}]}
    else:
        return content

with open("test.xml","r") as f:
    print(getdict(f.read().replace('\n','')))

Sample input

<details class="4b" count=1 boy>
    <name type="firstname">John</name>
    <age>13</age>
    <hobby>Coin collection</hobby>
    <hobby>Stamp collection</hobby>
    <address>
        <country>USA</country>
        <state>CA</state>
    </address>
</details>
<details empty="True"/>
<details/>
<details class="4a" count=2 girl>
    <name type="firstname">Samantha</name>
    <age>13</age>
    <hobby>Fishing</hobby>
    <hobby>Chess</hobby>
    <address current="no">
        <country>Australia</country>
        <state>NSW</state>
    </address>
</details>

Output (Beautified)

[
  {
    "details": [
      {
        "@attributes": [
          {
            "class": "4b"
          },
          {
            "count": "1"
          },
          {
            "boy": ""
          }
        ]
      },
      {
        "$values": [
          {
            "name": [
              {
                "@attributes": [
                  {
                    "type": "firstname"
                  }
                ]
              },
              {
                "$values": "John"
              }
            ]
          },
          {
            "age": [
              {
                "@attributes": []
              },
              {
                "$values": "13"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Coin collection"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Stamp collection"
              }
            ]
          },
          {
            "address": [
              {
                "@attributes": []
              },
              {
                "$values": [
                  {
                    "country": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "USA"
                      }
                    ]
                  },
                  {
                    "state": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "CA"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": [
          {
            "empty": "True"
          }
        ]
      },
      {
        "$values": ""
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": []
      },
      {
        "$values": ""
      }
    ]
  },
  {
    "details": [
      {
        "@attributes": [
          {
            "class": "4a"
          },
          {
            "count": "2"
          },
          {
            "girl": ""
          }
        ]
      },
      {
        "$values": [
          {
            "name": [
              {
                "@attributes": [
                  {
                    "type": "firstname"
                  }
                ]
              },
              {
                "$values": "Samantha"
              }
            ]
          },
          {
            "age": [
              {
                "@attributes": []
              },
              {
                "$values": "13"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Fishing"
              }
            ]
          },
          {
            "hobby": [
              {
                "@attributes": []
              },
              {
                "$values": "Chess"
              }
            ]
          },
          {
            "address": [
              {
                "@attributes": [
                  {
                    "current": "no"
                  }
                ]
              },
              {
                "$values": [
                  {
                    "country": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "Australia"
                      }
                    ]
                  },
                  {
                    "state": [
                      {
                        "@attributes": []
                      },
                      {
                        "$values": "NSW"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

How to auto-reload files in Node.js?

Here's a low tech method for use in Windows. Put this in a batch file called serve.bat:

@echo off

:serve
start /wait node.exe %*
goto :serve

Now instead of running node app.js from your cmd shell, run serve app.js.

This will open a new shell window running the server. The batch file will block (because of the /wait) until you close the shell window, at which point the original cmd shell will ask "Terminate batch job (Y/N)?" If you answer "N" then the server will be relaunched.

Each time you want to restart the server, close the server window and answer "N" in the cmd shell.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

Pipenv: Command Not Found

OS : Linux
Pip version : pip3
sudo -H pip3 install -U pipenv

OS : Windows
Pip version : any one
sudo -H pip install -U pipenv

How to change Maven local repository in eclipse

In newer versions of Eclipse the global configuration file can be set in

Windows > Preferences > Maven > User Settings > Global Settings

Don't beat me why global settings can be configured in user settings... Probably because of the same reason why you need to press "Start" to shutdown your PC on Windows... :D

How to round up integer division and have int result in Java?

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b

UIButton title text color

Besides de color, my problem was that I was setting the text using textlabel

bt.titleLabel?.text = title

and I solved changing to:

bt.setTitle(title, for: .normal)

R: Comment out block of code

A sort of block comment uses an if statement:

if(FALSE) {
  all your code
}

It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).

'cl' is not recognized as an internal or external command,

I think cl isn't in your path. You need to add it there. The recommended way to do this is to launch a developer command prompt.

Quoting the article Setting the Path and Environment Variables for Command-Line Builds:

To open a Developer Command Prompt window

  1. With the Windows 8 Start screen showing, type Visual Studio Tools. Notice that the search results change as you type; when Visual Studio Tools appears, choose it.

    On earlier versions of Windows, choose Start, and then in the search box, type Visual Studio Tools. When Visual Studio Tools appears in the search results, choose it.

  2. In the Visual Studio Tools folder, open the Developer Command Prompt for your version of Visual Studio. (To run as administrator, open the shortcut menu for the Developer Command Prompt and choose Run as Administrator.)

As the article notes, there are several different shortcuts for setting up different toolsets - you need to pick the suitable one.

If you already have a plain Command Prompt window open, you can run the batch file vcvarsall.bat with the appropriate argument to set up the environment variables. Quoting the same article:

To run vcvarsall.bat

  1. At the command prompt, change to the Visual C++ installation directory. (The location depends on the system and the Visual Studio installation, but a typical location is C:\Program Files (x86)\Microsoft Visual Studio version\VC.) For example, enter:

    cd "\Program Files (x86)\Microsoft Visual Studio 12.0\VC"
    
  2. To configure this Command Prompt window for 32-bit x86 command-line builds, at the command prompt, enter:

    vcvarsall x86
    

From the article, the possible arguments are the following:

  • x86 (x86 32-bit native)
  • x86_amd64 (x64 on x86 cross)
  • x86_arm (ARM on x86 cross)
  • amd64 (x64 64-bit native)
  • amd64_x86 (x86 on x64 cross)
  • amd64_arm (ARM on x64 cross)

Rails - controller action name to string

Rails 2.X: @controller.action_name

Rails 3.1.X: controller.action_name, action_name

Rails 4.X: action_name

For-loop vs while loop in R

Because 1 is numeric, but not integer (i.e. it's a floating point number), and 1:6000 is numeric and integer.

> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"

60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:

> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

3.6 billion is easily representable in floating point, however:

> as.single(60000)*as.single(60000)
[1] 3.6e+09

To fix your for code, convert to a floating point representation:

function (N)
{
    for(i in as.single(1:N)) {
        y <- i*i
    }
}

set the width of select2 input (through Angular-ui directive)

This is an old question but new info is still worth posting...

Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear if that attribute is used, and it handles placeholder text properly too.

$("#some_select_id").select2({
    dropdownAutoWidth : true
});

get string value from HashMap depending on key name

 HashMap<Integer, String> hmap = new HashMap<Integer, String>();
 hmap.put(4, "DD");

The Value mapped to Key 4 is DD

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I just had to uninstall HAXM and install it again. Then it started working again. Hope this helps someone!

Edit:

Oh wow, this was a long time ago. I have been using genymotion for a few months now, and never had any issues like that.

SQL: Two select statements in one query

You can use UNION in this case

select id, name, games, goals from tblMadrid
union
select id, name, games, goals from tblBarcelona

you jsut have to maintain order of selected columns ie id, name, games, goals in both SQLs

How to run Conda?

1. Check where you have installed Anaconda. In my case it looks like /home/nour/anaconda3/bin

  1. Open your .bashrc file. For example $ gedit .bashrc

3. Add this export PATH = /home/nour/anaconda3/bin:$PATH line at the end of the file and save.

  1. Reopen the terminal. Type conda --version

NOTE: Make sure path in line no. 1 and line no. 3 must be same. In my case /home/nour/anaconda3/bin .

What's the safest way to iterate through the keys of a Perl hash?

A few miscellaneous thoughts on this topic:

  1. There is nothing unsafe about any of the hash iterators themselves. What is unsafe is modifying the keys of a hash while you're iterating over it. (It's perfectly safe to modify the values.) The only potential side-effect I can think of is that values returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.
  2. John's accepted answer is good with one exception: the documentation is clear that it is not safe to add keys while iterating over a hash. It may work for some data sets but will fail for others depending on the hash order.
  3. As already noted, it is safe to delete the last key returned by each. This is not true for keys as each is an iterator while keys returns a list.

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

How can a LEFT OUTER JOIN return more records than exist in the left table?

In response to your postscript, that depends on what you would like.

You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.

Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.

If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.

libpng warning: iCCP: known incorrect sRGB profile

After trying a couple of the suggestions on this page I ended up using the pngcrush solution. You can use the bash script below to recursively detect and fix bad png profiles. Just pass it the full path to the directory you want to search for png files.

fixpng "/path/to/png/folder"

The script:

#!/bin/bash

FILES=$(find "$1" -type f -iname '*.png')

FIXED=0
for f in $FILES; do
    WARN=$(pngcrush -n -warn "$f" 2>&1)
    if [[ "$WARN" == *"PCS illuminant is not D50"* ]] || [[ "$WARN" == *"known incorrect sRGB profile"* ]]; then
        pngcrush -s -ow -rem allb -reduce "$f"
        FIXED=$((FIXED + 1))
    fi
done

echo "$FIXED errors fixed"

How do you query for "is not null" in Mongo?

The simplest way to check the existence of the column in mongo compass is :

{ 'column_name': { $exists: true } }