Programs & Examples On #Groovyws

Force drop mysql bypassing foreign key constraint

This might be useful to someone ending up here from a search. Make sure you're trying to drop a table and not a view.

SET foreign_key_checks = 0;
-- Drop tables
drop table ...
-- Drop views
drop view ...
SET foreign_key_checks = 1;

SET foreign_key_checks = 0 is to set foreign key checks to off and then SET foreign_key_checks = 1 is to set foreign key checks back on. While the checks are off the tables can be dropped, the checks are then turned back on to keep the integrity of the table structure.

When should I use Lazy<T>?

A great real-world example of where lazy loading comes in handy is with ORM's (Object Relation Mappers) such as Entity Framework and NHibernate.

Say you have an entity Customer which has properties for Name, PhoneNumber, and Orders. Name and PhoneNumber are regular strings but Orders is a navigation property that returns a list of every order the customer ever made.

You often might want to go through all your customer's and get their name and phone number to call them. This is a very quick and simple task, but imagine if each time you created a customer it automatically went and did a complex join to return thousands of orders. The worst part is that you aren't even going to use the orders so it is a complete waste of resources!

This is the perfect place for lazy loading because if the Order property is lazy it will not go fetch all the customer's order unless you actually need them. You can enumerate the Customer objects getting only their Name and Phone Number while the Order property is patiently sleeping, ready for when you need it.

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

The easiest is to use the queryout option and use union all to link a column list with the actual table content

    bcp "select 'col1', 'col2',... union all select * from myschema.dbo.myTableout" queryout myTable.csv /SmyServer01 /c /t, -T

An example:

create table Question1355876
(id int, name varchar(10), someinfo numeric)

insert into Question1355876
values (1, 'a', 123.12)
     , (2, 'b', 456.78)
     , (3, 'c', 901.12)
     , (4, 'd', 353.76)

This query will return the information with the headers as first row (note the casts of the numeric values):

select 'col1', 'col2', 'col3'
union all
select cast(id as varchar(10)), name, cast(someinfo as varchar(28))
from Question1355876

The bcp command will be:

bcp "select 'col1', 'col2', 'col3' union all select cast(id as varchar(10)), name, cast(someinfo as varchar(28)) from Question1355876" queryout myTable.csv /SmyServer01 /c /t, -T

Adb over wireless without usb cable at all for not rooted phones

The question is about a non rooted device but if it is rooted the simplest way would be to:

From the terminal on your phone, do this:

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

See this answer for full details.

How to check currently internet connection is available or not in android

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Real world use of JMS/message queues?

JMS (ActiveMQ is a JMS broker implementation) can be used as a mechanism to allow asynchronous request processing. You may wish to do this because the request take a long time to complete or because several parties may be interested in the actual request. Another reason for using it is to allow multiple clients (potentially written in different languages) to access information via JMS. ActiveMQ is a good example here because you can use the STOMP protocol to allow access from a C#/Java/Ruby client.

A real world example is that of a web application that is used to place an order for a particular customer. As part of placing that order (and storing it in a database) you may wish to carry a number of additional tasks:

  • Store the order in some sort of third party back-end system (such as SAP)
  • Send an email to the customer to inform them their order has been placed

To do this your application code would publish a message onto a JMS queue which includes an order id. One part of your application listening to the queue may respond to the event by taking the orderId, looking the order up in the database and then place that order with another third party system. Another part of your application may be responsible for taking the orderId and sending a confirmation email to the customer.

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

How to easily get network path to the file you are working on?

Right click on the ribbon and choose Customize the ribbon. From the Choose commands from: drop down, select Commands not in the ribbon.

That is where I found the Document location command.

How does the Python's range function work?

It is looping, probably the problem is in the part of the print...

If you can't find the logic where the system prints, just add the folling where you want the content out:

for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]

Loop and get key/value pair for JSON array using jQuery

var obj = $.parseJSON(result);
for (var prop in obj) {
    alert(prop + " is " + obj[prop]);
}

lambda expression for exists within list

You can use the Contains() extension method:

list.Where(r => listofIds.Contains(r.Id))

How to force cp to overwrite without confirmation

As other answers have stated, this could happend if cp is an alias of cp -i.

You can append a \ before the cp command to use it without alias.

\cp -fR source target

Printing long int value in C

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

How do you follow an HTTP Redirect in Node.js?

Possibly a little bit of a necromancing post here, but...

here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON

Note - uses a callback helper (shown at the end of this post)

( TLDR; full working demo in context here or remixed-version here)

function getJSON(url,cb){

    var callback=errBack(cb);
    //var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 301/302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("301/302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      console.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {

                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

Note - uses a callback helper (shown below)

you can paste this into the node console and it should run as is.

( or for full working demo in context see here )

var 

fs      = require('fs'),
https   = require('https');

function errBack (cb,THIS,logger) {

   var 
   self,
   EB=function(fn,r,e){
       if (logger===false) {
           fn.log=fn.info=fn.warn=fn.errlog=function(){};       
       } else {
           fn.log        = logger?logger.log   : console.log.bind(console);
           fn.info       = logger?logger.info  : console.info.bind(console);
           fn.warn       = logger?logger.warn  : console.warn.bind(console);
           fn.errlog     = logger?logger.error : console.error.bind(console);
       }
       fn.result=r;
       fn.error=e;
       return (self=fn);
   };


   if (typeof cb==='function') {
       return EB(

            logger===false // optimization when not logging - don't log errors
            ?   function(err){
                   if (err) {
                      cb (err);
                     return true;
                   }
                   return false;
               }

            :  function(err){
                   if (err) {
                      self.errlog(err);
                      cb (err);
                     return true;
                   }
                   return false;
               },

           function () {
               return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
           },
           function (err) {
               return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
           }
       );
   } else {

       return EB(

           function(err){
               if (err) {
                   if (typeof err ==='object' && err instanceof Error) {
                       throw err;
                   } else {
                       throw new Error(err);
                   }
                   return true;//redundant due to throw, but anyway.
               }
               return false;
           },

           logger===false
              ? self.log //optimization :resolves to noop when logger==false
              : function () {
                   self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
           },

           function (err) {
               throw typeof err==='string'?new Error(err):err;
           }
       );
   }
}

function getJSON(url,cb){

    var callback=errBack(cb);

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {
                      // read with "bypass refetch" option
                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};


function getTLDs(cb,filter_func){

    if (typeof cb!=='function') return TLDs;

    var 
    read,fetch,
    CB_WRAP=function(tlds){
        return cb(
            filter_func===false
            ? cb(tlds)
            : tlds.filter(
                typeof filter_func==='function'
                 ? filter_func
                 : TLD_default_filter)
            );
    },
    check_mtime = function(mtime) {
       if (Date.now()-mtime > TLD_refresh_msec) {
           return fetch();
       } 
       if (TLDs) return CB_WRAP (TLDs);
       return read();
    };

    fetch = function(){

        getJSON(TLD_url,function(err,data){
            if (err) {
                console.log("exception in getTLDs.fetch:",err.message||err);
                return read(true);      
            } else {
                TLDs=Object.keys(data);

                fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
                    if (err) {
                        // ignore save error, we have the data
                        CB_WRAP(TLDs);
                    } else {
                        // get mmtime for the file we just made
                        fs.stat(TLD_cache,function(err,stats){
                            if (!err && stats) {
                               TLD_last_msec = stats.mtimeMs; 
                            }
                            CB_WRAP(TLDs);    
                        });
                    }
                });
            }
        });
    };

    read=function(bypassFetch) {
        fs.readFile(TLD_cache,'utf-8',function(err,json){

            try {
                if (err) {

                    if (bypassFetch) {
                        // after a http errror, we fallback to hardcoded basic list of tlds
                        // if the disk file is not readable
                        console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);    

                        throw err;
                    }
                    // if the disk read failed, get the data from the CDN server instead
                    return fetch();
                }

                TLDs=JSON.parse(json);
                if (bypassFetch) {
                    // we need to update stats here as fetch called us directly
                    // instead of being called by check_mtime
                    return fs.stat(TLD_cache,function(err,stats){
                        if (err) return fetch();
                        TLD_last_msec =stats.mtimeMs;
                        return CB_WRAP(TLDs);
                    });
                }

            } catch (e){
                // after JSON error, if we aren't in an http fail situation, refetch from cdn server
                if (!bypassFetch) {
                    return fetch();
                }

                // after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds

                console.log("exception in getTLDs.read:",err.messsage||err);    
                TLDs=TLDs_fallback;
            }

            return CB_WRAP(TLDs);
        });
    };

    if (TLD_last_msec) {
        return check_mtime(TLD_last_msec);
    } else {
        fs.stat(TLD_cache,function(err,stats){
            if (err) return fetch();
            TLD_last_msec =stats.mtimeMs;
            return check_mtime(TLD_last_msec);
        });
    }
}

getTLDs(console.log.bind(console));

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

Is there an arraylist in Javascript?

There is no ArrayList in javascript.

There is however ArrayECMA 5.1 which has similar functionality to an "ArrayList". The majority of this answer is taken verbatim from the HTML rendering of Ecma-262 Edition 5.1, The ECMAScript Language Specification.

Defined arrays have the following methods available:

  • .toString ( )
  • .toLocaleString ( )
  • .concat ( [ item1 [ , item2 [ , … ] ] ] )
    When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.
  • .join (separator)
    The elements of the array are converted to Strings, and these Strings are then concatenated, separated by occurrences of the separator. If no separator is provided, a single comma is used as the separator.
  • .pop ( )
    The last element of the array is removed from the array and returned.
  • .push ( [ item1 [ , item2 [ , … ] ] ] )
    The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call."
  • .reverse ( )
    The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call.
  • .shift ( )
    The first element of the array is removed from the array and returned."
  • .slice (start, end)
    The slice method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if end is undefined).
  • .sort (comparefn)
    The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
  • .splice (start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )
    When the splice method is called with two or more arguments start, deleteCount and (optionally) item1, item2, etc., the deleteCount elements of the array starting at array index start are replaced by the arguments item1, item2, etc. An Array object containing the deleted elements (if any) is returned.
  • .unshift ( [ item1 [ , item2 [ , … ] ] ] )
    The arguments are prepended to the start of the array, such that their order within the array is the same as the order in which they appear in the argument list.
  • .indexOf ( searchElement [ , fromIndex ] )
    indexOf compares searchElement to the elements of the array, in ascending order, using the internal Strict Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the first such position; otherwise, -1 is returned.
  • .lastIndexOf ( searchElement [ , fromIndex ] )
    lastIndexOf compares searchElement to the elements of the array in descending order using the internal Strict Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the last such position; otherwise, -1 is returned.
  • .every ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. every calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns false. If such an element is found, every immediately returns false. Otherwise, if callbackfn returned true for all elements, every will return true.
  • .some ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. some calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns true. If such an element is found, some immediately returns true. Otherwise, some returns false.
  • .forEach ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order.
  • .map ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments. map calls callbackfn once for each element in the array, in ascending order, and constructs a new Array from the results.
  • .filter ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. filter calls callbackfn once for each element in the array, in ascending order, and constructs a new array of all the values for which callbackfn returns true.
  • .reduce ( callbackfn [ , initialValue ] )
    callbackfn should be a function that takes four arguments. reduce calls the callback, as a function, once for each element present in the array, in ascending order.
  • .reduceRight ( callbackfn [ , initialValue ] )
    callbackfn should be a function that takes four arguments. reduceRight calls the callback, as a function, once for each element present in the array, in descending order.

and also the length property.

a tag as a submit button?

Try something like below

 <a href="#" onclick="this.forms['formName'].submit()">Submit</a> 

How to sort pandas data frame using values from several columns?

If you are writing this code as a script file then you will have to write it like this:

df = df.sort(['c1','c2'], ascending=[False,True])

How to check if input is numeric in C++

When cin gets input it can't use, it sets failbit:

int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
    // user didn't input a number
    cin.clear(); // reset failbit
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
    // next, request user reinput
}

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

Getting a list of associative array keys

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Java NIO: What does IOException: Broken pipe mean?

What causes a "broken pipe", and more importantly, is it possible to recover from that state?

It is caused by something causing the connection to close. (It is not your application that closed the connection: that would have resulted in a different exception.)

It is not possible to recover the connection. You need to open a new one.

If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption?

Yes it is. Once you've received that exception, the socket won't ever work again. Closing it is is the only sensible thing to do.

Is there ever a time when this IOException would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?

No. (Or at least, not without subverting proper behavior of the OS'es network stack, the JVM and/or your application.)


Is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write() ...

In general, it is a bad idea to call r.isXYZ() before some call that uses the (external) resource r. There is a small chance that the state of the resource will change between the two calls. It is a better idea to do the action, catch the IOException (or whatever) resulting from the failed action and take whatever remedial action is required.

In this particular case, calling isConnected() is pointless. The method is defined to return true if the socket was connected at some point in the past. It does not tell you if the connection is still live. The only way to determine if the connection is still alive is to attempt to use it; e.g. do a read or write.

How to select the first row of each group?

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

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

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

implicit val dfEnc = RowEncoder(df.schema)

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

How to remove folders with a certain name

find ./ -name "FOLDERNAME" | xargs rm -Rf

Should do the trick. WARNING, if you accidentally pump a . or / into xargs rm -Rf your entire computer will be deleted without an option to get it back, requiring an OS reinstall.

Can attributes be added dynamically in C#?

Well, just to be different, I found an article that references using Reflection.Emit to do so.

Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.

wamp server mysql user id and password

Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link. alt text

How to group by month from Date field using sql

I used the FORMAT function to accomplish this:

select
 FORMAT(Closing_Date, 'yyyy_MM') AS Closing_Month
 , count(*) cc 
FROM
 MyTable
WHERE
 Defect_Status1 IS NOT NULL
 AND Closing_Date >= '2011-12-01'
 AND Closing_Date < '2016-07-01' 
GROUP BY FORMAT(Closing_Date, 'yyyy_MM')
ORDER BY Closing_Month

How to add action listener that listens to multiple buttons

Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)

Suppose we have a class for a frame window which contains 2 buttons:

class MainWindow {
    Jbutton searchButton;
    Jbutton filterButton;
}

You can use my 'router' class to route the event back to your MainWindow class:

class MainWindow {
    JButton searchButton;
    Jbutton filterButton;
    ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
    
    void initWindowContent() {
        // create your components here...
        
        // setup button listeners
        searchButton.addActionListener(buttonRouter);
        filterButton.addActionListener(buttonRouter);
    }

    void on_searchButton() {
        // TODO your handler goes here...
    }
    
    void on_filterButton() {
        // TODO your handler goes here...
    }
}

Do you like it? :)

If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)

Finally, the router class is at below. You can copy it into your programme without the need for any update.

Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ButtonClickRouter implements ActionListener {
    private Object target;

    ButtonClickRouter(Object target) {
        this.target = target;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        // get source button
        Object sourceButton = actionEvent.getSource();

        // find the corresponding field of the button in the host class
        Field fieldOfSourceButton = null;
        for (Field field : target.getClass().getDeclaredFields()) {
            try {
                if (field.get(target).equals(sourceButton)) {
                    fieldOfSourceButton = field;
                    break;
                }
            } catch (IllegalAccessException e) {
            }
        }

        if (fieldOfSourceButton == null)
            return;

        // make the expected method name for the source button
        // rule: suppose the button field is 'searchButton', then the method
        // is expected to be 'void on_searchButton()'
        String methodName = "on_" + fieldOfSourceButton.getName();

        // find such a method
        Method expectedHanderMethod = null;
        for (Method method : target.getClass().getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                expectedHanderMethod = method;
                break;
            }
        }

        if (expectedHanderMethod == null)
            return;

        // fire
        try {
            expectedHanderMethod.invoke(target);
        } catch (IllegalAccessException | InvocationTargetException e) { }
    }
}

I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Java current machine name and logged in user?

To get the currently logged in user path:

System.getProperty("user.home");

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

If the former actions haven't had effect, backup your server configurations, remove the server and reinclude it. It was my case.

How do I sort an observable collection?

I would like to Add to NeilW's answer. To incorporate a method that resembles the orderby. Add this method as an extension:

public static void Sort<T>(this ObservableCollection<T> collection, Func<T,T> keySelector) where T : IComparable
{
    List<T> sorted = collection.OrderBy(keySelector).ToList();
    for (int i = 0; i < sorted.Count(); i++)
        collection.Move(collection.IndexOf(sorted[i]), i);
}

And use like:

myCollection = new ObservableCollection<MyObject>();

//Sorts in place, on a specific Func<T,T>
myCollection.Sort(x => x.ID);

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

How do I break out of a loop in Perl?

Oh, I found it. You use last instead of break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

How do you log content of a JSON object in Node.js?

console.log(obj);

Run: node app.js > output.txt

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

How can I align two divs horizontally?

Add a class to each of the divs:

_x000D_
_x000D_
.source, .destination {_x000D_
    float: left;_x000D_
    width: 48%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.source {_x000D_
    margin-right: 4%;_x000D_
}
_x000D_
<div class="source">_x000D_
    <span>source list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>_x000D_
<div class="destination">_x000D_
    <span>destination list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

That's a generic percentages solution - using pixel-based widths is usually much more reliable. You'll probably want to change the various margin/padding sizes too.

You can also optionally wrap the HTML in a container div, and use this CSS:

.container {
  overflow: hidden;
}

This will ensure subsequent content does not wrap around the floated elements.

How to round the double value to 2 decimal points?

This would do it.

     public static void main(String[] args) {
        double d = 12.349678;
        int r = (int) Math.round(d*100);
        double f = r / 100.0;
       System.out.println(f);
     }

You can short this method, it's easy to understand that's why I have written like this.

String parsing in Java with delimiter tab "\t" using split

Try this:

String[] columnDetail = column.split("\t", -1);

Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:

split

public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex   Limit   Result
:   2   { "boo", "and:foo" }
:   5   { "boo", "and", "foo" }
:   -2  { "boo", "and", "foo" }
o   5   { "b", "", ":and:f", "", "" }
o   -2  { "b", "", ":and:f", "", "" }
o   0   { "b", "", ":and:f" }

When the last few fields (I guest that's your situation) are missing, you will get the column like this:

field1\tfield2\tfield3\t\t

If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.

When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.

How to get client's IP address using JavaScript?

If you're including an file anways, you could do a simple ajax get:

function ip_callback() {
    $.get("ajax.getIp.php",function(data){ return data; }
}

And ajax.getIp.php would be this:

<?=$_SERVER['REMOTE_ADDR']?>

How to split a string in Java

import java.io.*;

public class BreakString {

  public static void main(String args[]) {

    String string = "004-034556-1234-2341";
    String[] parts = string.split("-");

    for(int i=0;i<parts.length;i++) {
      System.out.println(parts[i]);
    }
  }
}

How do I execute a bash script in Terminal?

You could do:
sh scriptname.sh

How to check if image exists with given url?

From here:

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

No Title Bar Android Theme

To Hide the Action Bar add the below code in Values/Styles

<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then in your AndroidManifest.xml file add the below code in the required activity

<activity
        android:name="com.newbelievers.android.NBMenu"
        android:label="@string/title_activity_nbmenu"
        android:theme="@style/CustomActivityThemeNoActionBar">
</activity>

'Source code does not match the bytecode' when debugging on a device

Probably this error message can have more than one cause, my case was not like the one from the OP, in my case this was due to a 3rd party library that required additional libraries.

For example: you manually add X.jar to your LIB, but this X.jar requires Z.jar to work.

It took me sometime to figure out, the message was not helping at all. I had to debug the app until I reached the crashing class, and in that class make sure that all imports were satisfied.

(Particualry: I added MercadoLibre-0.3.4.jar, which required commons-httpclient.jar)

Hope this helps!

Generate random 5 characters string

$rand = substr(md5(microtime()),rand(0,26),5);

Would be my best guess--Unless you're looking for special characters, too:

$seed = str_split('abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

Example

And, for one based on the clock (fewer collisions since it's incremental):

function incrementalHash($len = 5){
  $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  $base = strlen($charset);
  $result = '';

  $now = explode(' ', microtime())[1];
  while ($now >= $base){
    $i = $now % $base;
    $result = $charset[$i] . $result;
    $now /= $base;
  }
  return substr($result, -5);
}

Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

Applying a selector from the .nav-tabs seems to be working

HTML is

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Script is

$(document).ready(function(){
  activaTab('aaa');
});

function activaTab(tab){
  $('.nav-tabs a[href="#' + tab + '"]').tab('show');
};

http://jsfiddle.net/pThn6/80/

Excel: last character/string match in a string

I think I get what you mean. Let's say for example you want the right-most \ in the following string (which is stored in cell A1):

Drive:\Folder\SubFolder\Filename.ext

To get the position of the last \, you would use this formula:

=FIND("@",SUBSTITUTE(A1,"\","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))/LEN("\")))

That tells us the right-most \ is at character 24. It does this by looking for "@" and substituting the very last "\" with an "@". It determines the last one by using

(len(string)-len(substitute(string, substring, "")))\len(substring)

In this scenario, the substring is simply "\" which has a length of 1, so you could leave off the division at the end and just use:

=FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))

Now we can use that to get the folder path:

=LEFT(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

Here's the folder path without the trailing \

=LEFT(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))-1)

And to get just the filename:

=MID(A1,FIND("@",SUBSTITUTE(A1,"\","@",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))

However, here is an alternate version of getting everything to the right of the last instance of a specific character. So using our same example, this would also return the file name:

=TRIM(RIGHT(SUBSTITUTE(A1,"\",REPT(" ",LEN(A1))),LEN(A1)))

Python regex for integer?

You need to anchor the regex at the start and end of the string:

^[0-9]+$

Explanation:

^      # Start of string
[0-9]+ # one or more digits 0-9
$      # End of string

How to change the background color of a UIButton while it's highlighted?

Here's an approach in Swift, using a UIButton extension to add an IBInspectable, called highlightedBackgroundColor. Similar to subclassing, without requiring a subclass.

private var HighlightedBackgroundColorKey = 0
private var NormalBackgroundColorKey = 0

extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &HighlightedBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &HighlightedBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private var normalBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &NormalBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &NormalBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    override public var backgroundColor: UIColor? {
        didSet {
            if !highlighted {
                normalBackgroundColor = backgroundColor
            }
        }
    }

    override public var highlighted: Bool {
        didSet {
            if let highlightedBackgroundColor = self.highlightedBackgroundColor {
                if highlighted {
                    backgroundColor = highlightedBackgroundColor
                } else {
                    backgroundColor = normalBackgroundColor
                }
            }
        }
    }
}

I hope this helps.

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Converting camel case to underscore case in ruby

The ruby core itself has no support to convert a string from (upper) camel case to (also known as pascal case) to underscore (also known as snake case).

So you need either to make your own implementation or use an existing gem.

There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

require 'lucky_case'

# convert to snake case string
LuckyCase.snake_case('CamelCaseString')      # => 'camel_case_string'
# or the opposite way
LuckyCase.pascal_case('camel_case_string')   # => 'CamelCaseString'

You can even monkey patch the String class if you want to:

require 'lucky_case/string'

'CamelCaseString'.snake_case  # => 'camel_case_string'
'CamelCaseString'.snake_case! # => 'camel_case_string' and overwriting original

Have a look at the offical repository for more examples and documentation:

https://github.com/magynhard/lucky_case

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

Check if a given time lies between two times regardless of date

strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.

if(($to < $from && ($time >= $from || $time <= $to)) ||
    ($time >= $from && $time <= $to)) {
    return true;
}

Preloading @font-face fonts?

There are a few techniques for "preloading" here: http://paulirish.com/2009/fighting-the-font-face-fout/

Mostly tricking the browser into downloading the file as fast as possible..

You can also deliver it as a data-uri, which helps a lot. and also you could hide the page content and show it when its ready.

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

omp parallel vs. omp parallel for

Here is example of using separated parallel and for here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for cycle in several threads. It is impossible to do the same initializing in parallel for case.

UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:

#pragma omp parallel
{ 
    double *data = (double*)malloc(...); // this data is thread private

    #pragma omp for
    for(1...100) // first parallelized cycle
    {
    }

    #pragma omp single 
    {} // make some single thread processing

    #pragma omp for // second parallelized cycle
    for(1...100)
    {
    }

    #pragma omp single 
    {} // make some single thread processing again

    free(data); // free thread private data
}

nodejs get file name from absolute path?

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();

how to delete a specific row in codeigniter?

a simple way:

in view(pass the id value):

<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>

in controller(receive the id):

$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);

in model(get the passed args):

function row_delete($id){}

Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.

Compare objects in Angular

To compare two objects you can use:

angular.equals(obj1, obj2)

It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo

var obj1 = {
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return true

Why does adb return offline after the device string?

What did me in is was that multiple unrelated software packages just happened to install adb.exe -- in particular for me (on Windoze), the phone OEM driver installation package "helpfully" also installed adb.exe into C:\windows, and this directory appears in %PATH% long before the platform-tools directory of my android SDK. Unsurprisingly, the adb.exe included in the phone OEM driver package is MUCH older than the one in the updated android sdk. So adb worked just fine for me until one day something caused me to update the windows drivers for my phone. Once I did that, absolutely NOTHING would make my phone status change from "offline" -- but the problem had nothing to do with the driver. It was simply that the driver package had installed a different adb.exe - and a MUCH older one - into a directory with higher precedence. To fix my installation I simply altered the PATH environment variable to make the sdk's adb.exe have priority. A quick check suggested to me that "lots" of different packages include adb.exe, so be careful not to insert an older one into your toolchain unintentionally.

I must really be getting old: I don't ever remember such a stupid issue taking so endlessly long to uncover.

Angular 2 - View not updating after model changes

It is originally an answer in the comments from @Mark Rajcok, But I want to place it here as a tested and worked as a solution using ChangeDetectorRef , I see a good point here:

Another alternative is to inject ChangeDetectorRef and call cdRef.detectChanges() instead of zone.run(). This could be more efficient, since it will not run change detection over the entire component tree like zone.run() does. – Mark Rajcok

So code must be like:

import {Component, OnInit, ChangeDetectorRef} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private cdRef: ChangeDetectorRef, // <== added
                private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => {
                this.recentDetections = recent;
                console.log(this.recentDetections[0].macAddress);
                this.cdRef.detectChanges(); // <== added
            });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
} 

Edit: Using .detectChanges() inside subscibe could lead to issue Attempt to use a destroyed view: detectChanges

To solve it you need to unsubscribe before you destroy the component, so the full code will be like:

import {Component, OnInit, ChangeDetectorRef, OnDestroy} from 'angular2/core';

export class RecentDetectionComponent implements OnInit, OnDestroy {

    recentDetections: Array<RecentDetection>;
    private timerObserver: Subscription;

    constructor(private cdRef: ChangeDetectorRef, // <== added
                private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => {
                this.recentDetections = recent;
                console.log(this.recentDetections[0].macAddress);
                this.cdRef.detectChanges(); // <== added
            });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        this.timerObserver = timer.subscribe(() => this.getRecentDetections());
    }

    ngOnDestroy() {
        this.timerObserver.unsubscribe();
    }

}

How do you specify table padding in CSS? ( table, not cell padding )

table {
    background: #fff;
    box-shadow: 0 0 0 10px #fff;
    margin: 10px;
    width: calc(100% - 20px); 
}

How to insert close button in popover for Bootstrap

For me this is the simplest solution to add a close button in a popover.

HTML:

    <button type="button" id="popover" class="btn btn-primary" data-toggle="popover" title="POpover" data-html="true">
                    Show popover
    </button>

    <div id="popover-content" style="display:none"> 
       <!--Your content-->
       <button type="submit" class="btn btn-outline-primary" id="create_btn">Create</button>
       <button type="button" class="btn btn-outline-primary" id="close_popover">Cancel</button>  
    </div>

Javascript:

    document.addEventListener("click",function(e){
        // Close the popover 
        if (e.target.id == "close_popover"){
                $("[data-toggle=popover]").popover('hide');
            }
    });

In Java, how can I determine if a char array contains a particular character?

This method does the trick.

boolean contains(char c, char[] array) {
    for (char x : array) {
        if (x == c) {
            return true;
        }
    }
    return false;
}

Example of usage:

class Main {

    static boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] a) {
        char[] charArray = new char[] {'h','e','l','l','o'};
        if (!contains('q', charArray)) {
            // Do something...
            System.out.println("Hello world!");
        }
    }

}

Alternative way:

if (!String.valueOf(charArray).contains("q")) {
    // do something...
}

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)

Adding a y-axis label to secondary y-axis in matplotlib

The best way is to interact with the axes object directly

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

example graph

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

How can I find which tables reference a given table in Oracle SQL Developer?

I like to do this with a straight SQL query, rather than messing about with the SQL Developer application.

Here's how I just did it. Best to read through this and understand what's going on, so you can tweak it to fit your needs...

WITH all_primary_keys AS (
  SELECT constraint_name AS pk_name,
         table_name
    FROM all_constraints
   WHERE owner = USER
     AND constraint_type = 'P'
)
  SELECT ac.table_name || ' table has a foreign key called ' || upper(ac.constraint_name)
         || ' which references the primary key ' || upper(ac.r_constraint_name) || ' on table ' || apk.table_name AS foreign_keys
    FROM all_constraints ac
         LEFT JOIN all_primary_keys apk
                ON ac.r_constraint_name = apk.pk_name
   WHERE ac.owner = USER
     AND ac.constraint_type = 'R'
     AND ac.table_name = nvl(upper(:table_name), ac.table_name)
ORDER BY ac.table_name, ac.constraint_name
;

How do I get the full path to a Perl script that is executing?

Are you looking for this?:

my $thisfile = $1 if $0 =~
/\\([^\\]*)$|\/([^\/]*)$/;

print "You are running $thisfile
now.\n";

The output will look like this:

You are running MyFileName.pl now.

It works on both Windows and Unix.

How to change shape color dynamically?

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

XML:

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

Java:

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

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Globally catch exceptions in a WPF application?

Use the Application.DispatcherUnhandledException Event. See this question for a summary (see Drew Noakes' answer).

Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.

How to make inline plots in Jupyter Notebook larger?

The question is about matplotlib, but for the sake of any R users that end up here given the language-agnostic title:

If you're using an R kernel, just use:

options(repr.plot.width=4, repr.plot.height=3)

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

This works for MVC 5

@Html.ActionLink("LinkText", "ActionName", new { id = item.id }, new { @class = "btn btn-success" })

Ant: How to execute a command for each file in directory?

Do what blak3r suggested and define your targets classpath like so

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <fileset dir="lib">
          <include name="**/*.jar"/>
        </fileset>
    </classpath>        
</taskdef>

where lib is where you store your jar's

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

First run your IDE or CMD as Administrator and run the following:

pip install pipwin
pipwin install pyaudio

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Convert a double to a QString

Check out the documentation

Quote:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

.datepicker('setdate') issues, in jQuery

function calenderEdit(dob) {
    var date= $('#'+dob).val();
    $("#dob").datepicker({
        changeMonth: true,
        changeYear: true, yearRange: '1950:+10'
    }).datepicker("setDate", date);
}

Why are only final variables accessible in anonymous class?

There is a trick that allows anonymous class to update data in the outer scope.

private void f(Button b, final int a) {
    final int[] res = new int[1];
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            res[0] = a * 5;
        }
    });

    // But at this point handler is most likely not executed yet!
    // How should we now res[0] is ready?
}

However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated

This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:

// ...

final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);

// ...

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

How to delete files/subfolders in a specific directory at the command prompt in Windows

Use Notepad to create a text document and copy/paste this:

rmdir /s/q "%temp%"
mkdir "%temp%"

Select Save As and file name:

delete_temp.bat

Save as type: All files and click the Save button.

It works on any kind of account (administrator or a standard user). Just run it!

I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!

Find the IP address of the client in an SSH session

Improving on a prior answer. Gives ip address instead of hostname. --ips not available on OS X.

who am i --ips|awk '{print $5}' #ubuntu 14

more universal, change $5 to $6 for OS X 10.11:

WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
WORKSTATION_IP=`dig +short $WORKSTATION`
if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
echo $WORKSTATION_IP

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

centos: Another MySQL daemon already running with the same unix socket

Just open a bug report with your OS vendor asking them to put the socket in /var/run so it automagically gets removed at reboot. It's a bug to keep this socket after an unclean reboot, /var/run is the spot for these kinds of files.

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

Check if one date is between two dates

Try this

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(Date.now()))
        {
            alert('small');
        }else{
            alert('big');
        }

Fiddle

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

make sure your user has attributes on its role. for example:

postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      |                                                | {}
 postgres  | Superuser, Create role, Create DB, Replication | {}

after performing the following command:

postgres=# ALTER ROLE flux WITH Superuser;
ALTER ROLE
postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      | Superuser                                      | {}
postgres  | Superuser, Create role, Create DB, Replication | {}

it fixed the problem.

see tutorial for roles and stuff here: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

How to pass json POST data to Web API method as an object?

1)In your client side you can send you http.post request in string like below

var IndexInfo = JSON.stringify(this.scope.IndexTree);
this.$http.post('../../../api/EvaluationProcess/InsertEvaluationProcessInputType', "'" + IndexInfo + "'" ).then((response: any) => {}

2)Then in your web api controller you can deserialize it

public ApiResponce InsertEvaluationProcessInputType([FromBody]string IndexInfo)
    {
var des = (ApiReceivedListOfObjects<TempDistributedIndex>)Newtonsoft.Json.JsonConvert.DeserializeObject(DecryptedProcessInfo, typeof(ApiReceivedListOfObjects<TempDistributedIndex>));}

3)Your ApiReceivedListOfObjects class should be like below

public class ApiReceivedListOfObjects<T>
    {
        public List<T> element { get; set; }

    }

4)make sure that your serialized string (IndexInfo here) becomes like below structure before JsonConvert.DeserializeObject command in step 2

var resp = @"
    {
        ""element"": [
        {
            ""A"": ""A Jones"",
            ""B"": ""500015763""
        },
        {
            ""A"": ""B Smith"",
            ""B"": ""504986213""
        },
        {
            ""A"": ""C Brown"",
            ""B"": ""509034361""
        }
        ]
    }";

Drawing in Java using Canvas

You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

Random date in C#

I am a bit late in to the game, but here is one solution which works fine:

    void Main()
    {
        var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);
        foreach (var r in dateResult)
            Console.WriteLine(r);
    }

    public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)
    {
        var randomResult = GetRandomNumbers(range).ToArray();

        var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;
        var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();
        return dateResults;
    }

    public static IEnumerable<int> GetRandomNumbers(int size)
    {
        var data = new byte[4];
        using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))
        {
            for (int i = 0; i < size; i++)
            {
                rng.GetBytes(data);

                var value = BitConverter.ToInt32(data, 0);
                yield return value < 0 ? value * -1 : value;
            }
        }
    }

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Iterate over object keys in node.js

What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.

The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.

You could try the following, however it will also load all the keys into memory

Object.keys(o).forEach(function(key) {
  var val = o[key];
  logic();
});

However since Object.keys is a native method it may allow for better optimisation.

Benchmark

As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.

var async = {};
async.forEach = function(o, cb) {
  var counter = 0,
    keys = Object.keys(o),
    len = keys.length;
  var next = function() {
    if (counter < len) cb(o[keys[counter++]], next);
  };
  next();
};

async.forEach(obj, function(val, next) {
  // do things
  setTimeout(next, 100);
});

WPF Binding StringFormat Short Date String

Some DateTime StringFormat samples I found useful. Lifted from C# Examples

DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

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

With defining the file to import it's possible to use all folders common definitions.

So, @import "style/*" will compile all the files in the style folder.

More about import feature in Sass you can find here.

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

How to get the last char of a string in PHP?

A string in different languages including C sharp and PHP is also considered an array of characters.

Knowing that in theory array operations should be faster than string ones you could do,

$foo = "bar";


$lastChar = strlen($foo) -1;
echo $foo[$lastChar];

$firstChar = 0;
echo $foo[$firstChar];

However, standard array functions like

count();

will not work on a string.

How to get a value from the last inserted row?

Use sequences in postgres for id columns:

INSERT mytable(myid) VALUES (nextval('MySequence'));

SELECT currval('MySequence');

currval will return the current value of the sequence in the same session.

(In MS SQL, you would use @@identity or SCOPE_IDENTITY())

How to remove the last character from a bash grep output

Some refinements to answer above. To remove more than one char you add multiple question marks. For example, to remove last two chars from variable $SRC_IP_MSG, you can use:

SRC_IP_MSG=${SRC_IP_MSG%??}

Sql script to find invalid email addresses

SELECT EmailAddress AS ValidEmail
FROM Contacts
WHERE EmailAddress LIKE '%_@__%.__%'
        AND PATINDEX('%[^a-z,0-9,@,.,_,\-]%', EmailAddress) = 0
GO

Please check this link: https://blog.sqlauthority.com/2017/11/12/validate-email-address-sql-server-interview-question-week-147/

Removing viewcontrollers from navigation stack

You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.

Here is small piece of code:

NSArray* tempVCA = [self.navigationController viewControllers];

for(UIViewController *tempVC in tempVCA)
{
    if([tempVC isKindOfClass:[urViewControllerClass class]])
    {
        [tempVC removeFromParentViewController];
    }
}

I think this will make your work easier.

Video format or MIME type is not supported

For Ubuntu 14.04

Just removed the package Oxideqt-dodecs then install flash or ubuntu restricted extras

and you are good to go!!

Nested objects in javascript, best practices

If you know the settings in advance you can define it in a single statement:

var defaultsettings = {
                        ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
                        uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
                      };

If you don't know the values in advance you can just define the top level object and then add properties:

var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";

Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:

var defaultsettings = {
                        ajaxsettings : {  },
                        uisettings : {  }
                      };

defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";

You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:

var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";

Note that you can not use variables for key names in the { } literal syntax.

How can I read an input string of unknown length?

i also have a solution with standard inputs and outputs

#include<stdio.h>
#include<malloc.h>
int main()
{
    char *str,ch;
    int size=10,len=0;
    str=realloc(NULL,sizeof(char)*size);
    if(!str)return str;
    while(EOF!=scanf("%c",&ch) && ch!="\n")
    {
        str[len++]=ch;
        if(len==size)
        {
            str = realloc(str,sizeof(char)*(size+=10));
            if(!str)return str;
        }
    }
    str[len++]='\0';
    printf("%s\n",str);
    free(str);
}

Get last record of a table in Postgres

The last inserted record can be queried using this assuming you have the "id" as the primary key:

SELECT timestamp,value,card FROM my_table WHERE id=(select max(id) from my_table)

Assuming every new row inserted will use the highest integer value for the table's id.

How can I set the value of a DropDownList using jQuery?

There are many ways to do it. here are some of them:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3);

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

Regex for allowing alphanumeric,-,_ and space

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

Difference between Destroy and Delete

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

Which are more performant, CTE or temporary tables?

This is a really open ended question, and it all depends on how its being used and the type of temp table (Table variable or traditional table).

A traditional temp table stores the data in the temp DB, which does slow down the temp tables; however table variables do not.

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Checking if float is an integer

This deals with computational round-off. You set the epsilon as desired:

bool IsInteger(float value)
{
    return fabs(ceilf(value) - value) < EPSILON;
}

LINQ - Left Join, Group By, and Count

 (from p in context.ParentTable     
  join c in context.ChildTable 
    on p.ParentId equals c.ChildParentId into j1 
  from j2 in j1.DefaultIfEmpty() 
     select new { 
          ParentId = p.ParentId,
         ChildId = j2==null? 0 : 1 
      })
   .GroupBy(o=>o.ParentId) 
   .Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })

How to restart VScode after editing extension's config?

Execute the workbench.action.reloadWindow command.

There are some ways to do so:

  1. Open the command palette (Ctrl + Shift + P) and execute the command:

    >Reload Window    
    
  2. Define a keybinding for the command (for example CTRL+F5) in keybindings.json:

    [
      {
        "key": "ctrl+f5",
        "command": "workbench.action.reloadWindow",
        "when": "editorTextFocus"
      }
    ]
    

Specify an SSH key for git push for a given domain

You can utilize git environment variable GIT_SSH_COMMAND. Run this in your terminal under your git repository:

GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init

Replace ~/.ssh/your_private_key with the path of ssh private key you wanna use. And you can change the subsequent git command (in the example is git submodule update --init) to others like git pull, git fetch, etc.

Good way of getting the user's location in Android

Looks like we're coding the same application ;-)
Here is my current implementation. I'm still in the beta testing phase of my GPS uploader app, so there might be many possible improvements. but it seems to work pretty well so far.

/**
 * try to get the 'best' location selected from all providers
 */
private Location getBestLocation() {
    Location gpslocation = getLocationByProvider(LocationManager.GPS_PROVIDER);
    Location networkLocation =
            getLocationByProvider(LocationManager.NETWORK_PROVIDER);
    // if we have only one location available, the choice is easy
    if (gpslocation == null) {
        Log.d(TAG, "No GPS Location available.");
        return networkLocation;
    }
    if (networkLocation == null) {
        Log.d(TAG, "No Network Location available");
        return gpslocation;
    }
    // a locationupdate is considered 'old' if its older than the configured
    // update interval. this means, we didn't get a
    // update from this provider since the last check
    long old = System.currentTimeMillis() - getGPSCheckMilliSecsFromPrefs();
    boolean gpsIsOld = (gpslocation.getTime() < old);
    boolean networkIsOld = (networkLocation.getTime() < old);
    // gps is current and available, gps is better than network
    if (!gpsIsOld) {
        Log.d(TAG, "Returning current GPS Location");
        return gpslocation;
    }
    // gps is old, we can't trust it. use network location
    if (!networkIsOld) {
        Log.d(TAG, "GPS is old, Network is current, returning network");
        return networkLocation;
    }
    // both are old return the newer of those two
    if (gpslocation.getTime() > networkLocation.getTime()) {
        Log.d(TAG, "Both are old, returning gps(newer)");
        return gpslocation;
    } else {
        Log.d(TAG, "Both are old, returning network(newer)");
        return networkLocation;
    }
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private Location getLocationByProvider(String provider) {
    Location location = null;
    if (!isProviderSupported(provider)) {
        return null;
    }
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Cannot acces Provider " + provider);
    }
    return location;
}

Edit: here is the part that requests the periodic updates from the location providers:

public void startRecording() {
    gpsTimer.cancel();
    gpsTimer = new Timer();
    long checkInterval = getGPSCheckMilliSecsFromPrefs();
    long minDistance = getMinDistanceFromPrefs();
    // receive updates
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    for (String s : locationManager.getAllProviders()) {
        locationManager.requestLocationUpdates(s, checkInterval,
                minDistance, new LocationListener() {

                    @Override
                    public void onStatusChanged(String provider,
                            int status, Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}

                    @Override
                    public void onLocationChanged(Location location) {
                        // if this is a gps location, we can use it
                        if (location.getProvider().equals(
                                LocationManager.GPS_PROVIDER)) {
                            doLocationUpdate(location, true);
                        }
                    }
                });
        // //Toast.makeText(this, "GPS Service STARTED",
        // Toast.LENGTH_LONG).show();
        gps_recorder_running = true;
    }
    // start the gps receiver thread
    gpsTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Location location = getBestLocation();
            doLocationUpdate(location, false);
        }
    }, 0, checkInterval);
}

public void doLocationUpdate(Location l, boolean force) {
    long minDistance = getMinDistanceFromPrefs();
    Log.d(TAG, "update received:" + l);
    if (l == null) {
        Log.d(TAG, "Empty location");
        if (force)
            Toast.makeText(this, "Current location not available",
                    Toast.LENGTH_SHORT).show();
        return;
    }
    if (lastLocation != null) {
        float distance = l.distanceTo(lastLocation);
        Log.d(TAG, "Distance to last: " + distance);
        if (l.distanceTo(lastLocation) < minDistance && !force) {
            Log.d(TAG, "Position didn't change");
            return;
        }
        if (l.getAccuracy() >= lastLocation.getAccuracy()
                && l.distanceTo(lastLocation) < l.getAccuracy() && !force) {
            Log.d(TAG,
                    "Accuracy got worse and we are still "
                      + "within the accuracy range.. Not updating");
            return;
        }
        if (l.getTime() <= lastprovidertimestamp && !force) {
            Log.d(TAG, "Timestamp not never than last");
            return;
        }
    }
    // upload/store your location here
}

Things to consider:

  • do not request GPS updates too often, it drains battery power. I currently use 30 min as default for my application.

  • add a 'minimum distance to last known location' check. without this, your points will "jump around" when GPS is not available and the location is being triangulated from the cell towers. or you can check if the new location is outside of the accuracy value from the last known location.

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Difference between decimal, float and double in .NET?

In simple words:

  1. The Decimal, Double, and Float variable types are different in the way that they store the values.
  2. Precision is the main difference (Notice that this is not the single difference) where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
  3. The summary table:

/==========================================================================================
    Type       Bits    Have up to                   Approximate Range 
/==========================================================================================
    float      32      7 digits                     -3.4 × 10 ^ (38)   to +3.4 × 10 ^ (38)
    double     64      15-16 digits                 ±5.0 × 10 ^ (-324) to ±1.7 × 10 ^ (308)
    decimal    128     28-29 significant digits     ±7.9 x 10 ^ (28) or (1 to 10 ^ (28)
/==========================================================================================
You can read more here, Float, Double, and Decimal.

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

How to bind an enum to a combobox control in WPF?

I wouldn't recommend implementing this as it is but hopefully this can inspire a good solution.

Let's say your enum is Foo. Then you can do something like this.

public class FooViewModel : ViewModel
{
    private int _fooValue;

    public int FooValue
    {
        get => _fooValue;
        set
        {
            _fooValue = value;
            OnPropertyChange();
            OnPropertyChange(nameof(Foo));
            OnPropertyChange(nameof(FooName));
        }
    }
    public Foo Foo 
    { 
        get => (Foo)FooValue; 
        set 
        { 
            _fooValue = (int)value;
            OnPropertyChange();
            OnPropertyChange(nameof(FooValue));
            OnPropertyChange(nameof(FooName));
        } 
    }
    public string FooName { get => Enum.GetName(typeof(Foo), Foo); }

    public FooViewModel(Foo foo)
    {
        Foo = foo;
    }
}

Then on Window.Load method you can load all enums to an ObservableCollection<FooViewModel> which you can set as the DataContext of the combobox.

How to catch a click event on a button?

/src/com/example/MyClass.java

package com.example

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MyClass extends Activity
{

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
         ImageView iv = (ImageView) findViewById(R.id.imageview1);
         iv.setVisibility(View.VISIBLE);
      }
    });

  }
}

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <Button 
      android:text="Button"
      android:id="@+id/button1"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
    />
    <ImageView 
      android:src="@drawable/image" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:id="@+id/imageview1"
      android:visibility="invisible"
    />
</LinearLayout>

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

How does one check if a table exists in an Android SQLite database?

Important condition is IF NOT EXISTS to check table is already exist or not in database

like...

String query = "CREATE TABLE IF NOT EXISTS " + TABLE_PLAYER_PHOTO + "("
            + KEY_PLAYER_ID + " TEXT,"
            + KEY_PLAYER_IMAGE + " TEXT)";
db.execSQL(query);

How can you create multiple cursors in Visual Studio Code

In my XFCE (version 4.12), it's in Settings -> Window Manager Tweaks -> Accessibility.

There's a dropdown field Key used to grab and move windows:, set this to None.

Alt + Click works now in VS Code to add more cursor.

Serialize form data to JSON

I know this doesn't meet the helper function requirement, but the way I've done this is using jQuery's $.each() method

var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
    function(i, v) {
        loginFormObject[v.name] = v.value;
    });

Then I can pass loginFormObject to my backend, or you could create a userobject and save() it in backbone as well.

Delegates in swift?

DELEGATES IN SWIFT 2

I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.

Class with Protocol Declaration

protocol  getDataDelegate  {
    func getDataFromAnotherVC(temp: String)
}


import UIKit
class SecondVC: UIViewController {

    var delegateCustom : getDataDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func backToMainVC(sender: AnyObject) {
      //calling method defined in first View Controller with Object  
      self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
        self.navigationController?.popViewControllerAnimated(true)
    }
    
}

In First ViewController Protocol conforming is done here:

class ViewController: UIViewController, getDataDelegate

Protocol method definition in First View Controller(ViewController)

func getDataFromAnotherVC(temp : String)
{
  // dataString from SecondVC
   lblForData.text = dataString
}

During push the SecondVC from First View Controller (ViewController)

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This will work, Try this -

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.

How do I get JSON data from RESTful service using Python?

I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:

import requests

response = requests.get('http://thedataishere.com',
                         auth=('user', 'password'))
data = response.json()

For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:

import requests
from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',
                         auth=HTTPKerberosAuth())
data = response.json()

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had this problem and then I ran "apache_start.bat" the error in german told me there was a problem with line 51 in httpd-ssl.conf which is

SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5

What I did was comment lines 163 (ssl module) and 522 (httpd-ssl.conf include) in httpd.conf; I don't need ssl for development, so that solved it for me.

Convert a Pandas DataFrame to a dictionary

Should a dictionary like:

{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}

be required out of a dataframe like:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

simplest way would be to do:

dict(df.values)

working snippet below:

import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)

'Missing contentDescription attribute on image' in XML

Add android:contentDescription="@string/description" (static or dynamic) to your ImageView. Please do not ignore nor filter the message, because it is helpfull for people using alternative input methods because of their disability (Like TalkBack, Tecla Access Shield etc etc).

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

Command-line svn for Windows?

Install MSYS2, it has svn in its repository (besides lots of other Unix goodies). MSYS2 installs without Windows Admin rights.

$ pacman -S svn

The tools can be used from cmd, too:

C:\>C:\msys64\usr\bin\svn.exe co http://somehost/somerepo/

Python main call within class

That entire block is misplaced.

class Example(object):
    def main(self):     
        print "Hello World!"

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

But you really shouldn't be using a class just to run your main code.

Checking if output of a command contains a certain string in a shell script

A clean if/else conditional shell script:

if ./somecommand | grep -q 'some_string'; then
  echo "exists"
else
  echo "doesn't exist"
fi

FFmpeg: How to split video efficiently?

Didn't test ist, but this looks promising:

Basic stream segmenter

It is obviously splitting AVI into segments of same size, which implies these chunks don't loose quality or increase memory or must be recalculated.

It also uses the codec copy - does that mean it can handle very large streams ? Because this is my problem, i want to break down my avi so i could use a filter to get rid of the distorsion. But a whole avi runs for hours.

Get current URL/URI without some of $_GET variables

To get the absolute current request url (exactly as seen in the address bar, with GET params and http://) I found that the following works well:

Yii::app()->request->hostInfo . Yii::app()->request->url

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

How can I rename a single column in a table at select?

There is no need to use AS, just use:

SELECT table1.price Table1 Price, table2.price Table2 Price, .....

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

Row count where data exists

Assuming that your Sheet1 is not necessary active you would need to use this improved code of yours:

i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count

Look into full worksheet reference for second argument for Range(arg1, arg2) which important in this situation.

How to trigger click event on href element

In addition to romkyns's great answer.. here is some relevant documentation/examples.


DOM Elements have a native .click() method.

The HTMLElement.click() method simulates a mouse click on an element.

When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an <a> element to initiate navigation as if a real mouse-click had been received. (mdn reference)

Relevant W3 documentation.


A few examples..

  • You can access a specific DOM element from a jQuery object: (example)

      $('a')[0].click();
    
  • You can use the .get() method to retrieve a DOM element from a jQuery object: (example)

      $('a').get(0).click();
    
  • As expected, you can select the DOM element and call the .click() method. (example)

      document.querySelector('a').click();
    

It's worth pointing out that jQuery is not required to trigger a native .click() event.

Fragments within Fragments

If you find your nested fragment not being removed or being duplicated (eg. on Activity restart, on screen rotate) try changing:

transaction.add(R.id.placeholder, newFragment);

to

transaction.replace(R.id.placeholder, newFragment);

If above doesn't help, try:

Fragment f = getChildFragmentManager().findFragmentById(R.id.placeholder);

FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

if (f == null) {
    Log.d(TAG, "onCreateView: fragment doesn't exist");
    newFragment= new MyFragmentType();
    transaction.add(R.id.placeholder, newFragment);
} else {
    Log.d(TAG, "onCreateView: fragment already exists");
    transaction.replace(R.id.placeholder, f);
}
transaction.commit();

Learnt here

Allow 2 decimal places in <input type="number">

Try this for allowing only 2 decimal in input type

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

javascript: detect scroll end

I found an alternative that works.

None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.

Implemented solution:

function IsScrollbarAtBottom() {
    var documentHeight = $(document).height();
    var scrollDifference = $(window).height() + $(window).scrollTop();
    return (documentHeight == scrollDifference);
}

Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html

Regards

Maven plugins can not be found in IntelliJ

Tried invalidating cache, reimporting the project, removing .m2 folder partially and as a whole, and switching to the Idea bundled Maven. Nothing worked, and I've finally broken Maven completely: when it would build the project in the console, now it stopped. Had to reinstall Maven, and it helped!

How to support different screen size in android

You can figure out the dimensions of the screen dynamically

Display mDisplay= activity.getWindowManager().getDefaultDisplay();
int width= mDisplay.getWidth();
int Height= mDisplay.getHeight();

The layout can be set using the width and the height obtained using this method.

How to test if a DataSet is empty?

If (ds != null)

Should do the work for you!

Run a php app using tomcat?

If anyone's still looking - Quercus has a war that allows to run PHP scripts in apache tomcat or glassfish. For a step by step guide look at this article

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

C++ - how to find the length of an integer

Not necessarily the most efficient, but one of the shortest and most readable using C++:

std::to_string(num).length()

setTimeout in React Native

const getData = () => {
// some functionality
}

const that = this;
   setTimeout(() => {
   // write your functions    
   that.getData()
},6000);

Simple, Settimout function get triggered after 6000 milliseonds

How to add two strings as if they were numbers?

var result = Number(num1) + Number(num2);

How to stash my previous commit?

If it were me, I would avoid any risky revision editing and do the following instead:

  1. Create a new branch on the SHA where 222 was committed, basically as a bookmark.

  2. Switch back to the main branch. In it, revert commit 222.

  3. Push all the commits that have been made, which will push commit 111 only, because 222 was reverted.

  4. Work on the branch from step #1 if needed. Merge from the trunk to it as needed to keep it up to date. I wouldn't bother with stash.

When it's time for the changes in commit 222 to go in, that branch can be merged to trunk.

JSON to pandas DataFrame

I prefer a more generic method in which may be user doesn't prefer to give key 'results'. You can still flatten it by using a recursive approach of finding key having nested data or if you have key but your JSON is very nested. It is something like:

from pandas import json_normalize

def findnestedlist(js):
    for i in js.keys():
        if isinstance(js[i],list):
            return js[i]
    for v in js.values():
        if isinstance(v,dict):
            return check_list(v)


def recursive_lookup(k, d):
    if k in d:
        return d[k]
    for v in d.values():
        if isinstance(v, dict):
            return recursive_lookup(k, v)
    return None

def flat_json(content,key):
    nested_list = []
    js = json.loads(content)
    if key is None or key == '':
        nested_list = findnestedlist(js)
    else:
        nested_list = recursive_lookup(key, js)
    return json_normalize(nested_list,sep="_")

key = "results" # If you don't have it, give it None

csv_data = flat_json(your_json_string,root_key)
print(csv_data)

I do not want to inherit the child opacity from the parent in CSS

Opacity is not actually inherited in CSS. It's a post-rendering group transform. In other words, if a <div> has opacity set you render the div and all its kids into a temporary buffer, and then composite that whole buffer into the page with the given opacity setting.

What exactly you want to do here depends on the exact rendering you're looking for, which is not clear from the question.

Fragment pressing back button

This is a working solution for me:

dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            // DO WHAT YOU WANT ON BACK PRESSED
                            return true;
                        }
                        return false;
                    }
                });

Edit: You can replace dialog with getView() for fragments.

inserting characters at the start and end of a string

If you want to insert other string somewhere else in existing string, you may use selection method below.

Calling character on second position:

>>> s = "0123456789"
>>> s[2]
'2'

Calling range with start and end position:

>>> s[4:6]
'45'

Calling part of a string before that position:

>>> s[:6]
'012345'

Calling part of a string after that position:

>>> s[4:]
'456789'

Inserting your string in 5th position.

>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'

Also s is equivalent to s[:].

With your question you can use all your string, i.e.

>>> s = "L" + s + "LL"

or if "L" is a some other string (for example I call it as l), then you may use that code:

>>> s = l + s + (l * 2)

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

pg_config is for compliation information, to help extensions and client programs compile and link against PostgreSQL. It knows nothing about the active PostgreSQL instance(s) on the machine, only the binaries.

pg_hba.conf can appear in many other places depending on how Pg was installed. The standard location is pg_hba.conf within the data_directory of the database (which could be in /home, /var/lib/pgsql, /var/lib/postgresql/[version]/, /opt/postgres/, etc etc etc) but users and packagers can put it wherever they like. Unfortunately.

The only valid ways find pg_hba.conf is to ask a running PostgreSQL instance where it's pg_hba.conf is, or ask the sysadmin where it is. You can't even rely on asking where the datadir is and parsing postgresql.conf because an init script might passed a param like -c hba_file=/some/other/path when starting Pg.

What you want to do is ask PostgreSQL:

SHOW hba_file;

This command must be run on a superuser session, so for shell scripting you might write something like:

psql -t -P format=unaligned -c 'show hba_file';

and set the environment variables PGUSER, PGDATABASE, etc to ensure that the connection is right.

Yes, this is somewhat of a chicken-and-egg problem, in that if the user can't connect (say, after screwing up editing pg_hba.conf) you can't find pg_hba.conf in order to fix it.

Another option is to look at the ps command's output and see if the postmaster data directory argument -D is visible there, e.g.

ps aux  | grep 'postgres *-D'

since pg_hba.conf will be inside the data directory (unless you're on Debian/Ubuntu or some derivative and using their packages).

If you're targeting specifically Ubuntu systems with PostgreSQL installed from Debian/Ubuntu packages it gets a little easier. You don't have to deal with hand-compiled-from-source Pg that someone's initdb'd a datadir for in their home dir, or an EnterpriseDB Pg install in /opt, etc. You can ask pg_wrapper, the Debian/Ubuntu multi-version Pg manager, where PostgreSQL is using the pg_lsclusters command from pg_wrapper.

If you can't connect (Pg isn't running, or you need to edit pg_hba.conf to connect) you'll have to search the system for pg_hba.conf files. On Mac and Linux something like sudo find / -type f -name pg_hba.conf will do. Then check the PG_VERSION file in the same directory to make sure it's the right PostgreSQL version if you have more than one. (If pg_hba.conf is in /etc/, ignore this, it's the parent directory name instead). If you have more than one data directory for the same PostgreSQL version you'll have to look at database size, check the command line of the running postgres from ps to see if it's data directory -D argument matches where you're editing, etc. https://askubuntu.com/questions/256534/how-do-i-find-the-path-to-pg-hba-conf-from-the-shell/256711

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

How to lowercase a pandas dataframe string column if it has missing values?

Use apply function,

Xlower = df['x'].apply(lambda x: x.upper()).head(10) 

What is ANSI format?

Technically, ANSI should be the same as US-ASCII. It refers to the ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII. Use of the top-bit-set characters is not defined in ASCII/ANSI as it is a 7-bit character set.

However years of misuse of the term by the DOS and subsequently Windows community has left its practical meaning as “the system codepage of whatever machine is being used”. The system codepage is also sometimes known as ‘mbcs’, since on East Asian systems that can be a multiple-byte-per-character encoding. Some code pages can even use top-bit-clear bytes as trailing bytes in a multibyte sequence, so it's not even strict compatible with plain ASCII... but even then, it's still called “ANSI”.

On US and Western European default settings, “ANSI” maps to Windows code page 1252. This is not the same as ISO-8859-1 (although it is quite similar). On other machines it could be anything else at all. This makes “ANSI” utterly useless as an external encoding identifier.

How to allow <input type="file"> to accept only image files?

If you want to upload multiple images at once you can add multiple attribute to input.

_x000D_
_x000D_
upload multiple files: <input type="file" multiple accept='image/*'>
_x000D_
_x000D_
_x000D_

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

When I went to create a laravel project, I got this problem.

After googling, I got this solution.

I followed these steps:

Step 1: sudo apt-get install -y php7.2-gd

Step 2: sudo apt-get install php7.2-intl

Step 3: sudo apt-get install php7.2-xsl

Step 4: sudo apt-get install php7.2-mbstring

How to replace existing value of ArrayList element in Java

You must use

list.remove(indexYouWantToReplace);

first.

Your elements will become like this. [zero, one, three]

then add this

list.add(indexYouWantedToReplace, newElement)

Your elements will become like this. [zero, one, new, three]

Return multiple values from a function in swift

Update Swift 4.1

Here we create a struct to implement the Tuple usage and validate the OTP text length. That needs to be of 2 fields for this example.

struct ValidateOTP {
var code: String
var isValid: Bool }

func validateTheOTP() -> ValidateOTP {
    let otpCode = String(format: "%@%@", txtOtpField1.text!, txtOtpField2.text!)
    if otpCode.length < 2 {
        return ValidateOTP(code: otpCode, isValid: false)
    } else {
        return ValidateOTP(code: otpCode, isValid: true)
    }
}

Usage:

let isValidOTP = validateTheOTP()
    if isValidOTP.isValid { print(" valid OTP") } else {   self.alert(msg: "Please fill the valid OTP", buttons: ["Ok"], handler: nil)
    }

Hope it helps!

Thanks

How do I minimize the command prompt from my bat file

Use the start command, with the /min switch to run minimized. For example:

start /min C:\Ruby192\bin\setrbvars.bat

Since you've specified a batch file as the argument, the command processor is run, passing the /k switch. This means that the window will remain on screen after the command has finished. You can alter that behavior by explicitly running cmd.exe yourself and passing the appropriate switches if necessary.

Alternatively, you can create a shortcut to the batch file (are PIF files still around), and then alter its properties so that it starts minimized.

Cross compile Go on OSX?

You can do this pretty easily using Docker, so no extra libs required. Just run this command:

docker run --rm -it -v "$GOPATH":/go -w /go/src/github.com/iron-io/ironcli golang:1.4.2-cross sh -c '
for GOOS in darwin linux windows; do
  for GOARCH in 386 amd64; do
    echo "Building $GOOS-$GOARCH"
    export GOOS=$GOOS
    export GOARCH=$GOARCH
    go build -o bin/ironcli-$GOOS-$GOARCH
  done
done
'

You can find more details in this post: https://medium.com/iron-io-blog/how-to-cross-compile-go-programs-using-docker-beaa102a316d

Using npm behind corporate proxy .pac

I had a similar issue and I tried all the workarounds above but none of them worked for me ( I was using special characters (like '@' symbol) in my password and I also needed to add domain name).

Apart from that I was bit apprehensive to add my password as plain text. It turned-out the easiest solution to overcome all these challenges was to use some sort of reverse proxy (like Fiddler).

I have already detailed the configuration steps in this answer in SO.

How to echo xml file in php

Here's what worked for me:

<pre class="prettyprint linenums">
    <code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code>
</pre>

Using htmlspecialchars will prevent tags from being displayed as html and won't break anything. Note that I'm using Prettyprint to highlight the code ;)

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

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

You can divide seconds by 60 to get the minutes

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

When you divide it by 60 again, you will get the hours

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

Can we add div inside table above every <tr>?

No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.

I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.

How do I change db schema to dbo

ALTER SCHEMA dbo TRANSFER jonathan.MovieData;

See ALTER SCHEMA.

Generalized Syntax:

ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName; 

How to remove old and unused Docker images

To remove old tagged images that are more than a month old:

$ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
    | grep ' months' | awk '{ print $1 }' \
    | xargs --no-run-if-empty docker rmi

Note that it'll fail to remove images that are used by a container, referenced in a repository, has dependent child images... which is probably what you want. Else just add -f flag.

Example of /etc/cron.daily/docker-gc script:

#!/bin/sh -e

# Delete all stopped containers (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v

# Delete all tagged images more than a month old
# (will fail to remove images still used).
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true

# Delete all 'untagged/dangling' (<none>) images
# Those are used for Docker caching mechanism.
docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi

# Delete all dangling volumes.
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

enter image description hereFirst of all stop all the mongoDB services, then create a directory on / , it means root, if you don't have, and remove the port file also. give all permission to that directory, become that directory owner, run below command:

sudo service mongod stop
sudo rm -rf /tmp/mongod*
sudo mkdir -p /data/db
sudo chmod -R a+wxr /data
sudo chown -R $USER:$USER /data

Now you're done, just start the MongoDB service, if didn't help, try to change the port like:

sudo service mongod restart && mongod # if didn't help run below cmd
mongod --port 27018

Note: For me all this stuff works and hoping would work for you, guy!

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}