Programs & Examples On #Logmein

LogMeIn is a suite of software services that provides remote access to computers over the Internet.

How is TeamViewer so fast?

Oddly. but in my experience TeamViewer is not faster/more responsive than VNC, only easier to setup. I have a couple of win-boxen that I VNC over OpenVPN into (so there is another overhead layer) and that's on cheap Cable (512 up) and I find properly setup TightVNC to be much more responsive than TeamViewer to same boxen. RDP (naturally) even more so since by large part it sends GUI draw commands instead of bitmap tiles.

Which brings us to:

  1. Why are you not using VNC? There are plethora of open source solutions, and Tight is probably on top of it's game right now.

  2. Advanced VNC implementations use lossy compression and that seems to achieve better results than your choice of PNG. Also, IIRC the rest of the payload is also squashed using zlib. Bothj Tight and UltraVNC have very optimized algos, especially for windows. On top of that Tight is open-source.

  3. If win boxen are your primary target RDP may be a better option, and has an opensource implementation (rdesktop)

  4. If *nix boxen are your primary target NX may be a better option and has an open source implementation (FreeNX, albeit not as optimised as NoMachine's proprietary product).

If compressing JPEG is a performance issue for your algo, I'm pretty sure that image comparison would still take away some performance. I'd bet they use best-case compression for every specific situation ie lossy for large frames, some quick and dirty internall losless for smaller ones, compare bits of images and send only diffs of sort and bunch of other optimisation tricks.

And a lot of those tricks must be present in Tight > 2.0 since again, in my experience it beats the hell out of TeamViewer performance wyse, YMMV.

Also the choice of a JIT compiled runtime over something like C++ might take a slice from your performance edge, especially in memory constrained machines (a lot of performance tuning goes to the toilet when windows start using the pagefile intensively). And you will need memory to keep previous image states for internal comparison atop of what DF mirage gives you.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

If you are not worried about an unbounded queue of Callable/Runnable tasks, you can use one of them. As suggested by bruno, I too prefer newFixedThreadPool to newCachedThreadPool over these two.

But ThreadPoolExecutor provides more flexible features compared to either newFixedThreadPool or newCachedThreadPool

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, 
TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler)

Advantages:

  1. You have full control of BlockingQueue size. It's not un-bounded, unlike the earlier two options. I won't get an out of memory error due to a huge pile-up of pending Callable/Runnable tasks when there is unexpected turbulence in the system.

  2. You can implement custom Rejection handling policy OR use one of the policies:

    1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

    2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.

    3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.

    4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

  3. You can implement a custom Thread factory for the below use cases:

    1. To set a more descriptive thread name
    2. To set thread daemon status
    3. To set thread priority

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

How to change the author and committer name and e-mail of multiple commits in Git?

Try this out. It will do the same as above mentioned, but interactively.

bash <(curl -s  https://raw.githubusercontent.com/majdarbash/git-author-change-script/master/run.sh)

Reference: https://github.com/majdarbash/git-author-change-script

PHP - Failed to open stream : No such file or directory

Add script with query parameters

That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value, PHP looks for file named script.php?parameter=value, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=... or $GLOBALS[]=... or other way you like.

Using Bootstrap Modal window as PartialView

I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.

How do I format a number with commas in T-SQL?

`/* Author: Tsiridis Dimitris */
/* Greek amount format. For the other change the change on replace of '.' & ',' */
CREATE FUNCTION dbo.formatAmount  (
@amtIn as varchar(20)
) RETURNS varchar(20)
AS
BEGIN 

return cast(REPLACE(SUBSTRING(CONVERT(varchar(20), CAST(@amtIn AS money), 1),1,
LEN(CONVERT(varchar(20), CAST(@amtIn AS money), 1))-3), ',','.')
 + replace(RIGHT(CONVERT(varchar(20), CAST(@amtIn AS money), 1),3), '.',',') AS VARCHAR(20))

END

SELECT [geniki].[dbo].[formatAmount]('9888777666555.44')`

Converting from longitude\latitude to Cartesian coordinates

You can do it this way on Java.

public List<Double> convertGpsToECEF(double lat, double longi, float alt) {

    double a=6378.1;
    double b=6356.8;
    double N;
    double e= 1-(Math.pow(b, 2)/Math.pow(a, 2));
    N= a/(Math.sqrt(1.0-(e*Math.pow(Math.sin(Math.toRadians(lat)), 2))));
    double cosLatRad=Math.cos(Math.toRadians(lat));
    double cosLongiRad=Math.cos(Math.toRadians(longi));
    double sinLatRad=Math.sin(Math.toRadians(lat));
    double sinLongiRad=Math.sin(Math.toRadians(longi));
    double x =(N+0.001*alt)*cosLatRad*cosLongiRad;
    double y =(N+0.001*alt)*cosLatRad*sinLongiRad;
    double z =((Math.pow(b, 2)/Math.pow(a, 2))*N+0.001*alt)*sinLatRad;

    List<Double> ecef= new ArrayList<>();
    ecef.add(x);
    ecef.add(y);
    ecef.add(z);

    return ecef;


}

Sorting multiple keys with Unix sort

Use the -k option (or --key=POS1[,POS2]). It can appear multiple times and each key can have global options (such as n for numeric sort)

How to find locked rows in Oracle

Given some table, you can find which rows are not locked with SELECT FOR UPDATESKIP LOCKED.

For example, this query will lock (and return) every unlocked row:

SELECT * FROM mytable FOR UPDATE SKIP LOCKED

References

What is the difference between .text, .value, and .value2?

.Text gives you a string representing what is displayed on the screen for the cell. Using .Text is usually a bad idea because you could get ####

.Value2 gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)

.Value gives you the same as .Value2 except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.

Using .Value or .Text is usually a bad idea because you may not get the real value from the cell, and they are slower than .Value2

For a more extensive discussion see my Text vs Value vs Value2

How do Python's any and all functions work?

The code in question you're asking about comes from my answer given here. It was intended to solve the problem of comparing multiple bit arrays - i.e. collections of 1 and 0.

any and all are useful when you can rely on the "truthiness" of values - i.e. their value in a boolean context. 1 is True and 0 is False, a convenience which that answer leveraged. 5 happens to also be True, so when you mix that into your possible inputs... well. Doesn't work.

You could instead do something like this:

[len(set(x)) > 1 for x in zip(*d['Drd2'])]

It lacks the aesthetics of the previous answer (I really liked the look of any(x) and not all(x)), but it gets the job done.

How do I hide certain files from the sidebar in Visual Studio Code?

I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.

Hit F1 for vscode command line (command palette), then

ext install [enter] peep [enter]

You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep, select Peep Toggle and add your binding.

How do I open phone settings when a button is clicked?

App-Prefs:root=Privacy&path=LOCATION worked for me for getting to general location settings. Note: only works on a device.

How do I keep the screen on in my App?

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

getWindow is a method defined for activities, and won't require you to find a View first.

Java: Instanceof and Generics

The runtime type of the object is a relatively arbitrary condition to filter on. I suggest keeping such muckiness away from your collection. This is simply achieved by having your collection delegate to a filter passed in a construction.

public interface FilterObject {
     boolean isAllowed(Object obj);
}

public class FilterOptimizedList<E> implements List<E> {
     private final FilterObject filter;
     ...
     public FilterOptimizedList(FilterObject filter) {
         if (filter == null) {
             throw NullPointerException();
         }
         this.filter = filter;
     }
     ...
     public int indexOf(Object obj) {
         if (!filter.isAllows(obj)) {
              return -1;
         }
         ...
     }
     ...
}

     final List<String> longStrs = new FilterOptimizedList<String>(
         new FilterObject() { public boolean isAllowed(Object obj) {
             if (obj == null) {
                 return true;
             } else if (obj instanceof String) {
                 String str = (String)str;
                 return str.length() > = 4;
             } else {
                 return false;
             }
         }}
     );

How to select rows for a specific date, ignoring time in SQL Server

select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy

The more correct way to do it:

DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)

If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >= and <

you can do it within one single statement, but it's just that the value is used twice.

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

Vue.js unknown custom element

I had the same error

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

however, I totally forgot to run npm install && npm run dev to compiling the js files.

maybe this helps newbies like me.

Travel/Hotel API's?

Try Tixik.com and their API there. They have a very different data that big players, really good coverage mostly in Europe and good API conditions.

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

onclick event function in JavaScript

Check you are calling same function or not.

<script>function greeting(){document.write("hi");}</script>

<input type="button" value="Click Here" onclick="greeting();"/>

How to initialize var?

you cannot assign null to a var type.

If you assign null the compiler cannot find the variable you wanted in var place.

throws error: Cannot assign <null> to an implicitly-typed local variable

you can try this:

var dummy =(string)null;

Here compiler can find the type you want so no problem

You can assign some empty values.

var dummy = string.Empty;

or

var dummy = 0;

Easiest way to convert int to string in C++

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

Python SQLite: database is locked

In Linux you can do something similar, for example, if your locked file is development.db:

$ fuser development.db This command will show what process is locking the file:

development.db: 5430 Just kill the process...

kill -9 5430 ...And your database will be unlocked.

hadoop copy a local file system folder to HDFS

Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:

To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"

eg)./hadoop fs -put /opt/csv/load.csv /user/load

Here the /opt/csv/load.csv is source file path from my local linux system.

/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"

To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"

eg)hadoop fs -get /user/load/a.csv /opt/csv/

After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.

This uploaded files could also be seen through HDFS NameNode web UI.

How do I set the default Java installation/runtime (Windows)?

I just had that problem (Java 1.8 vs. Java 9 on Windows 7) and my findings are:

short version

default seems to be (because of Path entry)

c:\ProgramData\Oracle\Java\javapath\java -version

select the version you want (test, use tab completing in cmd, not sure what those numbers represent), I had 2 options, see longer version for details

c:\ProgramData\Oracle\Java\javapath_target_[tab]

remove junction/link and link to your version (the one ending with 181743567 in my case for Java 8)

rmdir javapath
mklink /D javapath javapath_target_181743567

longer version:

Reinstall Java 1.8 after Java 9 didn't work. The sequence of installations was jdk1.8.0_74, jdk-9.0.4 and attempt to make Java 8 default with jdk1.8.0_162...

After jdk1.8.0_162 installation I still have

java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

What I see in path is

Path=...;C:\ProgramData\Oracle\Java\javapath;...

So I checked what is that and I found it is a junction (link)

c:\ProgramData\Oracle\Java>dir
 Volume in drive C is OSDisk
 Volume Serial Number is DA2F-C2CC

 Directory of c:\ProgramData\Oracle\Java

2018-02-07  17:06    <DIR>          .
2018-02-07  17:06    <DIR>          ..
2018-02-08  17:08    <DIR>          .oracle_jre_usage
2017-08-22  11:04    <DIR>          installcache
2018-02-08  17:08    <DIR>          installcache_x64
2018-02-07  17:06    <JUNCTION>     javapath [C:\ProgramData\Oracle\Java\javapath_target_185258831]
2018-02-07  17:06    <DIR>          javapath_target_181743567
2018-02-07  17:06    <DIR>          javapath_target_185258831

Those hashes doesn't ring a bell, but when I checked

c:\ProgramData\Oracle\Java\javapath_target_181743567>.\java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

c:\ProgramData\Oracle\Java\javapath_target_185258831>.\java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

so to make Java 8 default again I had to delete the link as described here

rmdir javapath

and recreate with Java I wanted

mklink /D javapath javapath_target_181743567

tested:

c:\ProgramData\Oracle\Java>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

** update (Java 10) **

With Java 10 it is similar, only javapath is in c:\Program Files (x86)\Common Files\Oracle\Java\ which is strange as I installed 64-bit IMHO

.\java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)

How do I catch a numpy warning like it's an exception (not just for testing)?

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

Bootstrap 4 File Input

For Bootstrap v.5

document.querySelectorAll('.form-file-input')
        .forEach(el => el.addEventListener('change', e => e.target.parentElement.querySelector('.form-file-text').innerText = e.target.files[0].name));

Affect all file input element. No need to specify elements id.

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

Truncate Decimal number not Round Off

Maybe another quick solution could be:

>>> float("%.1f" % 1.00001)
1.0
>>> float("%.3f" % 1.23001)
1.23
>>> float("%.5f" % 1.23001)
1.23001

json_encode is returning NULL?

few day ago I have the SAME problem with 1 table.

Firstly try:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

Find position of a node using xpath

Just a note to the answer done by James Sulak.

If you want to take into consideration that the node may not exist and want to keep it purely XPATH, then try the following that will return 0 if the node does not exist.

count(a/b[.='tsr']/preceding-sibling::*)+number(boolean(a/b[.='tsr']))

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

Convert UTC/GMT time to local time

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

How do we adjust for the extra hour?

Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

By the looks the code might look something like:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

Kill process by name?

Assuming you're on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

gives you ps -A's output in the out variable (a string). You can break it down into lines and loop on them...:

>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

(you could avoid importing signal, and use 9 instead of signal.SIGKILL, but I just don't particularly like that style, so I'd rather used the named constant this way).

Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.

If what you're after is avoiding ps, that's hard to do across different Unix-like systems (ps is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.

how to destroy an object in java?

Answer E is correct answer. If E is not there, you will soon run out of memory (or) No correct answer.

Object should be unreachable to be eligible for GC. JVM will do multiple scans and moving objects from one generation to another generation to determine the eligibility of GC and frees the memory when the objects are not reachable.

jQuery Button.click() event is triggered twice

$("#id").off().on("click", function() {

});

Worked for me.

$("#id").off().on("click", function() {

});

Creating your own header file in C

foo.h

#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_

foo.c

#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}

main.c

#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}

To compile using GCC

gcc -o my_app main.c foo.c

Create JPA EntityManager without persistence.xml configuration file

With plain JPA, assuming that you have a PersistenceProvider implementation (e.g. Hibernate), you can use the PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method to bootstrap an EntityManagerFactory without needing a persistence.xml.

However, it's annoying that you have to implement the PersistenceUnitInfo interface, so you are better off using Spring or Hibernate which both support bootstrapping JPA without a persistence.xml file:

this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
    this.persistenceUnitInfo, 
    getJpaPropertyMap()
);

Where the PersistenceUnitInfo is implemented by the Spring-specific MutablePersistenceUnitInfo class.

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

Firebase Permission Denied

By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.


You can change the rules so that the database is only readable/writeable by authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

See the quickstart for the Firebase Database security rules.

But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.

Allow unauthenticated access to your database

The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.

Sign in the user before accessing the database

For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:

firebase.auth().signInAnonymously().catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

And then attach your listeners when the sign-in is detected

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var userRef = app.dataInfo.child(app.users);
    
    var useridRef = userRef.child(app.userid);
    
    useridRef.set({
      locations: "",
      theme: "",
      colorScheme: "",
      food: ""
    });

  } else {
    // User is signed out.
    // ...
  }
  // ...
});

What is a regex to match ONLY an empty string?

I would use a negative lookahead for any character:

^(?![\s\S])

This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

Check string length in PHP

$message is propably not a string at all, but an array. Use $message[0] to access the first element.

How to add custom html attributes in JSX

I ran into this problem a lot when attempting to use SVG with react.

I ended up using quite a dirty fix, but it's useful to know this option existed. Below I allow the use of the vector-effect attribute on SVG elements.

import SVGDOMPropertyConfig from 'react/lib/SVGDOMPropertyConfig.js';
import DOMProperty from 'react/lib/DOMProperty.js';

SVGDOMPropertyConfig.Properties.vectorEffect = DOMProperty.injection.MUST_USE_ATTRIBUTE;
SVGDOMPropertyConfig.DOMAttributeNames.vectorEffect = 'vector-effect';

As long as this is included/imported before you start using react, it should work.

How to redirect to previous page in Ruby On Rails?

In rails 5, as per the instructions in Rails Guides, you can use:

redirect_back(fallback_location: root_path)

The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.

How do I read configuration settings from Symfony2 config.yml?

While the solution of moving the contact_email to parameters.yml is easy, as proposed in other answers, that can easily clutter your parameters file if you deal with many bundles or if you deal with nested blocks of configuration.

  • First, I'll answer strictly the question.
  • Later, I'll give an approach for getting those configs from services without ever passing via a common space as parameters.

FIRST APPROACH: Separated config block, getting it as a parameter

With an extension (more on extensions here) you can keep this easily "separated" into different blocks in the config.yml and then inject that as a parameter gettable from the controller.

Inside your Extension class inside the DependencyInjection directory write this:

class MyNiceProjectExtension extends Extension
{
    public function load( array $configs, ContainerBuilder $container )
    {
        // The next 2 lines are pretty common to all Extension templates.
        $configuration = new Configuration();
        $processedConfig = $this->processConfiguration( $configuration, $configs );

        // This is the KEY TO YOUR ANSWER
        $container->setParameter( 'my_nice_project.contact_email', $processedConfig[ 'contact_email' ] );

        // Other stuff like loading services.yml
    }

Then in your config.yml, config_dev.yml and so you can set

my_nice_project:
    contact_email: [email protected]

To be able to process that config.yml inside your MyNiceBundleExtension you'll also need a Configuration class in the same namespace:

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root( 'my_nice_project' );

        $rootNode->children()->scalarNode( 'contact_email' )->end();

        return $treeBuilder;
    }
}

Then you can get the config from your controller, as you desired in your original question, but keeping the parameters.yml clean, and setting it in the config.yml in separated sections:

$recipient = $this->container->getParameter( 'my_nice_project.contact_email' );

SECOND APPROACH: Separated config block, injecting the config into a service

For readers looking for something similar but for getting the config from a service, there is even a nicer way that never clutters the "paramaters" common space and does even not need the container to be passed to the service (passing the whole container is practice to avoid).

This trick above still "injects" into the parameters space your config.

Nevertheless, after loading your definition of the service, you could add a method-call like for example setConfig() that injects that block only to the service.

For example, in the Extension class:

class MyNiceProjectExtension extends Extension
{
    public function load( array $configs, ContainerBuilder $container )
    {
        $configuration = new Configuration();
        $processedConfig = $this->processConfiguration( $configuration, $configs );

        // Do not add a paramater now, just continue reading the services.
        $loader = new YamlFileLoader( $container, new FileLocator( __DIR__ . '/../Resources/config' ) );
        $loader->load( 'services.yml' );

        // Once the services definition are read, get your service and add a method call to setConfig()
        $sillyServiceDefintion = $container->getDefinition( 'my.niceproject.sillymanager' );
        $sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'contact_email' ] ) );
    }
}

Then in your services.yml you define your service as usual, without any absolute change:

services:
    my.niceproject.sillymanager:
        class: My\NiceProjectBundle\Model\SillyManager
        arguments: []

And then in your SillyManager class, just add the method:

class SillyManager
{
    private $contact_email;

    public function setConfig( $newConfigContactEmail )
    {
        $this->contact_email = $newConfigContactEmail;
    }
}

Note that this also works for arrays instead of scalar values! Imagine that you configure a rabbit queue and need host, user and password:

my_nice_project:
    amqp:
        host: 192.168.33.55
        user: guest
        password: guest

Of course you need to change your Tree, but then you can do:

$sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'amqp' ] ) );

and then in the service do:

class SillyManager
{
    private $host;
    private $user;
    private $password;

    public function setConfig( $config )
    {
        $this->host = $config[ 'host' ];
        $this->user = $config[ 'user' ];
        $this->password = $config[ 'password' ];
    }
}

Hope this helps!

Get item in the list in Scala?

Please use parenthesis () to access the list elements list_name(index)

Generate random integers between 0 and 9

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.

Can't connect Nexus 4 to adb: unauthorized

Here is my version of the steps:

  1. Make sure adb is running
  2. In device go to Settings -> developer options -> Revoke USB debugging authorities
  3. Disconnect device
  4. In adb shell type > adb kill-server
  5. In adb shell type > adb start-server
  6. Connect device

if adb shell shows empty host name, restart device

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

iPhone Debugging: How to resolve 'failed to get the task for process'?

I just changed my bundleIdentifier name, that seemed to do the trick.

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

How can I catch all the exceptions that will be thrown through reading and writing a file?

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}

Laravel requires the Mcrypt PHP extension

For non MAMP or XAMPP users on OSX (with homebrew installed):

brew install homebrew/php/php56-mcrypt

Cheers!

Validating input using java.util.Scanner

what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input

Scanner s=new Scanner(System.in);

    int a=s.nextInt();
    while(a<0)
    {
    System.out.println("please provide non negative integer input ");
    a=s.nextInt();
    }
    System.out.println("the non negative integer input is "+a);

Here, you need to take the character input first and check whether user gave character or not if not than again take the character input

    char ch = s.findInLine(".").charAt(0);
    while(!Charcter.isLetter(ch))
    {
    System.out.println("please provide a character input ");
    ch=s.findInLine(".").charAt(0);
    }
    System.out.println("the character  input is "+ch);

Python requests library how to pass Authorization header with single token

You can also set headers for the entire session:

TOKEN = 'abcd0123'
HEADERS = {'Authorization': 'token {}'.format(TOKEN)}

with requests.Session() as s:

    s.headers.update(HEADERS)
    resp = s.get('http://example.com/')

Find the division remainder of a number

you can define a function and call it remainder with 2 values like rem(number1,number2) that returns number1%number2 then create a while and set it to true then print out two inputs for your function holding number 1 and 2 then print(rem(number1,number2)

jQuery $(".class").click(); - multiple elements, click event once

Hi sorry for bump this post just face this problem and i would like to show my case.

My code look like this.

<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>

Javascript code

<script>
 var product = {
     //  Define your function
     'add':(product_id)=>{
          //  Do some thing here
     },

     'delete':(product_id)=>{
         //  Do some thig here
     }
 }
</script>

Remove multiple whitespaces

I use this code and pattern:

preg_replace('/\\s+/', ' ',$data)

$data = 'This is   a Text 
   and so on         Text text on multiple lines and with        whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;

You may test this on http://writecodeonline.com/php/

Setting default values to null fields when mapping with Jackson

Only one proposed solution keeps the default-value when some-value:null was set explicitly (POJO readability is lost there and it's clumsy)

Here's how one can keep the default-value and never set it to null

@JsonProperty("some-value")
public String someValue = "default-value";

@JsonSetter("some-value")
public void setSomeValue(String s) {
    if (s != null) { 
        someValue = s; 
    }
}

Let JSON object accept bytes or let urlopen output strings

For anyone else trying to solve this using the requests library:

import json
import requests

r = requests.get('http://localhost/index.json')
r.raise_for_status()
# works for Python2 and Python3
json.loads(r.content.decode('utf-8'))

How to handle ListView click in Android

The two answers before mine are correct - you can use OnItemClickListener.

It's good to note that the difference between OnItemClickListener and OnItemSelectedListener, while sounding subtle, is in fact significant, as item selection and focus are related with the touch mode of your AdapterView.

By default, in touch mode, there is no selection and focus. You can take a look here for further info on the subject.

Swift: Display HTML data in a label or textView

Display images and text paragraphs is not possible in a UITextView or UILabel, to this, you must use a UIWebView.

Just add the item in the storyboard, link to your code, and call it to load the URL.

OBJ-C

NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];

Swift

let url = NSURL (string: "http://www.sourcefreeze.com");
let requestObj = NSURLRequest(URL: url!);
viewWeb.loadRequest(requestObj);

Step by step tutorial. http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

jQuery DataTable overflow and text-wrapping issues

Using the classes "responsive nowrap" on the table element should do the trick.

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to compare DateTime without time via LINQ?

Try this code

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) <= today);

ssh : Permission denied (publickey,gssapi-with-mic)

I had the same issue while using vagrant. So from my Mac I was trying to ssh to a vagrant box (CentOS 7)

Solved it by amending the /etc/ssh/sshd_config PasswordAuthentication yes then re-started the service using sudo systemctl restart sshd

Hope this helps.

How To Get Selected Value From UIPickerView

You have to use the didSelectRow delegate method, because a UIPickerView can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.

Getting the object's property name

Disclaimer I misunderstood the question to be: "Can I know the property name that an object was attached to", but chose to leave the answer since some people may end up here while searching for that.


No, an object could be attached to multiple properties, so it has no way of knowing its name.

var obj = {a:1};
var a = {x: obj, y: obj}

What would obj's name be?

Are you sure you don't just want the property name from the for loop?

for (var propName in obj) {
  console.log("Iterating through prop with name", propName, " its value is ", obj[propName])
}

How do I retrieve my MySQL username and password?

Although a strict, logical, computer science'ish interpretation of the op's question would be to require both "How do I retrieve my MySQL username" and "password" - I thought It might be useful to someone to also address the OR interpretation. In other words ...

1) How do I retrieve my MySQL username?

OR

2) password

This latter condition seems to have been amply addressed already so I won't bother with it. The following is a solution for the case "How do i retreive my MySQL username" alone. HIH.

To find your mysql username run the following commands from the mysql shell ...

SELECT User FROM mysql.user;

it will print a table of all mysql users.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

JupyterLab ToC instructions

There are already many good answers to this question, but they often require tweaks to work properly with notebooks in JupyterLab. I wrote this answer to detail the possible ways of including a ToC in a notebook while working in and exporting from JupyterLab.

As a side panel

The jupyterlab-toc extension adds the ToC as a side panel that can number headings, collapse sections, and be used for navigation (see gif below for a demo). This extension is included by default since JupyterLab 3.0, in older version you can install it with the following command

jupyter labextension install @jupyterlab/toc

enter image description here


In the notebook as a cell

At the time being, this can either be done manually as in Matt Dancho's answer, or automatically via the toc2 jupyter notebook extension in the classic notebook interface.

First, install toc2 as part of the jupyter_contrib_nbextensions bundle:

conda install -c conda-forge jupyter_contrib_nbextensions

Then, launch JupyterLab, go to Help --> Launch Classic Notebook, and open the notebook in which you want to add the ToC. Click the toc2 symbol in the toolbar to bring up the floating ToC window (see the gif below if you can't find it), click the gear icon and check the box for "Add notebook ToC cell". Save the notebook and the ToC cell will be there when you open it in JupyterLab. The inserted cell is a markdown cell with html in it, it will not update automatically.

The default options of the toc2 can be configured in the "Nbextensions" tab in the classic notebook launch page. You can e.g. choose to number headings and to anchor the ToC as a side bar (which I personally think looks cleaner).

enter image description here


In an exported HTML file

nbconvert can be used to export notebooks to HTML following rules of how to format the exported HTML. The toc2 extension mentioned above adds an export format called html_toc, which can be used directly with nbconvert from the command line (after the toc2 extension has been installed):

jupyter nbconvert file.ipynb --to html_toc
# Append `--ExtractOutputPreprocessor.enabled=False`
# to get a single html file instead of a separate directory for images

Remember that shell commands can be added to notebook cells by prefacing them with an exclamation mark !, so you can stick this line in the last cell of the notebook and always have an HTML file with a ToC generated when you hit "Run all cells" (or whatever output you desire from nbconvert). This way, you could use jupyterlab-toc to navigate the notebook while you are working, and still get ToCs in the exported output without having to resort to using the classic notebook interface (for the purists among us).

Note that configuring the default toc2 options as described above, will not change the format of nbconver --to html_toc. You need to open the notebook in the classic notebook interface for the metadata to be written to the .ipynb file (nbconvert reads the metadata when exporting) Alternatively, you can add the metadata manually via the Notebook tools tab of the JupyterLab sidebar, e.g. something like:

    "toc": {
        "number_sections": false,
        "sideBar": true
    }

If you prefer a GUI-driven approach, you should be able to open the classic notebook and click File --> Save as HTML (with ToC) (although note that this menu item was not available for me).


The gifs above are linked from the respective documentation of the extensions.

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

Animated GIF in IE stopping

A very easy way is to use jQuery and SimpleModal plugin. Then when I need to show my "loading" gif on submit, I do:

$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );

How do I check CPU and Memory Usage in Java?

If you are using Tomcat, check out Psi Probe, which lets you monitor internal and external memory consumption as well as a host of other areas.

How to get files in a relative path in C#

To make sure you have the application's path (and not just the current directory), use this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx

Now you have a Process object that represents the process that is running.

Then use Process.MainModule.FileName:

http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx

Finally, use Path.GetDirectoryName to get the folder containing the .exe:

http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx

So this is what you want:

string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);

(Notice that "\Archive\" from your question is now @"\Archive\": you need the @ so that the \ backslashes aren't interpreted as the start of an escape sequence)

Hope that helps!

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

It's better (but wordier) to use:

var element = document.getElementById('something');
if (element != null && element.value == '') {
}

Please note, the first version of my answer was wrong:

var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}

because getElementById() always return an object (null object if not found) and checking for"undefined" would never return a false, as typeof null !== "undefined" is still true.

How to enable cURL in PHP / XAMPP

Since you're using XAMPP, uncomment the line

;extension=php_curl.dll

in xampp\apache\bin\php.ini, and then restart the Apache service.

NB: In newer XAMPP versions, PHP has moved to root xampp folder xampp\php\php.ini.

How to wait for async method to complete?

just put Wait() to wait until task completed

GetInputReportViaInterruptTransfer().Wait();

Python regex findall

Your question is not 100% clear, but I'm assuming you want to find every piece of text inside [P][/P] tags:

>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']

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

This code should do the same as your new routine, working with the correct multi-dimensional array..

 $arr = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => '')
 );

 echo 'Index of "string2" = '. array_search('string2', array_keys($arr));

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

Creating an index on a table variable

It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386

Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.

The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.

To avoid name clashes, something like this usually works:

declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);

This insures the name is always unique even between simultaneous executions of the same procedure.

How do I get the parent directory in Python?

import os

def parent_filedir(n):
    return parent_filedir_iter(n, os.path.dirname(__file__))

def parent_filedir_iter(n, path):
    n = int(n)
    if n <= 1:
        return path
    return parent_filedir_iter(n - 1, os.path.dirname(path))

test_dir = os.path.abspath(parent_filedir(2))

How can I list all tags for a Docker image on a remote registry?

You can achieve by running on terminal this:

curl -L -s 'https://registry.hub.docker.com/v2/repositories/library/mysql/tags/' | jq . | grep name

Also, if you don't have jq you have to install it by

sudo apt-get install jq

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Determine if two rectangles overlap each other?

struct Rect
{
   Rect(int x1, int x2, int y1, int y2)
   : x1(x1), x2(x2), y1(y1), y2(y2)
   {
       assert(x1 < x2);
       assert(y1 < y2);
   }

   int x1, x2, y1, y2;
};

//some area of the r1 overlaps r2
bool overlap(const Rect &r1, const Rect &r2)
{
    return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&
           r1.y1 < r2.y2 && r2.x1 < r1.y2;
}

//either the rectangles overlap or the edges touch
bool touch(const Rect &r1, const Rect &r2)
{
    return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&
           r1.y1 <= r2.y2 && r2.x1 <= r1.y2;
}

Swift Open Link in Safari

UPDATED for Swift 4: (credit to Marco Weber)

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.shared.openURL(requestUrl as URL) 
}

OR go with more of swift style using guard:

guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
    return
}

UIApplication.shared.openURL(requestUrl as URL) 

Swift 3:

You can check NSURL as optional implicitly by:

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.sharedApplication().openURL(requestUrl)
}

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Generating a PDF file from React Components

React-PDF is a great resource for this.

It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward.

To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When clicked, the site renders and downloads the PDF for the user.

Here's their REPL which will familiarize you with the markup and styling required. They have a download link for the PDF too, but they don't show the code for that here.

Comparing arrays in C#

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this question is already been answered but for new comers those two solutions may help:

  1. Make sure your gmail is allowing low secure apps to sign in, you can turn it on here: https://www.google.com/settings/security/lesssecureapps.
  2. Change your password.

How can I tell if a VARCHAR variable contains a substring?

CONTAINS is for a Full Text Indexed field - if not, then use LIKE

How to convert all text to lowercase in Vim

  • Toggle case "HellO" to "hELLo" with g~ then a movement.
  • Uppercase "HellO" to "HELLO" with gU then a movement.
  • Lowercase "HellO" to "hello" with gu then a movement.

For examples and more info please read this: http://vim.wikia.com/wiki/Switching_case_of_characters

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));

Toggle show/hide on click with jQuery

The toggle-event is deprecated in version 1.8, and removed in version 1.9

Try this...

$('#myelement').toggle(
   function () {
      $('#another-element').show("slide", {
          direction: "right"
      }, 1000);
   },
   function () {
      $('#another-element').hide("slide", {
          direction: "right"
      }, 1000);
});

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs

You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.

Live Demo

$( "#myelement" ).click(function() {     
    if($('#another-element:visible').length)
        $('#another-element').hide("slide", { direction: "right" }, 1000);
    else
        $('#another-element').show("slide", { direction: "right" }, 1000);        
});

Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.

Live Demo

$( "#myelement" ).click(function() {     
   $('#another-element').toggle("slide", { direction: "right" }, 1000);
});

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How to open the default webbrowser using java

As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:

Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.

For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.

Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:

This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.

Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk

Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

How to check if a String contains any letter from a to z?

Replace your for loop by this :

errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;

Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import

How to store a list in a column of a database table

Simple answer: If, and only if, you're certain that the list will always be used as a list, then join the list together on your end with a character (such as '\0') that will not be used in the text ever, and store that. Then when you retrieve it, you can split by '\0'. There are of course other ways of going about this stuff, but those are dependent on your specific database vendor.

As an example, you can store JSON in a Postgres database. If your list is text, and you just want the list without further hassle, that's a reasonable compromise.

Others have ventured suggestions of serializing, but I don't really think that serializing is a good idea: Part of the neat thing about databases is that several programs written in different languages can talk to one another. And programs serialized using Java's format would not do all that well if a Lisp program wanted to load it.

If you want a good way to do this sort of thing there are usually array-or-similar types available. Postgres for instance, offers array as a type, and lets you store an array of text, if that's what you want, and there are similar tricks for MySql and MS SQL using JSON, and IBM's DB2 offer an array type as well (in their own helpful documentation). This would not be so common if there wasn't a need for this.

What you do lose by going that road is the notion of the list as a bunch of things in sequence. At least nominally, databases treat fields as single values. But if that's all you want, then you should go for it. It's a value judgement you have to make for yourself.

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

How can I tell gcc not to inline a function?

You want the gcc-specific noinline attribute.

This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm ("");

Use it like this:

void __attribute__ ((noinline)) foo() 
{
  ...
}

All ASP.NET Web API controllers return 404

Similar problem with an embarrassingly simple solution - make sure your API methods are public. Leaving off any method access modifier will return an HTTP 404 too.

Will return 404:

List<CustomerInvitation> GetInvitations(){

Will execute as expected:

public List<CustomerInvitation> GetInvitations(){

Command to change the default home directory of a user

In case other readers look for information on the adduser command.

Edit /etc/adduser.conf

Set DHOME variable

What is a lambda expression in C++11?

One problem it solves: Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member

You can initialize a const member of your class, with a call to a function that sets its value by giving back its output as an output parameter.

git push says "everything up-to-date" even though I have local changes

There is a quick way I found. Go to your .git folder, open the HEAD file and change whatever branch you were on back to master. E.g. ref: refs/heads/master

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

Component is part of the declaration of 2 modules

Some people using Lazy loading are going to stumble across this page.

Here is what I did to fix sharing a directive.

  1. create a new shared module

shared.module.ts

import { NgModule, Directive,OnInit, EventEmitter, Output, OnDestroy, Input,ElementRef,Renderer } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SortDirective } from './sort-directive';

@NgModule({
  imports: [
  ],
  declarations: [
  SortDirective
  ],
  exports: [
    SortDirective
  ]
})

export class SharedModule { }

Then in app.module and your other module(s)

import {SharedModule} from '../directives/shared.module'
...

@NgModule({
   imports: [
       SharedModule
       ....
       ....
 ]
})
export class WhateverModule { }

How to Insert Double or Single Quotes

Assuming your data is in column A, add a formula to column B

="'" & A1 & "'" 

and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.

Difference between onLoad and ng-init in angular

ng-init is a directive that can be placed inside div's, span's, whatever, whereas onload is an attribute specific to the ng-include directive that functions as an ng-init. To see what I mean try something like:

<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>

You'll see that only the second one shows up.

An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

C++ Array Of Pointers

If you don't use the STL, then the code looks a lot bit like C.

#include <cstdlib>
#include <new>

template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
    T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
    if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
       // assign things now that there is no exception
    arr = tmp;
    new( &arr[ n ] ) T( obj ); // placement new
    ++ n;
}

T can be any POD type, including pointers.

Note that arr must be allocated by malloc, not new[].

How to fix: Error device not found with ADB.exe

This worked for me, my AVG anti virus was deleting my adb.exe file. If you have AVG try: 1) opening the program 2) go to options 3) go to the virus vault and click on it 4) find your adb program, click on it, and press RESTORE at the bottom This will move the file back to its original place. However, unless you turn off the AVG it will delete the file again.
After this android studio located the file. Good luck.

What is the simplest and most robust way to get the user's current location on Android?

This is the code that provides user current location

create Maps Activty:

public class Maps extends MapActivity {

    public static final String TAG = "MapActivity";
    private MapView mapView;
    private LocationManager locationManager;
    Geocoder geocoder;
    Location location;
    LocationListener locationListener;
    CountDownTimer locationtimer;
    MapController mapController;
    MapOverlay mapOverlay = new MapOverlay();

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        initComponents();
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        mapView.setTraffic(true);
        mapView.setStreetView(true);
        mapController = mapView.getController();
        mapController.setZoom(16);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager == null) {
            Toast.makeText(Maps.this, "Location Manager Not Available",
                Toast.LENGTH_SHORT).show();
            return;
        }
        location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null)
            location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Toast.makeText(Maps.this, "Location Are" + lat + ":" + lng,
                Toast.LENGTH_SHORT).show();
            GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
            mapController.animateTo(point, new Message());
            mapOverlay.setPointToDraw(point);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
        }
        locationListener = new LocationListener() {

            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

            public void onProviderEnabled(String arg0) {}

            public void onProviderDisabled(String arg0) {}

            public void onLocationChanged(Location l) {
                location = l;
                locationManager.removeUpdates(this);
                if (l.getLatitude() == 0 || l.getLongitude() == 0) {
                } else {
                    double lat = l.getLatitude();
                    double lng = l.getLongitude();
                    Toast.makeText(Maps.this, "Location Are" + lat + ":" + lng,
                        Toast.LENGTH_SHORT).show();
                }
            }
        };
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
        locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
        locationtimer = new CountDownTimer(30000, 5000) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (location != null) locationtimer.cancel();
            }

            @Override
            public void onFinish() {
                if (location == null) {
                }
            }
        };
        locationtimer.start();
    }

    public MapView getMapView() {
        return this.mapView;
    }

    private void initComponents() {
        mapView = (MapView) findViewById(R.id.map_container);
        ImageView ivhome = (ImageView) this.findViewById(R.id.imageView_home);
        ivhome.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Maps.this, GridViewContainer.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    class MapOverlay extends Overlay {

        private GeoPoint pointToDraw;

        public void setPointToDraw(GeoPoint point) {
            pointToDraw = point;
        }

        public GeoPoint getPointToDraw() {
            return pointToDraw;
        }

        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
                long when) {
            super.draw(canvas, mapView, shadow);
            Point screenPts = new Point();
            mapView.getProjection().toPixels(pointToDraw, screenPts);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.select_map);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
            return true;
        }
    }
}

main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:orientation="vertical" >

        <com.google.android.maps.MapView
            android:id="@+id/map_container"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:apiKey="yor api key"
            android:clickable="true"
            android:focusable="true" />

    </LinearLayout>

and define following permission in manifest:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Changing CSS Values with Javascript

Gathering the code in the answers, I wrote this function that seems running well on my FF 25.

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  /* returns the value of the element style of the rule in the stylesheet
  *  If no value is given, reads the value
  *  If value is given, the value is changed and returned
  *  If '' (empty string) is given, erases the value.
  *  The browser will apply the default one
  *
  * string stylesheet: part of the .css name to be recognized, e.g. 'default'
  * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
  * string style: camelCase element style, e.g. 'fontSize'
  * string value optionnal : the new value
  */
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.

Call :

CCSStylesheetRuleStyle('default', "#mydiv", "height");

CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

What is the meaning of "Failed building wheel for X" in pip install?

I got the same message when I tried to install pip install django-imagekit. So I ran pip install wheel (I had python 2.7) and then I reran pip install django-imagekit and it worked. Thanks

change Oracle user account status from EXPIRE(GRACE) to OPEN

In case you know the password of that user, or you would like to guess it, do the following:

  • connect user/password

If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:

  • alter user NAME_OF_THE_USER identified by OLD_PASSWORD;

and this will reset the password to the same password as before and also reset the account_status for that user.

C pass int array pointer as parameter into a function

Using the really excellent example from Greggo, I got this to work as a bubble sort with passing an array as a pointer and doing a simple -1 manipulation.

#include<stdio.h>

void sub_one(int (*arr)[7])
{
     int i; 
     for(i=0;i<7;i++)
    {
        (*arr)[i] -= 1 ; // subtract 1 from each point
        printf("%i\n", (*arr)[i]);

    }

}   

int main()
{
    int a[]= { 180, 185, 190, 175, 200, 180, 181};
    int pos, j, i;
    int n=7;
    int temp;
    for (pos =0; pos < 7; pos ++){
        printf("\nPosition=%i Value=%i", pos, a[pos]);
    }
    for(i=1;i<=n-1;i++){
        temp=a[i];
        j=i-1;
        while((temp<a[j])&&(j>=0)) // while selected # less than a[j] and not j isn't 0
        {
            a[j+1]=a[j];    //moves element forward
            j=j-1;
        }
         a[j+1]=temp;    //insert element in proper place
    }

    printf("\nSorted list is as follows:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\n",a[i]);
    }
    printf("\nmedian = %d\n", a[3]);
    sub_one(&a);

    return 0;
}

I need to read up on how to encapsulate pointers because that threw me off.

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

for the first section, we need to set tableHeaderView like this:

tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.01))

and also for the other sections, we should set heightForFooterInSection like this:

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 0.01
}

How do I find out which process is locking a file using .NET?

It is very complex to invoke Win32 from C#.

You should use the tool Handle.exe.

After that your C# code have to be the following:

string fileName = @"c:\aaa.doc";//Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();           
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

How can I use random numbers in groovy?

Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random

Pass mouse events through absolutely-positioned element

If all you need is mousedown, you may be able to make do with the document.elementFromPoint method, by:

  1. removing the top layer on mousedown,
  2. passing the x and y coordinates from the event to the document.elementFromPoint method to get the element underneath, and then
  3. restoring the top layer.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

Get current value selected in dropdown using jQuery

You can try:

$("._someDropDown").val();

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

How often should you use git-gc?

I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Can I change the scroll speed using css or jQuery?

I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

How to do what head, tail, more, less, sed do in Powershell?

more.exe exists on Windows, ports of less are easily found (and the PowerShell Community Extensions, PSCX, includes one).

PowerShell doesn't really provide any alternative to separate programs for either, but for structured data Out-Grid can be helpful.

Head and Tail can both be emulated with Select-Object using the -First and -Last parameters respectively.

Sed functions are all available but structured rather differently. The filtering options are available in Where-Object (or via Foreach-Object and some state for ranges). Other, transforming, operations can be done with Select-Object and Foreach-Object.

However as PowerShell passes (.NET) objects – with all their typed structure, eg. dates remain DateTime instances – rather than just strings, which each command needs to parse itself, much of sed and other such programs are redundant.

get and set in TypeScript

TS offers getters and setters which allow object properties to have more control of how they are accessed (getter) or updated (setter) outside of the object. Instead of directly accessing or updating the property a proxy function is called.

Example:

class Person {
    constructor(name: string) {
        this._name = name;
    }

    private _name: string;

    get name() {
        return this._name;
    }

    // first checks the length of the name and then updates the name.
    set name(name: string) {
        if (name.length > 10) {
            throw new Error("Name has a max length of 10");
        }

        this._name = name;  
    }

    doStuff () {
        this._name = 'foofooooooofoooo';
    }


}

const person = new Person('Willem');

// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();  

// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';  

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

Changing nav-bar color after scrolling?

Slight variation to the above answers, but with Vanilla JS:

var nav = document.querySelector('nav'); // Identify target

window.addEventListener('scroll', function(event) { // To listen for event
    event.preventDefault();

    if (window.scrollY <= 150) { // Just an example
        nav.style.backgroundColor = '#000'; // or default color
    } else {
        nav.style.backgroundColor = 'transparent';
    }
});

The located assembly's manifest definition does not match the assembly reference

I'll let someone benefit from my shear stupidity. I have some dependencies to a completely separate application (let's call this App1). The dll's from that App1 are pulled into my new application (App2). Any time I do updates in APP1, I have to create new dll's and copy them into App2. Well. . .I got tired of copying and pasting between 2 different App1 versions, so I simply added a 'NEW_' prefix to the dll's.

Well. . . I'm guessing that the build process scans the /bin folder and when it matches something up incorrectly, it barfs with the same error message as noted above. I deleted my "new_" versions and it built just dandy.

how to count length of the JSON array element

I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}

How to support placeholder attribute in IE8 and 9

You can use any one of these polyfills:

These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!

How to check if an array element exists?

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

Get value when selected ng-option changes

as Artyom said you need to use ngChange and pass ngModel object as argument to your ngChange function

Example:

<div ng-app="App" >
  <div ng-controller="ctrl">
    <select ng-model="blisterPackTemplateSelected" ng-change="changedValue(blisterPackTemplateSelected)" 
            data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates">
      <option value="">Select Account</option>
    </select>
    {{itemList}}     
  </div>       
</div>

js:

function ctrl($scope) {
  $scope.itemList = [];
  $scope.blisterPackTemplates = [{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];

  $scope.changedValue = function(item) {
    $scope.itemList.push(item.name);
  }       
}

Live example: http://jsfiddle.net/choroshin/9w5XT/4/

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

as text:

=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $("#type").change(function () {_x000D_
        var val = $(this).val();_x000D_
        if (val == "item1") {_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
        } else if (val == "item2") {_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
        } else if (val == "item3") {_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
        } else if (val == "item0") {_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to avoid warning when introducing NAs by coercion

In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.

as.num = function(x, na.strings = "NA") {
    stopifnot(is.character(x))
    na = x %in% na.strings
    x[na] = 0
    x = as.numeric(x)
    x[na] = NA_real_
    x
}
as.num(c("1", "2", "X"), na.strings="X")
#[1]  1  2 NA

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

how to draw directed graphs using networkx in python?

Instead of regular nx.draw you may want to use:

nx.draw_networkx(G[, pos, arrows, with_labels])

For example:

nx.draw_networkx(G, arrows=True, **options)

You can add options by initialising that ** variable like this:

options = {
    'node_color': 'blue',
    'node_size': 100,
    'width': 3,
    'arrowstyle': '-|>',
    'arrowsize': 12,
}

Also some functions support the directed=True parameter In this case this state is the default one:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

Graph with arrows image

How do you pass view parameters when navigating from an action in JSF2?

Check out these:

You're gonna need something like:

<h:link outcome="success">
  <f:param name="foo" value="bar"/>
</h:link>

...and...

<f:metadata>
  <f:viewParam name="foo" value="#{bean.foo}"/>
</f:metadata>

Judging from this page, something like this might be easier:

 <managed-bean>
   <managed-bean-name>blog</managed-bean-name>
   <managed-bean-class>com.acme.Blog</managed-bean-class>
   <managed-property>
      <property-name>entryId</property-name>
      <value>#{param['id']}</value>
   </managed-property>
 </managed-bean>

How do I join two SQLite tables in my Android application?

"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.

Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.

select P.* 
from product_has_image P
inner join highest_priority_images H 
        on (H.id_product = P.id_product and H.priority = p.priority)

How can I install Python's pip3 on my Mac?

If you're using Python 3, just execute python3 get-pip.py . It is just a simple command.

'' is not recognized as an internal or external command, operable program or batch file

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

how to check for null with a ng-if values in a view with angularjs?

Here is a simple example that I tried to explain.

<div>
    <div *ngIf="product">     <!--If "product" exists-->
      <h2>Product Details</h2><hr>
      <h4>Name: {{ product.name }}</h4>
      <h5>Price: {{ product.price | currency }}</h5>
      <p> Description: {{ product.description }}</p>
    </div>

    <div *ngIf="!product">     <!--If "product" not exists-->
       *Product not found
    </div>
</div>

How can I use Guzzle to send a POST request in JSON?

The simple and basic way (guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

CSS position absolute full width problem

I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.

position: fixed;
left: 0;
right: 0;

using facebook sdk in Android studio

I fixed the

"Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'."

error on the build.gradle file, by adding in gradle.properties the values:

ANDROID_BUILD_TARGET_SDK_VERSION=21<br>
ANDROID_BUILD_MIN_SDK_VERSION=15<br>
ANDROID_BUILD_TOOLS_VERSION=21.1.2<br>
ANDROID_BUILD_SDK_VERSION=21<br>

Source: https://stackoverflow.com/a/21490651/2161698

Bootstrap row class contains margin-left and margin-right which creates problems

I was facing this same issue and initially, I removed the row's right and left -ve margin and it removed the horizontal scroll, but it wasn't good. Then after 45 minutes of inspecting and searching, I found out that I was using container-fluid and was removing the padding and its inner row had left and right negative margins. So I gave container-fluid it's padding back and everything went back to normal.

If you do need to remove container-fluid padding, don't just remove every row's left and right negative margin in your project instead introduce a class and use that on your desired container

Convert pem key to ssh-rsa format

I did with

ssh-keygen -i -f $sshkeysfile >> authorized_keys

Credit goes here

Converting Integer to Long

If the Integer is not null

Integer i;
Long long = Long.valueOf(i);

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

How to use environment variables in docker compose

env SOME_VAR="I am some var" OTHER_VAR="I am other var" docker stack deploy -c docker-compose.yml

Use the version 3.6 :

version: "3.6"
services:
  one:
    image: "nginx:alpine"
    environment:
      foo: "bar"
      SOME_VAR:
      baz: "${OTHER_VAR}"
    labels:
      some-label: "$SOME_VAR"
  two:
    image: "nginx:alpine"
    environment:
      hello: "world"
      world: "${SOME_VAR}"
    labels:
      some-label: "$OTHER_VAR"

I got it form this link https://github.com/docker/cli/issues/939

use jQuery to get values of selected checkboxes

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

Cast Int to enum in Java

If you want to give your integer values, you can use a structure like below

public enum A
{
        B(0),
        C(10),
        None(11);
        int id;
        private A(int i){id = i;}

        public int GetID(){return id;}
        public boolean IsEmpty(){return this.equals(A.None);}
        public boolean Compare(int i){return id == i;}
        public static A GetValue(int _id)
        {
            A[] As = A.values();
            for(int i = 0; i < As.length; i++)
            {
                if(As[i].Compare(_id))
                    return As[i];
            }
            return A.None;
        }
}

How to enable remote access of mysql in centos?

so do the following edit my.cnf:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';

thats it make sure your iptables allow connection from 3306 if not put the following:

iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT

Matplotlib 2 Subplots, 1 Colorbar

As a beginner who stumbled across this thread, I'd like to add a python-for-dummies adaptation of abevieiramota's very neat answer (because I'm at the level that I had to look up 'ravel' to work out what their code was doing):

import numpy as np
import matplotlib.pyplot as plt

fig, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plt.subplots(2,3)

axlist = [ax1,ax2,ax3,ax4,ax5,ax6]

first = ax1.imshow(np.random.random((10,10)), vmin=0, vmax=1)
third = ax3.imshow(np.random.random((12,12)), vmin=0, vmax=1)

fig.colorbar(first, ax=axlist)

plt.show()

Much less pythonic, much easier for noobs like me to see what's actually happening here.

How to implement Rate It feature in Android App

All those libraries are not the solution for the problem in this post. This libraries just open a webpage to the app on google play. Instead this Play core library has more consistent interface.

So I think this is the problem, ProGuard: it obfscates some classes enough https://stackoverflow.com/a/63650212/10117882

Executing Javascript from Python

You can use requests-html which will download and use chromium underneath.

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

script = """
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
"""

val = html.render(script=script, reload=False)
print(val)
# +1 425-984-7450

More on this read here

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Java to Jackson JSON serialization: Money fields

Inspired by Steve, and as the updates for Java 11. Here's how we did the BigDecimal reformatting to avoid scientific notation.

public class PriceSerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        // Using writNumber and removing toString make sure the output is number but not String.
        jgen.writeNumber(value.setScale(2, RoundingMode.HALF_UP));
    }
}

Newline in markdown table?

Use an HTML line break (<br />) to force a line break within a table cell:

|Something|Something else<br />that's rather long|Something else|

How to ignore the first line of data when processing CSV data?

Python 3.X

Handles UTF8 BOM + HEADER

It was quite frustrating that the csv module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file). This works for me using only the csv module:

import csv

def read_csv(self, csv_path, delimiter):
    with open(csv_path, newline='', encoding='utf-8') as f:
        # https://bugs.python.org/issue7185
        # Remove UTF8 BOM.
        txt = f.read()[1:]

    # Remove header line.
    header = txt.splitlines()[:1]
    lines = txt.splitlines()[1:]

    # Convert to list.
    csv_rows = list(csv.reader(lines, delimiter=delimiter))

    for row in csv_rows:
        value = row[INDEX_HERE]

How to increase the max upload file size in ASP.NET?

To increase uploading file's size limit we have two ways

1. IIS6 or lower

By default, in ASP.Net the maximum size of a file to be uploaded to the server is around 4MB. This value can be increased by modifying the maxRequestLength attribute in web.config.

Remember : maxRequestLenght is in KB

Example: if you want to restrict uploads to 15MB, set maxRequestLength to “15360” (15 x 1024).

<system.web>
   <!-- maxRequestLength for asp.net, in KB --> 
   <httpRuntime maxRequestLength="15360" ></httpRuntime> 
</system.web>

2. IIS7 or higher

A slight different way used here to upload files.IIS7 has introduced request filtering module.Which executed before ASP.Net.Means the way pipeline works is that the IIS value(maxAllowedContentLength) checked first then ASP.NET value(maxRequestLength) is checked.The maxAllowedContentLength attribute defaults to 28.61 MB.This value can be increased by modifying both attribute in same web.config.

Remember : maxAllowedContentLength is in bytes

Example : if you want to restrict uploads to 15MB, set maxRequestLength to “15360” and maxAllowedContentLength to "15728640" (15 x 1024 x 1024).

<system.web>
   <!-- maxRequestLength for asp.net, in KB --> 
   <httpRuntime maxRequestLength="15360" ></httpRuntime> 
</system.web>

<system.webServer>              
   <security> 
      <requestFiltering> 
         <!-- maxAllowedContentLength, for IIS, in bytes --> 
         <requestLimits maxAllowedContentLength="15728640" ></requestLimits>
      </requestFiltering> 
   </security>
</system.webServer>

MSDN Reference link : https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx

Python Serial: How to use the read or readline function to read more than 1 character at a time

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n indicating one line.

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

EDIT

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

Google Android USB Driver and ADB

For my Azpen A727, the Windows driver installed correctly, so only step 3 of Mohammad's answer was necessary.

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

Convert month name to month number in SQL Server

You can do it this way, if you have the date (e.g. SubmittedDate)

DATENAME(MONTH,DATEADD(MONTH, MONTH(SubmittedDate) - 1, 0)) AS ColumnDisplayMonth

Or you can do it this way, if you have the month as an int

DATENAME(MONTH,DATEADD(MONTH, @monthInt - 1, 0)) AS ColumnDisplayMonth

How to set timeout on python's socket recv method?

Shout out to: https://boltons.readthedocs.io/en/latest/socketutils.html

It provides a buffered socket, this provides a lot of very useful functionality such as:

.recv_until()    #recv until occurrence of bytes
.recv_closed()   #recv until close
.peek()          #peek at buffer but don't pop values
.settimeout()    #configure timeout (including recv timeout)

Optimistic vs. Pessimistic locking

In addition to what's been said already:

  • It should be said that optimistic locking tends to improve concurrency at the expense of predictability.
  • Pessimistic locking tends to reduce concurrency, but is more predictable. You pay your money, etc ...

How to echo xml file in php

This works:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>

SQL Server : SUM() of multiple rows including where clauses

This will bring back totals per property and type

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
GROUP BY    PropertyID,
            TYPE

This will bring back only active values

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID,
            TYPE

and this will bring back totals for properties

SELECT  PropertyID,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID

......

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

How to get the full path of running process?

You can use pInvoke and a native call such as the following. This doesn't seem to have the 32 / 64 bit limitation (at least in my testing)

Here is the code

using System.Runtime.InteropServices;

    [DllImport("Kernel32.dll")]
    static extern uint QueryFullProcessImageName(IntPtr hProcess, uint flags, StringBuilder text, out uint size);

    //Get the path to a process
    //proc = the process desired
    private string GetPathToApp (Process proc)
    {
        string pathToExe = string.Empty;

        if (null != proc)
        {
            uint nChars = 256;
            StringBuilder Buff = new StringBuilder((int)nChars);

            uint success = QueryFullProcessImageName(proc.Handle, 0, Buff, out nChars);

            if (0 != success)
            {
                pathToExe = Buff.ToString();
            }
            else
            {
                int error = Marshal.GetLastWin32Error();
                pathToExe = ("Error = " + error + " when calling GetProcessImageFileName");
            }
        }

        return pathToExe;
    }

How can I set the color of a selected row in DataGrid

Got it. Add the following within the DataGrid.Resources section:

  <DataGrid.Resources>
     <Style TargetType="{x:Type dg:DataGridCell}">
        <Style.Triggers>
            <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
                <Setter Property="Background" Value="#CCDAFF" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

Google maps API V3 method fitBounds()

 var map = new google.maps.Map(document.getElementById("map"),{
                mapTypeId: google.maps.MapTypeId.ROADMAP

            });
var bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++){
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
bounds.extend(marker.position);
}
map.fitBounds(bounds);

Removing array item by value

function deleteValyeFromArray($array,$value)
{
   foreach($array as $key=>$val)
   {
      if($val == $value)
      {
         unset($array[$key]);
      }
   }
   return $array;
}

How to read one single line of csv data in Python?

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)

How to Troubleshoot Intermittent SQL Timeout Errors

We experienced this with SQL Server 2012 / SP3, when running a query via an SqlCommand object from within a C# application. The Command was a simple invocation of a stored procedure having one table parameter; we were passing a list of about 300 integers. The procedure in turn called three user-defined functions and passed the table as a parameter to each of them. The CommandTimeout was set to 90 seconds.

When running precisely the same stored proc with the same argument from within SQL Server Management Studio, the query ran in 15 seconds. But when running it from our application using the above setup, the SqlCommand timed out. The same SqlCommand (with different but comparable data) had been running successfully for weeks, but now it failed with any table argument containing more than 20 or so integers. We did a trace and discovered that when run from the SqlCommand object, the database spent the entire 90 seconds acquiring locks, and would invoke the procedure only at about the moment of the timeout. We changed the CommandTimeout time, and no matter time what we selected the stored proc would be invoked only at the very end of that period. So we surmise that SQL Server was indefinitely acquiring the same locks over and over, and that only the timeout of the Command object caused SQL Server to stop its infinite loop and begin executing the query, by which time it was too late to succeed. A simulation of this same process on a similar server using similar data exhibited no such problem. Our solution was to reboot the entire database server, after which the problem disappeared.

So it appears that there is some problem in SQL Server wherein some resource gets cumulatively consumed and never released. Eventually when connecting via an SqlConnection and running an SqlCommand involving a table parameter, SQL Server goes into an infinite loop acquiring locks. The loop is terminated by the timeout of the SqlCommand object. The solution is to reboot, apparently restoring (temporary?) sanity to SQL Server.

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

How can I uninstall an application using PowerShell?

To add a little to this post, I needed to be able to remove software from multiple Servers. I used Jeff's answer to lead me to this:

First I got a list of servers, I used an AD query, but you can provide the array of computer names however you want:

$computers = @("computer1", "computer2", "computer3")

Then I looped through them, adding the -computer parameter to the gwmi query:

foreach($server in $computers){
    $app = Get-WmiObject -Class Win32_Product -computer $server | Where-Object {
        $_.IdentifyingNumber -match "5A5F312145AE-0252130-432C34-9D89-1"
    }
    $app.Uninstall()
}

I used the IdentifyingNumber property to match against instead of name, just to be sure I was uninstalling the correct application.

char initial value in Java

Either you initialize the variable to something

char retChar = 'x';

or you leave it automatically initialized, which is

char retChar = '\0';

an ascii 0, the same as

char retChar = (char) 0;

What can one initialize char values to?

Sounds undecided between automatic initialisation, which means, you have no influence, or explicit initialisation. But you cannot change the default.

LINQ order by null column where order is ascending and nulls should be last

my decision:

Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)

Get integer value of the current year in Java

The easiest way is to get the year from Calendar.

// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);