Programs & Examples On #Xmlrpcclient

php string to int

Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)

intval(str_replace(" ", "", $b))

Combining CSS Pseudo-elements, ":after" the ":last-child"

You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.

What is the equivalent of 'describe table' in SQL Server?

In addition to above questions, if we have table in DB like db_name.dbo.table_name, we may use following steps

  1. Connect with DB

    USE db_name;

  2. Use EXEC sp_help and don't forget to put table name as 'dbo.tablename' if you have dbo as schema.

    exec sp_help 'dbo.table_name'

This should work!

Python division

Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.

Try casting one of the operands of "/" to be a float:

float(20-10) / (100-10)

How to provide shadow to Button

If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.


Add shadow-layout to your Gradle file:

dependencies {
    compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}


At the top the xml layout where you have your button, add to the top:

xmlns:app="http://schemas.android.com/apk/res-auto"

it will make available the custom attributes.


Then you put a shadow layout around you Button:

<com.dd.ShadowLayout
        android:layout_marginTop="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:sl_shadowRadius="4dp"
        app:sl_shadowColor="#AA000000"
        app:sl_dx="0dp"
        app:sl_dy="0dp"
        app:sl_cornerRadius="56dp"> 

       <YourButton
          .... />

</com.dd.ShadowLayout>

You can then tweak the app: settings to match your required shadow.

Hope it helps.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Loop through childNodes

Try this [reverse order traversal]:

var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
    console.log('node: ', childs[len]);
} while(len --);

OR [in order traversal]

var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
    console.log('node: ', childs[i]);
} while(++i < len);

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

How to test that no exception is thrown?

The following fails the test for all exceptions, checked or unchecked:

@Test
public void testMyCode() {

    try {
        runMyTestCode();
    } catch (Throwable t) {
        throw new Error("fail!");
    }
}

How can I read a text file in Android?

If you want to read file from sd card. Then following code might be helpful for you.

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }

If you wan to read file from asset folder then

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:

InputStream is = getResources().openRawResource(R.raw.test);     

Good example of reading text file from res/raw folder

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Regex replace (in Python) - a simpler way?

The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:

>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    re.sub("(?<=fo+)bar(?=baz)", "quux", string)
  File "C:\Development\Python25\lib\re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:\Development\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
error: look-behind requires fixed-width pattern

This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:

>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
        return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)

This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.

How to download a folder from github?

You can download a file/folder from github

Simply use: svn export <repo>/trunk/<folder>

Ex: svn export https://github.com/lodash/lodash/trunk/docs

Note: You may first list the contents of the folder in terminal using svn ls <repo>/trunk/folder

(yes, that's svn here. apparently in 2016 you still need svn to simply download some github files)

How to delete duplicate lines in a file without sorting it in Unix?

uniq would be fooled by trailing spaces and tabs. In order to emulate how a human makes comparison, I am trimming all trailing spaces and tabs before comparison.

I think that the $!N; needs curly braces or else it continues, and that is the cause of infinite loop.

I have bash 5.0 and sed 4.7 in Ubuntu 20.10. The second one-liner did not work, at the character set match.

Three variations, first to eliminate adjacent repeat lines, second to eliminate repeat lines wherever they occur, third to eliminate all but the last instance of lines in file.

pastebin

# First line in a set of duplicate lines is kept, rest are deleted.
# Emulate human eyes on trailing spaces and tabs by trimming those.
# Use after norepeat() to dedupe blank lines.

dedupe() {
 sed -E '
  $!{
   N;
   s/[ \t]+$//;
   /^(.*)\n\1$/!P;
   D;
  }
 ';
}

# Delete duplicate, nonconsecutive lines from a file. Ignore blank
# lines. Trailing spaces and tabs are trimmed to humanize comparisons
# squeeze blank lines to one

norepeat() {
 sed -n -E '
  s/[ \t]+$//;
  G;
  /^(\n){2,}/d;
  /^([^\n]+).*\n\1(\n|$)/d;
  h;
  P;
  ';
}

lastrepeat() {
 sed -n -E '
  s/[ \t]+$//;
  /^$/{
   H;
   d;
  };
  G;
  # delete previous repeated line if found
  s/^([^\n]+)(.*)(\n\1(\n.*|$))/\1\2\4/;
  # after searching for previous repeat, move tested last line to end
  s/^([^\n]+)(\n)(.*)/\3\2\1/;
  $!{
   h;
   d;
  };
  # squeeze blank lines to one
  s/(\n){3,}/\n\n/g;
  s/^\n//;
  p;
 ';
}

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

How to debug Ruby scripts

There is many debuggers with different features, based on which you make choice. My priorities was satisfied with pry-moves which was:

  • quickly comprehensible info on how to use
  • intuitive steps (like easy stepping into blocks)
  • "stepping back" (pry-moves partially satisfies the need)

Android overlay a view ontop of everything?

I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-

AppWaterMarkBuilder.doConfigure()
                .setAppCompatActivity(MainActivity.this)
                .setWatermarkProperty(R.layout.layout_water_mark)
                .showWatermarkAfterConfig();

Then you can hide and show it from anywhere in your app -

  /* For hiding the watermark*/
  AppWaterMarkBuilder.hideWatermark() 

  /* For showing the watermark*/
  AppWaterMarkBuilder.showWatermark() 

Gif preview -

preview

How can I inject a property value into a Spring Bean which was configured using annotations?

There is a new annotation @Value in Spring 3.0.0M3. @Value support not only #{...} expressions but ${...} placeholders as well

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

What are the correct version numbers for C#?

C# 8.0 is the latest version of c#.it is supported only on .NET Core 3.x and newer versions. Many of the newest features require library and runtime features introduced in .NET Core 3.x

The following table lists the target framework with version and their default C# version.

C# language version with Target framework

Source - C# language versioning

Best way to test for a variable's existence in PHP; isset() is clearly broken

I don't agree with your reasoning about NULL, and saying that you need to change your mindset about NULL is just weird.

I think isset() was not designed correctly, isset() should tell you if the variable has been set and it should not be concerned with the actual value of the variable.

What if you are checking values returned from a database and one of the columns have a NULL value, you still want to know if it exists even if the value is NULL...nope dont trust isset() here.

likewise

$a = array ('test' => 1, 'hello' => NULL);

var_dump(isset($a['test']));   // TRUE
var_dump(isset($a['foo']));    // FALSE
var_dump(isset($a['hello']));  // FALSE

isset() should have been designed to work like this:

if(isset($var) && $var===NULL){....

this way we leave it up to the programmer to check types and not leave it up to isset() to assume its not there because the value is NULL - its just stupid design

Mongoose: Get full list of users

If you'd like to send the data to a view pass the following in.

    server.get('/usersList', function(req, res) {
        User.find({}, function(err, users) {
           res.render('/usersList', {users: users});
        });
    });

Inside your view you can loop through the data using the variable users

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

//This is to convert a letter from upper case to lower case
import java.util.Scanner;
    public class ChangeCase {
        public static void main(String[]args) {

            String input;
            Scanner sc= new Scanner(System.in);
                System.out.println("Enter Letter from upper case");
                input=sc.next();

            String result;
            result= input.toLowerCase();
            System.out.println(result);
        }
    }

Is there a way that I can check if a data attribute exists?

var data = $("#dataTable").data('timer');
var diffs = [];

if( data.length > 0 ) {
for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));
}

Make the current Git branch a master branch

One can also checkout all files from the other branch into master:

git checkout master
git checkout better_branch -- .

and then commit all changes.

Using current time in UTC as default value in PostgreSQL

These are 2 equivalent solutions:

(in the following code, you should substitute 'UTC' for zone and now() for timestamp)

  1. timestamp AT TIME ZONE zone - SQL-standard-conforming
  2. timezone(zone, timestamp) - arguably more readable

The function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.


Explanation:

  • zone can be specified either as a text string (e.g., 'UTC') or as an interval (e.g., INTERVAL '-08:00') - here is a list of all available time zones
  • timestamp can be any value of type timestamp
  • now() returns a value of type timestamp (just what we need) with your database's default time zone attached (e.g. 2018-11-11T12:07:22.3+05:00).
  • timezone('UTC', now()) turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC.
    E.g., SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC' will return 2020-03-16T20:00:00Z.

Docs: timezone()

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

SOLVED
Search "Windows Feature" on start ->
Click "turn features on and off" ->
Expand "Internet Information Services" and
Check every progrm in every subfolder and
Click "OK"
This will fix all your problems. enter image description here

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

in my case i was working on a branch off master. so i checked out master branch, ran a build and then checked out my branch. It fixed the issue. If you already are on master, i suggest you check out previous commit and then build it.

Converting integer to string in Python

>>> str(10)
'10'
>>> int('10')
10

Links to the documentation:

Conversion to a string is done with the builtin str() function, which basically calls the __str__() method of its parameter.

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Storing money in a decimal column - what precision and scale?

We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way.

NEVER USE FLOATING POINT NUMBERS FOR MONEY

Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All values should be stored as either integers or fixed-decimal types, and if you choose to use a fixed-decimal type then make sure you understand exactly what that type does under the hood (ie, does it internally use an integer or floating point type).

When you do need to do calculations or conversions:

  1. Convert values to floating point
  2. Calculate new value
  3. Round the number and convert it back to an integer

When converting a floating point number back to an integer in step 3, don't just cast it - use a math function to round it first. This will usually be round, though in special cases it could be floor or ceil. Know the difference and choose carefully.

Store the type of a number alongside the value

This may not be as important for you if you're only handling one currency, but it was important for us in handling multiple currencies. We used the 3-character code for a currency, such as USD, GBP, JPY, EUR, etc.

Depending on the situation, it may also be helpful to store:

  • Whether the number is before or after tax (and what the tax rate was)
  • Whether the number is the result of a conversion (and what it was converted from)

Know the accuracy bounds of the numbers you're dealing with

For real values, you want to be as precise as the smallest unit of the currency. This means you have no values smaller than a cent, a penny, a yen, a fen, etc. Don't store values with higher accuracy than that for no reason.

Internally, you may choose to deal with smaller values, in which case that's a different type of currency value. Make sure your code knows which is which and doesn't get them mixed up. Avoid using floating point values even here.


Adding all those rules together, we decided on the following rules. In running code, currencies are stored using an integer for the smallest unit.

class Currency {
   String code;       //  eg "USD"
   int value;         //  eg 2500
   boolean converted;
}

class Price {
   Currency grossValue;
   Currency netValue;
   Tax taxRate;
}

In the database, the values are stored as a string in the following format:

USD:2500

That stores the value of $25.00. We were able to do that only because the code that deals with currencies doesn't need to be within the database layer itself, so all values can be converted into memory first. Other situations will no doubt lend themselves to other solutions.


And in case I didn't make it clear earlier, don't use float!

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

Using inline styling use <a href="your link here" style="cursor:default">your content here</a>. See this example

Alternatively use css. See this example.

This solution is cross-browser compatible.

How do I revert to a previous package in Anaconda?

For the case that you wish to revert a recently installed package that made several changes to dependencies (such as tensorflow), you can "roll back" to an earlier installation state via the following method:

conda list --revisions
conda install --revision [revision number]

The first command shows previous installation revisions (with dependencies) and the second reverts to whichever revision number you specify.

Note that if you wish to (re)install a later revision, you may have to sequentially reinstall all intermediate versions. If you had been at revision 23, reinstalled revision 20 and wish to return, you may have to run each:

conda install --revision 21
conda install --revision 22
conda install --revision 23

Android Studio gradle takes too long to build

I had the same issue in kotlin. Updating the outdated kotlin runtime solved it for me

Running PHP script from the command line

On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Android layout replacing a view with another view on run time

And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.

Call an activity method from a fragment

For accessing a function declared in your Activity via your fragment please use an interface, as shown in the answer by marco.

For accessing a function declared in your Fragment via your activity you can use this if you don't have a tag or an id

private void setupViewPager(ViewPager viewPager) {
    //fragmentOne,fragmentTwo and fragmentThree are all global variables
    fragmentOne= new FragmentOne();
    fragmentTwo= new FragmentTwo();
    fragmentThree = new FragmentThree();

    viewPagerAdapteradapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapteradapter.addFragment(fragmentOne, "Frag1");
    viewPagerAdapteradapter.addFragment(fragmentTwo, "Frag2");
    viewPagerAdapteradapter.addFragment(fragmentThree, "Frag3");

    //viewPager has to be instantiated when you create the activity:
    //ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
    //setupViewPager(viewPager);
    //Where R.id.pager is the id of the viewPager defined in your activity's xml page.

    viewPager.setAdapter(viewPagerAdapteradapter);


    //frag1 and frag2 are also global variables
    frag1 = (FragmentOne)viewPagerAdapteradapter.mFragmentList.get(0);
    frag2 = (FragmentTwo)viewPagerAdapteradapter.mFragmentList.get(1);;


    //You can use the variable fragmentOne or frag1 to access functions declared in FragmentOne


}

This is the ViewpagerAdapterClass

    class ViewPagerAdapter extends FragmentPagerAdapter {
    public final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

This answer is for noobs like me. Have a good day.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

How can I configure Logback to log different levels for a logger to different destinations?

Update: For an all configuration based approach using Groovy see Dean Hiller's answer.

--

You can do some interesting things with Logback filters. The below configuration will only print warn and error messages to stderr, and everything else to stdout.

logback.xml

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
  <target>System.out</target>
  <filter class="com.foo.StdOutFilter" />
   ...
</appender>

<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
  <target>System.err</target>
  <filter class="com.foo.ErrOutFilter" />
   ...
</appender>

<logger name="mylogger" level="debug">
    <appender-ref ref="stdout" />
    <appender-ref ref="stderr" />
</logger>

com.foo.StdOutFilter

public class StdOutFilter extends ch.qos.logback.core.filter.AbstractMatcherFilter
{

    @Override
    public FilterReply decide(Object event)
    {
        if (!isStarted())
        {
            return FilterReply.NEUTRAL;
        }

        LoggingEvent loggingEvent = (LoggingEvent) event;

        List<Level> eventsToKeep = Arrays.asList(Level.TRACE, Level.DEBUG, Level.INFO);
        if (eventsToKeep.contains(loggingEvent.getLevel()))
        {
            return FilterReply.NEUTRAL;
        }
        else
        {
            return FilterReply.DENY;
        }
    }

}

com.foo.ErrOutFilter

public class ErrOutFilter extends ch.qos.logback.core.filter.AbstractMatcherFilter
{

    @Override
    public FilterReply decide(Object event)
    {
        if (!isStarted())
        {
            return FilterReply.NEUTRAL;
        }

        LoggingEvent loggingEvent = (LoggingEvent) event;

        List<Level> eventsToKeep = Arrays.asList(Level.WARN, Level.ERROR);
        if (eventsToKeep.contains(loggingEvent.getLevel()))
        {
            return FilterReply.NEUTRAL;
        }
        else
        {
            return FilterReply.DENY;
        }
    }

}

Rename a file using Java

For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.

Example:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.

EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

in SQL 2017 You can do it more easily in the toolbar to the right just hit
enter image description here

the SQL button then its gonna apear the query with the top 200 you edit until the quantity that You want and Execute the query and Done! just Edit

Insert json file into mongodb

This worked for me - ( from mongo shell )

var file = cat('./new.json');     # file name
use testdb                        # db name
var o = JSON.parse(file);         # convert string to JSON
db.forms.insert(o)                # collection name

How do I select a sibling element using jQuery?

you can select a sibling element using jQuery

 <script type="text/javascript">
    $(document).ready(function(){
        $("selector").siblings().addClass("classname");
    });
 </script>

Demo here

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

The website was running fine then suddenly it started to display this same error 404 message (The origin server did not find a current representation for the target resource or is not willing to disclose that one exists), Perhaps because of switching servers back and forward from Tomcat 9 to 8 and 7

In my case, i only had to update the project which was causing this error then restart the specific tomcat version. You may also need to Maven Clean and Maven Install after the "Maven Update Project"

Select Maven Update ProjectUpdate and Refresh Workspace

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

How to get Spinner selected item value to string?

In addition to the suggested,

String Text = mySpinner.getSelectedItem().toString();

You can do,

String Text = String.valueOf(mySpinner.getSelectedItem());

How do I position an image at the bottom of div?

Using flexbox:

HTML:

<div class="wrapper">
    <img src="pikachu.gif"/>
</div>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    display: flex;
    align-items: flex-end;
}

As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;

Writing a Python list of lists to a csv file

Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

The good part you can change somethings to make a better csv file:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^[0-9][0-9]?[^A-Za-z0-9]?po$

You can test it here: http://www.regextester.com/

To use this in C#,

Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
   //Do Something
}

Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)

Magento How to debug blank white screen

I too had the same problem, but solved after disabling the compiler and again reinstalling the extension. Disable of the compiler can be done by system-> configration-> tools-> compilation.. Here Disable the process... Good Luck

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

In my case, there was no process to kill.

Updating docker fixed the problem.

Get the current year in JavaScript

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

How to remove line breaks from a file in Java?

FYI if you can want to replace simultaneous muti-linebreaks with single line break then you can use

myString.trim().replaceAll("[\n]{2,}", "\n")

Or replace with a single space

myString.trim().replaceAll("[\n]{2,}", " ")

Using Exit button to close a winform program

We can close every window using Application.Exit(); Using this method we can close hidden windows also.

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

2.name can no longer contain capital letters

don't use capital letters for your package:

npm install --save uex

use this:

npm install --save vuex

Custom sort function in ng-repeat

The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.

e.g. Given the following assignment:

$scope.cards = {
  "card2": {
    values: {
      opt1: 9,
      opt2: 12
    }
  },
  "card1": {
    values: {
      opt1: 9,
      opt2: 11
    }
  }
};

and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.

To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.

myApp.filter('orderByValue', function () {
  // custom value function for sorting
  function myValueFunction(card) {
    return card.values.opt1 + card.values.opt2;
  }

  return function (obj) {
    var array = [];
    Object.keys(obj).forEach(function (key) {
      // inject key into each object so we can refer to it from the template
      obj[key].name = key;
      array.push(obj[key]);
    });
    // apply a custom sorting function
    array.sort(function (a, b) {
      return myValueFunction(b) - myValueFunction(a);
    });
    return array;
  };
});

We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.

<ul ng-repeat="card in cards | orderByValue">
    <li>{{card.name}} {{value(card)}}</li>
</ul>

Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/

Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332

how to check if object already exists in a list

Simple but it works

MyList.Remove(nextObject)
MyList.Add(nextObject)

or

 if (!MyList.Contains(nextObject))
    MyList.Add(nextObject);

get string from right hand side

SELECT SUBSTR('299123456789',DECODE(least(LENGTH('299123456789'),9),9,-9,LENGTH('299123456789')*-1)) value from dual  

Gives 123456789

The same statement works even when the number is less than 9 digits:

SELECT SUBSTR('6789',DECODE(least(LENGTH('6789'),9),9,-9,LENGTH('6789')*-1)) value from dual  

Gives 6789

Optimal way to DELETE specified rows from Oracle

I have tried this code and It's working fine in my case.

DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
  (
      SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
      FROM NG_USR_0_CLIENT_GRID_NEW
      WHERE wi_name = 'NB-0000001385-Process'
  )
  WHERE RN=2
);

how to get domain name from URL

import urlparse

GENERIC_TLDS = [
    'aero', 'asia', 'biz', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'jobs', 
    'mil', 'mobi', 'museum', 'name', 'net', 'org', 'pro', 'tel', 'travel', 'cat'
    ]

def get_domain(url):
    hostname = urlparse.urlparse(url.lower()).netloc
    if hostname == '':
        # Force the recognition as a full URL
        hostname = urlparse.urlparse('http://' + uri).netloc

    # Remove the 'user:passw', 'www.' and ':port' parts
    hostname = hostname.split('@')[-1].split(':')[0].lstrip('www.').split('.')

    num_parts = len(hostname)
    if (num_parts < 3) or (len(hostname[-1]) > 2):
        return '.'.join(hostname[:-1])
    if len(hostname[-2]) > 2 and hostname[-2] not in GENERIC_TLDS:
        return '.'.join(hostname[:-1])
    if num_parts >= 3:
        return '.'.join(hostname[:-2])

This code isn't guaranteed to work with all URLs and doesn't filter those that are grammatically correct but invalid like 'example.uk'.

However it'll do the job in most cases.

Rebuild all indexes in a Database

Replace the "YOUR DATABASE NAME" in the query below.

    DECLARE @Database NVARCHAR(255)   
    DECLARE @Table NVARCHAR(255)  
    DECLARE @cmd NVARCHAR(1000)  

    DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
    SELECT name FROM master.sys.databases   
    WHERE name IN ('YOUR DATABASE NAME')  -- databases
    AND state = 0 -- database is online
    AND is_in_standby = 0 -- database is not read only for log shipping
    ORDER BY 1  

    OPEN DatabaseCursor  

    FETCH NEXT FROM DatabaseCursor INTO @Database  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  

       SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
       table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

       -- create table cursor  
       EXEC (@cmd)  
       OPEN TableCursor   

       FETCH NEXT FROM TableCursor INTO @Table   
       WHILE @@FETCH_STATUS = 0   
       BEGIN
          BEGIN TRY   
             SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
             PRINT @cmd -- uncomment if you want to see commands
             EXEC (@cmd) 
          END TRY
          BEGIN CATCH
             PRINT '---'
             PRINT @cmd
             PRINT ERROR_MESSAGE() 
             PRINT '---'
          END CATCH

          FETCH NEXT FROM TableCursor INTO @Table   
       END   

       CLOSE TableCursor   
       DEALLOCATE TableCursor  

       FETCH NEXT FROM DatabaseCursor INTO @Database  
    END  
    CLOSE DatabaseCursor   
    DEALLOCATE DatabaseCursor

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How to get unique values in an array

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

_x000D_
_x000D_
Array.prototype.contains = function(v) {_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (this[i] === v) return true;_x000D_
  }_x000D_
  return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (!arr.contains(this[i])) {_x000D_
      arr.push(this[i]);_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
_x000D_
_x000D_

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation

How to sort an ArrayList?

For example I have a class Person: String name, int age ==>Constructor new Person(name,age)

import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;


public void main(String[] args){
    Person ibrahima=new Person("Timera",40);
    Person toto=new Person("Toto",35);
    Person alex=new Person("Alex",50);
    ArrayList<Person> myList=new ArrayList<Person>
    Collections.sort(myList, new Comparator<Person>() {
        @Override
        public int compare(Person p1, Person p2) {
            // return p1.age+"".compareTo(p2.age+""); //sort by age
            return p1.name.compareTo(p2.name); // if you want to short by name
        }
    });
    System.out.println(myList.toString());
    //[Person [name=Alex, age=50], Person [name=Timera, age=40], Person [name=Toto, age=35]]
    Collections.reverse(myList);
    System.out.println(myList.toString());
    //[Person [name=Toto, age=35], Person [name=Timera, age=40], Person [name=Alex, age=50]]

}

Set cursor position on contentEditable <div>

Update

I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.

Previous answer

You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.

I might put something together to do this, will post back here if and when I do.

EDIT:

I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.

http://www.timdown.co.uk/code/selections/

Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.

I will write this up fully at some point soon.

"The page you are requesting cannot be served because of the extension configuration." error message

Verify that the application pool in IIS (in the case of IIS7 or above) is selected as integrated. In this case, probably change to Classic can solve this problem.

How to append something to an array?

if you want to combine 2 arrays without the duplicate you may try the code below

array_merge = function (arr1, arr2) {
  return arr1.concat(arr2.filter(function(item){
    return arr1.indexOf(item) < 0;
  }))
}

usage:

array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)

Output: [1,2,3,4,5]

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

How to set NODE_ENV to production/development in OS X

In order to have multiple environments you need all of the answers before (NODE_ENV parameter and export it), but I use a very simple approach without the need of installing anything. In your package.json just put a script for each env you need, like this:

...
"scripts": {
    "start-dev": "export NODE_ENV=dev && ts-node-dev --respawn --transpileOnly ./src/app.ts",
    "start-prod": "export NODE_ENV=prod && ts-node-dev --respawn --transpileOnly ./src/app.ts"
  }
 ...

Then, to start the app instead of using npm start use npm run script-prod.

In the code you can access the current environment with process.env.NODE_ENV.

Voila.

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

What's the difference between "Layers" and "Tiers"?

Why always trying to use complex words?

A layer = a part of your code, if your application is a cake, this is a slice.

A tier = a physical machine, a server.

A tier hosts one or more layers.


Example of layers:

  • Presentation layer = usually all the code related to the User Interface
  • Data Access layer = all the code related to your database access

Tier:

Your code is hosted on a server = Your code is hosted on a tier.

Your code is hosted on 2 servers = Your code is hosted on 2 tiers.

For example, one machine hosting the Web Site itself (the Presentation layer), another machine more secured hosting all the more security sensitive code (real business code - business layer, database access layer, etc.).


There are so many benefits to implement a layered architecture. This is tricky and properly implementing a layered application takes time. If you have some, have a look at this post from Microsoft: http://msdn.microsoft.com/en-gb/library/ee658109.aspx

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

Lining up labels with radio buttons in bootstrap

Best is to just Apply margin-top: 2px on the input element.

Bootstrap adds a margin-top: 4px to input element causing radio button to move down than the content.

OpenCV !_src.empty() in function 'cvtColor' error

I've been in same situation as well, and My case was because of the Korean letter in the path...

After I remove Korean letters from the folder name, it works.

OR put

[#-*- coding:utf-8 -*-]

(except [ ] at the edge)

or something like that in the first line to make python understand Korean or your language or etc. then it will work even if there is some Koreans in the path in my case.

So the things is, it seems like there is something about path or the letter. People who answered are saying similar things. Hope you guys solve it!

How to import multiple csv files in a single load?

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\*.csv)

will consider files tmp, tmp1, tmp2, ....

Setting the Vim background colors

supplement of windows

gvim version: 8.2

location of .gvimrc: %userprofile%/.gvimrc

" .gvimrc
colorscheme darkblue

Which color is allows me to choose?

Find your install directory and go to the directory of colors. in my case is: %PROGRAMFILES(X86)%\Vim\vim82\colors

blue.vim
darkblue.vim
slate.vim
...
README.txt

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

Use latest version of Internet Explorer in the webbrowser control

Here the method that I usually use and works for me (both for 32 bit and 64 bit applications; ie_emulation can be anyone documented here: Internet Feature Controls (B..C), Browser Emulation):

    [STAThread]
    static void Main()
    {
        if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
        {
            // Another application instance is running
            return;
        }
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var targetApplication = Process.GetCurrentProcess().ProcessName  + ".exe";
            int ie_emulation = 10000;
            try
            {
                string tmp = Properties.Settings.Default.ie_emulation;
                ie_emulation = int.Parse(tmp);
            }
            catch { }
            SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);

            m_webLoader = new FormMain();

            Application.Run(m_webLoader);
        }
        finally
        {
            mutex.ReleaseMutex();
        }
    }

    private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
    {
        RegistryKey Regkey = null;
        try
        {
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);

            // If the path is not correct or
            // if user haven't privileges to access the registry
            if (Regkey == null)
            {
                YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
                return;
            }

            string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

            // Check if key is already present
            if (FindAppkey == "" + ieval)
            {
                YukLoggerObj.logInfoMsg("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
                Regkey.Close();
                return;
            }

            // If a key is not present or different from desired, add/modify the key, key value
            Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);

            // Check for the key after adding
            FindAppkey = Convert.ToString(Regkey.GetValue(appName));

            if (FindAppkey == "" + ieval)
                YukLoggerObj.logInfoMsg("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
            else
                YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION setting failed; current value is  " + ieval);
        }
        catch (Exception ex)
        {
            YukLoggerObj.logWarnMsg("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);

        }
        finally
        {
            // Close the Registry
            if (Regkey != null)
                Regkey.Close();
        }
    }

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

Search for exact match of string in excel row using VBA Macro

Try this:

Sub GetColumns()

Dim lnRow As Long, lnCol As Long

lnRow = 3 'For testing

lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

End Sub

Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.

Turn off textarea resizing

Just one extra option, if you want to revert the default behaviour for all textareas in the application, you could add the following to your CSS:

textarea:not([resize="true"]) {
  resize: none !important;
}

And do the following to enable where you want resizing:

<textarea resize="true"></textarea>

Have in mind this solution might not work in all browsers you may want to support. You can check the list of support for resize here: http://caniuse.com/#feat=css-resize

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

Capturing mobile phone traffic on Wireshark

I had a similar problem that inspired me to develop an app that could help to capture traffic from an Android device. The app features SSH server that allows you to have traffic in Wireshark on the fly (sshdump wireshark component). As the app uses an OS feature called VPNService to capture traffic, it does not require the root access.

The app is in early Beta. If you have any issues/suggestions, do not hesitate to let me know.

Download From Play

Tutorial in which you could read additional details

Removing an item from a select box

Adding/Removing value dynamically without hard-code:

// remove value from select dynamically

$("#id-select option[value='" + dynamicVal + "']").remove();

// Add dynamic value to select

$("#id-select").append('<option value="' + dynamicVal + '">' + dynamicVal + '</option>');

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).

On Debian, change /etc/php5/conf.d/suhosin.ini

;suhosin.memory_limit = 0

to

suhosin.memory_limit = 2G

Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:

Changed the way the memory_limit protection is implemented

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

How can I save a base64-encoded image to disk?

Easy way to convert base64 image into file and save as some random id or name.

// to create some random id or name for your image name
const imgname = new Date().getTime().toString();

// to declare some path to store your converted image
const path = yourpath.png    

// image takes from body which you uploaded
const imgdata = req.body.image;    

// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
    console.log(err);
});

// assigning converted image into your database
req.body.coverImage = imgname

How to add SHA-1 to android application

If you are using Google Play App Signing you need to use the SHA1 from google play since Google will replace your release signing key with the one on googles server

enter image description here

Checking whether a string starts with XXXX

aString = "hello world"
aString.startswith("hello")

More info about startswith.

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

command/usr/bin/codesign failed with exit code 1- code sign error

I was having the issue after select the deny when it asks for permission

After some search I got it fixed by restarting the system.

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

Creating java date object from year,month,day

Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use

c.set(year, month - 1, day, 0, 0);  

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

How do I install a pip package globally instead of locally?

Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

Check to see if cURL is installed locally?

To extend the answer above and if the case is you are using XAMPP. In the current version of the xampp you cannot locate the curl_exec in the php.ini, just try using

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

and save to your htdocs. Next go to your browser and paste

http://localhost/[your_filename].php

if the result looks like this

array(9) {
  ["version_number"]=>
  int(469760)
  ["age"]=>
  int(3)
  ["features"]=>
  int(266141)
  ["ssl_version_number"]=>
  int(0)
  ["version"]=>
  string(6) "7.43.0"
  ["host"]=>
  string(13) "i386-pc-win32"
  ["ssl_version"]=>
  string(14) "OpenSSL/1.0.2e"
  ["libz_version"]=>
  string(5) "1.2.8"
  ["protocols"]=>
  array(19) {
    [0]=>
    string(4) "dict"
    [1]=>
    string(4) "file"
    [2]=>
    string(3) "ftp"
    [3]=>
    string(4) "ftps"
    [4]=>
    string(6) "gopher"
    [5]=>
    string(4) "http"
    [6]=>
    string(5) "https"
    [7]=>
    string(4) "imap"
    [8]=>
    string(5) "imaps"
    [9]=>
    string(4) "ldap"
    [10]=>
    string(4) "pop3"
    [11]=>
    string(5) "pop3s"
    [12]=>
    string(4) "rtsp"
    [13]=>
    string(3) "scp"
    [14]=>
    string(4) "sftp"
    [15]=>
    string(4) "smtp"
    [16]=>
    string(5) "smtps"
    [17]=>
    string(6) "telnet"
    [18]=>
    string(4) "tftp"
  }
}

curl is enable

React: why child component doesn't update when prop changes

In my case I was updating a loading state that was passed down to a component. Within the Button the props.loading was coming through as expected (switching from false to true) but the ternary that showed a spinner wasn't updating.

I tried adding a key, adding a state that updated with useEffect() etc but none of the other answers worked.

What worked for me was changing this:

setLoading(true);
handleOtherCPUHeavyCode();

To this:

setLoading(true);
setTimeout(() => { handleOtherCPUHeavyCode() }, 1)

I assume it's because the process in handleOtherCPUHeavyCode is pretty heavy and intensive so the app freezes for a second or so. Adding the 1ms timeout allows the loading boolean to update and then the heavy code function can do it's work.

List Directories and get the name of the Directory

You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

Inline functions in C#?

Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining value. It is also available in the Mono's trunk (committed today).

// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices; 

...

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)

1. Previously "force" was used here. Since there were a few downvotes, I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible. Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.

How to filter by string in JSONPath?

I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.

Here's the syntax and an abbreviated sample twitter document below.

This site was useful for testing:

The jsonpath filter expression:

.events[0].attributes[?(@.name=='screen_name')].value

Test document:

{
  "title" : "test twitter",
  "priority" : 5,
  "events" : [ {
    "eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
    "eventDate" : "2015-03-27T09:07:48-0500",
    "publisher" : "twitter",
    "type" : "tweet",
    "attributes" : [ {
      "name" : "filter_level",
      "value" : "low"
    }, {
      "name" : "screen_name",
      "value" : "_ziadin"
    }, {
      "name" : "followers_count",
      "value" : "406"
    } ]
  } ]
}

How to print out the method name and line number and conditionally disable NSLog?

Here are some useful macros around NSLog I use a lot:

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#   define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

The DLog macro is used to only output when the DEBUG variable is set (-DDEBUG in the projects's C flags for the debug confirguration).

ALog will always output text (like the regular NSLog).

The output (e.g. ALog(@"Hello world") ) will look like this:

-[LibraryController awakeFromNib] [Line 364] Hello world

Selenium Webdriver submit() vs click()

I was a great fan of submit() but not anymore.

In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit(), password textbox is cleared (becomes empty) and login keeps failing.

After breaking my head for sometime, when I replaced usernametextbox.submit() with loginbutton.click(), it worked like a magic.

how to implement Pagination in reactJs

I have implemented pagination + search in ReactJs, see the output: Pagination in React

View complete code on GitHub: https://github.com/navanathjadhav/generic-pagination

Also visit this article for step by step implementation of pagination: https://everblogs.com/react/3-simple-steps-to-add-pagination-in-react/

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

How to generate random number in Bash?

I wrote several articles on this.

$ RANDOM=$(date +%s%N | cut -b10-19)
$ echo $(( $RANDOM % 113 + 13 ))

The above will give a number between 13 and 113, with reasonable random entropy.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Yup, As @luizfelippe mentioned Session class has been removed since SDK 4.0. We need to use LoginManager.

I just looked into LoginButton class for logout. They are making this kind of check. They logs out only if accessToken is not null. So, I think its better to have this in our code too..

AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
    LoginManager.getInstance().logOut();
}

Asynchronous method call in Python?

The native Python way for asynchronous calls in 2021 with Python 3.9 suitable also for Jupyter / Ipython Kernel

Camabeh's answer is the way to go since Python 3.3.

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)


loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

This will work in Jupyter Notebook / Jupyter Lab but throw an error:

RuntimeError: This event loop is already running

Due to Ipython's usage of event loops we need something called nested asynchronous loops which is not yet implemented in Python. Luckily there is nest_asyncio to deal with the issue. All you need to do is:

!pip install nest_asyncio # use ! within Jupyter Notebook, else pip install in shell
import nest_asyncio
nest_asyncio.apply()

(Based on this thread)

Only when you call loop.close() it throws another error as it probably refers to Ipython's main loop.

RuntimeError: Cannot close a running event loop

I'll update this answer as soon as someone answered to this github issue.

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

Easy pretty printing of floats in python?

It's an old question but I'd add something potentially useful:

I know you wrote your example in raw Python lists, but if you decide to use numpy arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:

import numpy as np
np.set_printoptions(precision=2)

Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g:

np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})

For just printing once and not changing global behavior, use np.array2string with the same arguments as above.

How to see local history changes in Visual Studio Code?

I think there is no out-of-the-box support for that in VS Code.

You can install a plugin to give you similar functionality. Eg.:

https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints

Or the more famous:

https://marketplace.visualstudio.com/items?itemName=xyz.local-history

Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore file also solves this problem).

Insert a row to pandas dataframe

Just assign row to a particular index, using loc:

 df.loc[-1] = [2, 3, 4]  # adding a row
 df.index = df.index + 1  # shifting index
 df = df.sort_index()  # sorting by index

And you get, as desired:

    A  B  C
 0  2  3  4
 1  5  6  7
 2  7  8  9

See in Pandas documentation Indexing: Setting with enlargement.

http to https through .htaccess

Try the following:

 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Also, you can also redirect based on port number, for example:

 RewriteCond %{SERVER_PORT} ^80$
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

This will redirect all requests received on port 80 to HTTPS.

Exception.Message vs Exception.ToString()

In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

How to custom switch button?

I achieved this

enter image description here

by doing:

1) custom selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_switch_off"
          android:state_checked="false"/>
    <item android:drawable="@drawable/ic_switch_on"
          android:state_checked="true"/>
</selector>

2) using v7 SwitchCompat

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"
    android:button="@drawable/checkbox_yura"
    android:thumb="@null"
    app:track="@null"/>

Where value in column containing comma delimited values

SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, column)

If it turns out your column has whitespaces in between the list items, use

SELECT * FROM TABLENAME WHERE FIND_IN_SET(@search, REPLACE(column, ' ', ''))

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

How to split a string in shell and get the last field

You could try something like this if you want to use cut:

echo "1:2:3:4:5" | cut -d ":" -f5

You can also use grep try like this :

echo " 1:2:3:4:5" | grep -o '[^:]*$'

C# Test if user has write access to a folder

I tried most of these, but they give false positives, all for the same reason.. It is not enough to test the directory for an available permission, you have to check that the logged in user is a member of a group that has that permission. To do this you get the users identity, and check if it is a member of a group that contains the FileSystemAccessRule IdentityReference. I have tested this, works flawlessly..

    /// <summary>
    /// Test a directory for create file access permissions
    /// </summary>
    /// <param name="DirectoryPath">Full path to directory </param>
    /// <param name="AccessRight">File System right tested</param>
    /// <returns>State [bool]</returns>
    public static bool DirectoryHasPermission(string DirectoryPath, FileSystemRights AccessRight)
    {
        if (string.IsNullOrEmpty(DirectoryPath)) return false;

        try
        {
            AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
            WindowsIdentity identity = WindowsIdentity.GetCurrent();

            foreach (FileSystemAccessRule rule in rules)
            {
                if (identity.Groups.Contains(rule.IdentityReference))
                {
                    if ((AccessRight & rule.FileSystemRights) == AccessRight)
                    {
                        if (rule.AccessControlType == AccessControlType.Allow)
                            return true;
                    }
                }
            }
        }
        catch { }
        return false;
    }

How to make circular background using css?

Here is a solution for doing it with a single div element with CSS properties, border-radius does the magic.

CSS:

.circle{
    width:100px;
    height:100px;
    border-radius:50px;
    font-size:20px;
    color:#fff;
    line-height:100px;
    text-align:center;
    background:#000
}

HTML:

<div class="circle">Hello</div>

Ajax Success and Error function failure

You can implement error-specific logic as follows:

error: function (XMLHttpRequest, textStatus, errorThrown) {
    if (textStatus == 'Unauthorized') {
        alert('custom message. Error: ' + errorThrown);
    } else {
        alert('custom message. Error: ' + errorThrown);
    }
}

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

Postgresql, update if row with some unique value exists, else insert

I found this post more relevant in this scenario:

WITH upsert AS (
     UPDATE spider_count SET tally=tally+1 
     WHERE date='today' AND spider='Googlebot' 
     RETURNING *
)
INSERT INTO spider_count (spider, tally) 
SELECT 'Googlebot', 1 
WHERE NOT EXISTS (SELECT * FROM upsert)

Select first and last row from grouped data

Just for completeness: You can pass slice a vector of indices:

df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))

which gives

  id stopId stopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      b            1
6  3      a            3

add item in array list of android

This will definitely work for you...

ArrayList<String> list = new ArrayList<String>();

list.add(textview.getText().toString());
list.add("B");
list.add("C");

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

In my case, that happened because icu4c was upgraded to version 63 but my locally installed postgres image still referenced icu4c 62.1. Therefore i had to change the icu4c version used:

 brew info icu4c
 brew switch icu4c <version>

Where version is the the installed version returned by info

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

First you should install binary:

On Linux

sudo apt-get update
sudo apt-get install libleptonica-dev 
sudo apt-get install tesseract-ocr tesseract-ocr-dev
sudo apt-get install libtesseract-dev

On Mac

brew install tesseract

On Windows

download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' to your script.

Then you should install python package using pip:

pip install tesseract
pip install tesseract-ocr

references: https://pypi.org/project/pytesseract/ (INSTALLATION section) and https://github.com/tesseract-ocr/tesseract/wiki#installation

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

Searching if value exists in a list of objects using Linq

customerList.Any(x=>x.Firstname == "John")

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

Getting Lat/Lng from Google marker

// show the marker position //

console.log( objMarker.position.lat() );
console.log( objMarker.position.lng() );

// create a new point based into marker position //

var deltaLat = 1.002;
var deltaLng = -1.003;

var objPoint = new google.maps.LatLng( 
  parseFloat( objMarker.position.lat() ) + deltaLat, 
  parseFloat( objMarker.position.lng() ) + deltaLng
);

// now center the map using the new point //

objMap.setCenter( objPoint );

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Regex to match string containing two names in any order

You can make use of regex's quantifier feature since lookaround may not be supported all the time.

(\bjames\b){1,}.*(\bjack\b){1,}|(\bjack\b){1,}.*(\bjames\b){1,}

SQL how to make null values come last when sorting ascending

select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

VBA shorthand for x=x+1?

Sadly there are no operation-assignment operators in VBA.

(Addition-assignment += are available in VB.Net)

Pointless workaround;

Sub Inc(ByRef i As Integer)
   i = i + 1  
End Sub
...
Static value As Integer
inc value
inc value

How can I rotate an HTML <div> 90 degrees?

Use the css "rotate()" method:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  border: 1px solid black;
}

div#rotate{
  transform: rotate(90deg);
}
_x000D_
<div>
normal div
</div>
<br>

<div id="rotate">
This div is rotated 90 degrees
</div>
_x000D_
_x000D_
_x000D_

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

ASP.NET GridView RowIndex As CommandArgument

with paging you need to do some calculation

int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

import math
import numpy as np
alpha = 0.2 
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

The error:

    coff *= C 
TypeError: can't multiply sequence by non-int of type 'float'

The solution - convert the list to numpy array:

coff = np.asarray(coff) * C

Selecting data from two different servers in SQL Server

Server 2008:

When in SSMS connected to server1.DB1 and try:

SELECT  * FROM
[server2].[DB2].[dbo].[table1]

as others noted, if it doesn't work it's because the server isn't linked.

I get the error:

Could not find server DB2 in sys.servers. Verify that the correct server name was specified. If necessary, execute stored procedure sp_addlinkedserver to add the server to sys.servers.

To add the server:

reference: To add server using sp_addlinkedserver Link: [1]: To add server using sp_addlinkedserver

To see what is in your sys.servers just query it:

SELECT * FROM [sys].[servers]

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

is soft link of

/etc/ssl/openssl.cnf

You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

Fatal error: Namespace declaration statement has to be the very first statement in the script in

In my case, the file was created with UTF-8-BOM encoding. I have to save it into UTF-8 encoding, then everything works fine.

Get a pixel from HTML Canvas?

Yes sure, provided you have its context. (See how to get canvas context here.)

var imgData = context.getImageData(0,0,canvas.width,canvas.height);
// { data: [r,g,b,a,r,g,b,a,r,g,..], ... }

function getPixel(imgData, index) {
  var i = index*4, d = imgData.data;
  return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
}

// AND/OR

function getPixelXY(imgData, x, y) {
  return getPixel(imgData, y*imgData.width+x);
}



PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray

var
  idt = imgData, // See previous code snippet
  a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
  b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]

a[0] = 255 // Does nothing
getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]

b[0] = 255 // Mutates the original imgData.data
getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]

// Or use it in the function
function getPixel(imgData, index) {
  var i = index*4, d = imgData.data;
  return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
}

You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.

jQuery removeClass wildcard

An alternative way of approaching this problem is to use data attributes, which are by nature unique.

You'd set the colour of an element like: $el.attr('data-color', 'red');

And you'd style it in css like: [data-color="red"]{ color: tomato; }

This negates the need for using classes, which has the side-effect of needing to remove old classes.

1067 error on attempt to start MySQL

My issue happened right after a power failure. I got the error 1067 The process terminated unexpectedly. MySQL needless to say did not start. The answer was simple

  1. Open mysql path\data
  2. Remove (delete) both ib_logfile0 and ib_logfile1.
  3. Start the service

"for" vs "each" in Ruby

It looks like there is no difference, for uses each underneath.

$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):4

Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment

for .. in .. sets the iterator outside the scope of the loop, so

for a in [1,2]
  puts a
end

leaves a defined after the loop is finished. Where as each doesn't. Which is another reason in favor of using each, because the temp variable lives a shorter period.

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

Can't append <script> element

It is possible to dynamically load a JavaScript file using the jQuery function getScript

$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
  Display.sharePrice();
});

Now the external script will be called, and if it cannot be loaded it will gracefully degrade.

Version of Apache installed on a Debian machine

For me apachectl -V did not work, but apachectl fullstatus gave me my version.

How to convert an IPv4 address into a integer in C#?

Try this ones:

private int IpToInt32(string ipAddress)
{
   return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray(), 0);
}

private string Int32ToIp(int ipAddress)
{
   return new IPAddress(BitConverter.GetBytes(ipAddress).Reverse().ToArray()).ToString();
}

Exporting data In SQL Server as INSERT INTO

For the sake of over-explicit brainlessness, after following marc_s' instructions to here...

In SSMS in the Object Explorer, right click on the database right-click and pick "Tasks" and then "Generate Scripts".

... I then see a wizard screen with "Introduction, Choose Objects, Set Scripting Options, Summary, and Save or Publish Scripts" with prev, next, finish, cancel buttons at the bottom.

On the Set Scripting Options step, you have to click "Advanced" to get the page with the options. Then, as Ghlouw has mentioned, you now select "Types of data to script" and profit.

advanced button HIGHLIGHTED IN RED!1!!

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

The program can't start because libgcc_s_dw2-1.dll is missing

In CodeBlocks you can go to Settings...Compiler... and choose either 1) the two items in the blue box or 2) the one item in the green box

codeblocks compiler settings

Connecting to smtp.gmail.com via command line

gmail uses an encrypted connection. So, even after you establish a connection, you wont be able to send any email. The encryption is a little complex to manage. Try using openssl instead.

The thread below should help-

How to send email using simple SMTP commands via Gmail?

Installation error: INSTALL_FAILED_OLDER_SDK

This means the version of android of your avd is older than the version being used to compile the code

Xcode - ld: library not found for -lPods

In a project with multiple targets I had the same issue after changing the Scheme and App name and tried to update pods. The issue was caused because of multiple entries in Build Phases -> Link Binary with Libraries where both the previous .a library and the current one was listed, while the previous one was not existing anymore. Removing the library from there cleared the problem.

Could not autowire field in spring. why?

In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)

Facebook api: (#4) Application request limit reached

The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:

After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.

As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.

As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).

This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).

Else, you can try batch request, but I guess you're already going this way if you have big traffic.


If nothing of this works, according to the Facebook Platform Policy you should contact them.

If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).

Keras, How to get the output of each layer?

Based on all the good answers of this thread, I wrote a library to fetch the output of each layer. It abstracts all the complexity and has been designed to be as user-friendly as possible:

https://github.com/philipperemy/keract

It handles almost all the edge cases

Hope it helps!

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

How to install sshpass on mac?

Solution provided by lukesUbuntu from github works for me:

Just use brew

$ brew install http://git.io/sshpass.rb

How to process SIGTERM signal gracefully?

Based on the previous answers, I have created a context manager which protects from sigint and sigterm.

import logging
import signal
import sys


class TerminateProtected:
    """ Protect a piece of code from being killed by SIGINT or SIGTERM.
    It can still be killed by a force kill.

    Example:
        with TerminateProtected():
            run_func_1()
            run_func_2()

    Both functions will be executed even if a sigterm or sigkill has been received.
    """
    killed = False

    def _handler(self, signum, frame):
        logging.error("Received SIGINT or SIGTERM! Finishing this block, then exiting.")
        self.killed = True

    def __enter__(self):
        self.old_sigint = signal.signal(signal.SIGINT, self._handler)
        self.old_sigterm = signal.signal(signal.SIGTERM, self._handler)

    def __exit__(self, type, value, traceback):
        if self.killed:
            sys.exit(0)
        signal.signal(signal.SIGINT, self.old_sigint)
        signal.signal(signal.SIGTERM, self.old_sigterm)


if __name__ == '__main__':
    print("Try pressing ctrl+c while the sleep is running!")
    from time import sleep
    with TerminateProtected():
        sleep(10)
        print("Finished anyway!")
    print("This only prints if there was no sigint or sigterm")

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

Example JavaScript code to parse CSV data

Here's my simple vanilla JavaScript code:

let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0) 
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

Difference between / and /* in servlet mapping url pattern

The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").

In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.

Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).

See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.

Regular expression to match non-ASCII characters?

Unicode Property Escapes are among the features of ES2018.

Basic Usage

With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression:

/\p{Letter}/u

Or with the shorthand, even terser:

/\p{L}/u

Matching Words

Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters together with other word-characters like hyphens:

/[\p{L}-]/u

Stitching it all together, you could match words of all[1] languages with this beautifully short RegEx:

/[\p{L}-]+/ug

Example (shamelessly plugged from the answer above):

'Düsseldorf, Köln, ??????, ???, ??????? !@#$'.match(/[\p{L}-]+/ug)

// ["Düsseldorf", "Köln", "??????", "???", "???????"]

[1] Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words besides letters and hyphens.

Browser Support

This feature is available in all major evergreen browsers.

Transpiling

If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called regexpu. There's an online demo available here. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression:

/(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])/

If you're using Babel, there's also a regexpu-powered plugin for that (Babel v6 plugin, Babel v7 plugin).

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How to import .py file from another directory?

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib
module = importlib.load_module('folder.filename')
module.function()

Kudos to Sebastian for spplying a similar answer for Python2:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

Loop through columns and add string lengths as new columns

With dplyr and stringr you can use mutate_all:

> df %>% mutate_all(funs(length = str_length(.)))

     col1     col2 col1_length col2_length
1     abc adf qqwe           3           8
2    abcd        d           4           1
3       a        e           1           1
4 abcdefg        f           7           1

Php $_POST method to get textarea value

Make sure your escaping the HTML characters

E.g.

// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
    // Escape any html characters
    echo htmlentities($_POST['contact_list']);
}

This would occur because of the angle brackets and the browser thinking they are tags.

See: http://php.net/manual/en/function.htmlentities.php

How do I exit a WPF application programmatically?

private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
   System.Windows.Application.Current.MainWindow.Close();
}

//Override the onClose method in the Application Main window

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result =   MessageBox.Show("Do you really want to close", "",
                                          MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.Cancel)
    {
       e.Cancel = true;
    }
    base.OnClosing(e);
}

Is there Selected Tab Changed Event in the standard WPF Tab Control

I tied this in the handler to make it work:

void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
      //do work when tab is changed
    }
}

Maven dependencies are failing with a 501 error

Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.

If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts.

(source)

We have made the following changes in my project's build.gradle:

Old:

repositories {
   maven { url "http://repo.maven.apache.org/maven2" }
}

New:

repositories {
   maven { url "https://repo.maven.apache.org/maven2" }
}

How do I print to the debug output window in a Win32 app?

You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L prefix:

OutputDebugStringW(L"My output string.");

Normally you will use the macro version together with the _T macro like this:

OutputDebugString(_T("My output string."));

If you project is configured to build for UNICODE it will expand into:

OutputDebugStringW(L"My output string.");

If you are not building for UNICODE it will expand into:

OutputDebugStringA("My output string.");

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Is there a way to get the git root directory in one command?

To calculate the absolute path of the current git root directory, say for use in a shell script, use this combination of readlink and git rev-parse:

gitroot=$(readlink -f ./$(git rev-parse --show-cdup))

git-rev-parse --show-cdup gives you the right number of ".."s to get to the root from your cwd, or the empty string if you are at the root. Then prepend "./" to deal with the empty string case and use readlink -f to translate to a full path.

You could also create a git-root command in your PATH as a shell script to apply this technique:

cat > ~/bin/git-root << EOF
#!/bin/sh -e
cdup=$(git rev-parse --show-cdup)
exec readlink -f ./$cdup
EOF
chmod 755 ~/bin/git-root

(The above can be pasted into a terminal to create git-root and set execute bits; the actual script is in lines 2, 3 and 4.)

And then you'd be able to run git root to get the root of your current tree. Note that in the shell script, use "-e" to cause the shell to exit if the rev-parse fails so that you can properly get the exit status and error message if you are not in a git directory.

REST API - Use the "Accept: application/json" HTTP Header

Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement

from your model class and than run the same url, you have used for xml representation.

Make sure that you have jacson-databind dependency in your pom.xml

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1</version>
</dependency>

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

Connect to Oracle DB using sqlplus

Easy way (using XE):

1). Configure your tnsnames.ora

XE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.DOMAIN.COM)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = XE)
    )
  )

You can replace HOST.DOMAIN.COM with IP address, the TCP port by default is 1521 (ckeck it) and look that name of this configuration is XE

2). Using your app named sqlplus:

sqlplus SYSTEM@XE

SYSTEM should be replaced with an authorized USER, and put your password when prompt appear

3). See at firewall for any possibilities of some blocked TCP ports and fix it if appear

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780

Set database from SINGLE USER mode to MULTI USER

I googled for the solution for a while and finally came up with the below solution,

SSMS in general uses several connections to the database behind the scenes.

You will need to kill these connections before changing the access mode.(I have done it with EXEC(@kill); in the code template below.)

Then,

Run the following SQL to set the database in MULTI_USER mode.

USE master
GO
DECLARE @kill varchar(max) = '';
SELECT @kill = @kill + 'KILL ' + CONVERT(varchar(10), spid) + '; '
FROM master..sysprocesses 
WHERE spid > 50 AND dbid = DB_ID('<Your_DB_Name>')
EXEC(@kill);

GO
SET DEADLOCK_PRIORITY HIGH
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

To switch back to Single User mode, you can use:

ALTER DATABASE [<Your_DB_Name>] SET SINGLE_USER

This should work. Happy coding!!

Thanks!!

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

How do you convert a JavaScript date to UTC?

Here's my method:

var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

HashMap allows duplicates?

Hashmap type Overwrite that key if hashmap key is same key

map.put("1","1111");
map.put("1","2222");

output

key:value
1:2222

How to declare array of zeros in python (or an array of a certain size)

The question says "How to declare array of zeros ..." but then the sample code references the Python list:

buckets = []   # this is a list

However, if someone is actually wanting to initialize an array, I suggest:

from array import array

my_arr = array('I', [0] * count)

The Python purist might claim this is not pythonic and suggest:

my_arr = array('I', (0 for i in range(count)))

The pythonic version is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.

Reflection generic get field value

Like answered before, you should use:

Object value = field.get(objectInstance);

Another way, which is sometimes prefered, is calling the getter dynamically. example code:

public static Object runGetter(Field field, BaseValidationObject o)
{
    // MZ: Find the correct method
    for (Method method : o.getMethods())
    {
        if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
        {
            if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
            {
                // MZ: Method found, run it
                try
                {
                    return method.invoke(o);
                }
                catch (IllegalAccessException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }
                catch (InvocationTargetException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }

            }
        }
    }


    return null;
}

Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;

    for (Class<?> c = someClass; c != null; c = c.getSuperclass())
    {
        Field[] fields = c.getDeclaredFields();
        for (Field classField : fields)
        {
            result.add(classField);
        }
    }