Programs & Examples On #Dbpedia

DBpedia is a community project focused on transforming Wikipedia content in structured data represented using RDF Language statements. In addition to Wikipedia content transformation, it also publishes said content into the World Wide Web, as Linked Open Data, by adhering Linked Data principles. If you are completely new to SPARQL, please consider to ask your question on opendata.stackexchange.com.

Parsing XML with namespace in Python via 'ElementTree'

Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.

To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse function, parsing only namespace start events (start-ns):

>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
...     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...     xmlns:owl="http://www.w3.org/2002/07/owl#"
...     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
...     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
...     xmlns="http://dbpedia.org/ontology/">
... 
...     <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
...         <rdfs:label xml:lang="en">basketball league</rdfs:label>
...         <rdfs:comment xml:lang="en">
...           a group of sports teams that compete against each other
...           in Basketball
...         </rdfs:comment>
...     </owl:Class>
... 
... </rdf:RDF>'''
>>> my_namespaces = dict([
...     node for _, node in ElementTree.iterparse(
...         StringIO(my_schema), events=['start-ns']
...     )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
 'owl': 'http://www.w3.org/2002/07/owl#',
 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
 'xsd': 'http://www.w3.org/2001/XMLSchema#'}

Then the dictionary can be passed as argument to the search functions:

root.findall('owl:Class', my_namespaces)

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

How can I disable an <option> in a <select> based on its value in JavaScript?

var vals = new Array( 2, 3, 5, 8 );
select_disable_options('add_reklamaciq_reason',vals);
select_disable_options('add_reklamaciq_reason');

function select_disable_options(selectid,vals){
  var selected = false ;
  $('#'+selectid+' option').removeAttr('selected');
  $('#'+selectid+' option').each(function(i,elem){
       var elid = parseInt($(elem).attr('value'));
       if(vals){
           if(vals.indexOf(elid) != -1){
               $(elem).removeAttr('disabled');
               if(selected == false){
                   $(elem).attr('selected','selected');
                   selected = true ; 
               }
           }else{
               $(elem).attr('disabled','disabled'); 
           }
       }else{
            $(elem).removeAttr('disabled');
       }
  });   
}

Here with JQ .. if anybody search it

Running code after Spring Boot starts

Have you tried ApplicationReadyEvent?

@Component
public class ApplicationStartup 
implements ApplicationListener<ApplicationReadyEvent> {

  /**
   * This event is executed as late as conceivably possible to indicate that 
   * the application is ready to service requests.
   */
  @Override
  public void onApplicationEvent(final ApplicationReadyEvent event) {

    // here your code ...

    return;
  }
}

Code from: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

This is what the documentation mentions about the startup events:

...

Application events are sent in the following order, as your application runs:

An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.

An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.

An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.

An ApplicationFailedEvent is sent if there is an exception on startup.

...

Loading an image to a <img> from <input file>

Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.

* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)

Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)

Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

How to use HTTP_X_FORWARDED_FOR properly?

HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP']) returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.

How to iterate over each string in a list of strings and operate on it's elements

The reason is that in your second example i is the word itself, not the index of the word. So

for w1 in words:
     if w1[0] == w1[len(w1) - 1]:
       c += 1
     print c

would the equivalent of your code.

"The Controls collection cannot be modified because the control contains code blocks"

For some cases ResolveUrl and ResolveClientUrl works but not all times especially in case of js script files. What happens is it works for some pages but when you navigate to some other pages it might not work due to relative path of that particular page.

So finally my suggestion is always do a complete recheck of your site pages for whether all your javascript references are fine or not. Open your site in Google Chrome -> right click on the page -> click view source page -> HTML appears -> now click your JS hyperlinks; if its working fine it should open the js file in another browser window, otherwise it will not open.

array of string with unknown size

As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:

String[] s = yourListOfString.ToArray();

Xcode - ld: library not found for -lPods

This was my issue while trying to integrate Firebase to my Xcode project using cocoapods

library not found for -lGoogleToolboxForMac
linker command failed with exit code 1 (use -v to see invocation)

After hours of searching and trying out various fixes listed in the stackoverflow, my issue was finally fixed doing following steps

  1. Go to Build Settings, search for Other Linker Flags, remove all values expect $(inherited) Image

Do this for all targets.

  1. Delete the pods folder. (ios/Pods)
  2. Do pod update

Voila! All linker errors will be gone.

OWIN Startup Class Missing

If you don't want to use the OWIN startup, this is what you should add to your web.config file:

Under AppSettings add the following line:

    <add key="owin:AutomaticAppStartup" value="false" />

This is how it should look like in your web.config:

  <appSettings>
    <add key="owin:AutomaticAppStartup" value="false" />
  </appSettings>

UTF-8 encoding problem in Spring MVC

You need add charset in the RequestMapping annotation:

@RequestMapping(path = "/account",  produces = "application/json;charset=UTF-8")

thats all.

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

How do you merge two Git repositories?

I wanted to move a small project to a subdirectory of a larger one. Since my small project did not have many commits, I used git format-patch --output-directory /path/to/patch-dir. Then on the larger project, I used git am --directory=dir/in/project /path/to/patch-dir/*.

This feels way less scary and way more cleaner than a filter-branch. Granted, it may not be applicable to all cases.

Ajax using https on an http page

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

How to make my layout able to scroll down?

Just wrap all that inside a ScrollView

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ruatech.sanikamal.justjava.MainActivity">
<!-- Here you put the rest of your current view-->
</ScrollView>

What is the best open-source java charting library? (other than jfreechart)

There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.

How do I put a variable inside a string?

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

Best way to show a loading/progress indicator?

ProgressDialog has become deprecated since API Level 26 https://developer.android.com/reference/android/app/ProgressDialog.html

I include a ProgressBar in my layout

   <ProgressBar
        android:layout_weight="1"
        android:id="@+id/progressBar_cyclic"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:minWidth="40dp" />

and change its visibility to .GONE | .VISIBLE depending on the use case.

    progressBar_cyclic.visibility = View.VISIBLE

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Best practice to look up Java Enum

Apache Commons Lang 3 contais the class EnumUtils. If you aren't using Apache Commons in your projects, you're doing it wrong. You are reinventing the wheel!

There's a dozen of cool methods that we could use without throws an Exception. For example:

Gets the enum for the class, returning null if not found.

This method differs from Enum.valueOf in that it does not throw an exceptionfor an invalid enum name and performs case insensitive matching of the name.

EnumUtils.getEnumIgnoreCase(SeasonEnum.class, season);

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

If the error happens with error column "File" as SGEN, then the fix needs to be in a file sgen.exe.config, next to sgen.exe. For example, for VS 2015, create C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sgen.exe.config. Minimum file contents: <configuration><startup useLegacyV2RuntimeActivationPolicy="true"/></configuration>

Source: SGEN Mixed mode assembly

Authentication issue when debugging in VS2013 - iis express

You could also modify the project properties for your web project, choose "Web" from left tabs, then change the Servers drop down to "Local IIS". Create a new virtual directory and use IIS manager to setup your site/app pool as desired.

I prefer this method, as you would typically have a local IIS v-directory (or site) to test locally. You won't affect any other sites this way either.

Web Project Properties

How to style a select tag's option element?

Since version 49+, Chrome has supported styling <option> elements with font-weight. Source: https://code.google.com/p/chromium/issues/detail?id=44917#c22

New SELECT Popup: font-weight style should be applied.

This CL removes themeChromiumSkia.css. |!important| in it prevented to apply font-weight. Now html.css has |font-weight:normal|, and |!important| should be unnecessary.

There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important; in it all this time. It was introduced to the stable Chrome channel in version 49.0.

Merge PDF files with PHP

Below is the php PDF merge command.

$fileArray= array("name1.pdf","name2.pdf","name3.pdf","name4.pdf");

$datadir = "save_path/";
$outputName = $datadir."merged.pdf";

$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$outputName ";
//Add each pdf file to the end of the command
foreach($fileArray as $file) {
    $cmd .= $file." ";
}
$result = shell_exec($cmd);

I forgot the link from where I found it, but it works fine.

Note: You should have gs (on linux and probably Mac), or Ghostscript (on windows) installed for this to work.

Java: Detect duplicates in ArrayList?

Simply put: 1) make sure all items are comparable 2) sort the array 2) iterate over the array and find duplicates

How do I get my C# program to sleep for 50 msec?

Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

Eclipse, regular expression search and replace

Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2

...replaces ...

from checks import checklist(_list):

...with...

from checks import checklist



Blocks in regex are delineated by parenthesis (which are not preceded by a "\")

(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)

(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)

(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"

Then in the replace, just put the $1$2 to replace all three blocks with just the first two.



Screenshot

How do I install command line MySQL client on mac?

The mysql client is available in macOS ports. If you don't have this excellent third party package manager already installed, it is available from here: https://www.macports.org/

Once you have installed macports, open a terminal and make sure everything is up to date:

sudo port selfupdate

There are multiple different versions of MySQL and mariadb (community fork of MySQL) available in the ports repos. List available versions using the following command:

port search 'mariadb*'

I recommend choosing mariadb over mysql as it is, mostly, a drop in replacement (https://mariadb.com/kb/en/mariadb-vs-mysql-compatibility/) and has excellent community support.

If applicable, choose which version of mariadb you want (a list of versions of mariadb is available here: https://downloads.mariadb.org/mariadb/+releases/). If you're not bothered, install the default version:

sudo port install mariadb

Mariadb (including the mysql-compatible command line client) is now available on your system. On my system, the CLI client resides in the following location:

$ /opt/local/bin/mysql --version
/opt/local/bin/mysql  Ver 15.1 Distrib 5.5.68-MariaDB, for osx10.15 (x86_64) using readline 5.1

It's obviously a bit inconvenient to type out the full path, /opt/local/bin/mysql each time you want to use the client. Ports has already thought of this problem. To view available versions of mysql on your system, run:

$ port select mysql

Available versions for mysql:
mariadb (active)
none

Choose one from the list. For example, to use mariadb as the default mysql client:

sudo port select mysql mariadb

Now open a fresh terminal window and you should be able to start the mariadb mysql CLI client:

mysql -h <hostname> -u <username> -p

"Please provide a valid cache path" error in laravel

Your storage directory may be missing, or one of its sub-directories. The storage directory must have all the sub-directories that shipped with the Laravel installation.

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

Subversion stuck due to "previous operation has not finished"?

Running console svn cleanup has solved the same problem for me.

How do I sleep for a millisecond in Perl?

From perlfaq8:


How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).

jQuery detect if textarea is empty

if (!$.trim($("element").val())) {

}

$watch an object

The form object isn't changing, only the name property is

updated fiddle

function MyController($scope) {
$scope.form = {
    name: 'my name',
}

$scope.changeCount = 0;
$scope.$watch('form.name', function(newVal, oldVal){
    console.log('changed');
    $scope.changeCount++;
});
}

Set value of hidden field in a form using jQuery's ".val()" doesn't work

If you are searching for haml then this is the answer for hidden field to set value to a hidden field like

%input#forum_id.hidden

In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.

$('#forum_id').attr('val',forum_id.toString());

Static constant string (class member)

You can either go for the const char* solution mentioned above, but then if you need string all the time, you're going to have a lot of overhead.
On the other hand, static string needs dynamic initialization, thus if you want to use its value during another global/static variable's initialization, you might hit the problem of initialization order. To avoid that, the cheapest thing is accessing the static string object through a getter, which checks if your object is initialized or not.

//in a header  
class A{  
  static string s;   
public:   
  static string getS();  
};  
//in implementation  
string A::s;  
namespace{  
  bool init_A_s(){  
    A::s = string("foo");   
    return true;  
  }  
  bool A_s_initialized = init_A_s();  
}  
string A::getS(){      
  if (!A_s_initialized)  
    A_s_initialized = init_A_s();  
  return s;  
}  

Remember to only use A::getS(). Because any threading can only started by main(), and A_s_initialized is initialized before main(), you don't need locks even in a multithreaded environment. A_s_initialized is 0 by default (before the dynamic initialization), so if you use getS() before s is initialized, you call the init function safely.

Btw, in the answer above: "static const std::string RECTANGLE() const" , static functions cannot be const because they cannot change the state if any object anyway (there is no this pointer).

How do I resolve ClassNotFoundException?

A classpath is a list of locations to load classes from.

These 'locations' can either be directories, or jar files.

For directories, the JVM will follow an expected pattern for loading a class. If I have the directory C:/myproject/classes in my classpath, and I attempt to load a class com.mycompany.Foo, it will look under the classes directory for a directory called com, then under that a directory called mycompany, and finally it will look for a file called Foo.class in that directory.

In the second instance, for jar files, it will search the jar file for that class. A jar file is in reality just a zipped collection of directories like the above. If you unzip a jar file, you'll get a bunch of directories and class files following the pattern above.

So the JVM traverses a classpath from start to finish looking for the definition of the class when it attempts to load the class definition. For example, in the classpath :

C:/myproject/classes;C:/myproject/lib/stuff.jar;C:/myproject/lib/otherstuff.jar

The JVM will attempt to look in the directory classes first, then in stuff.jar and finally in otherstuff.jar.

When you get a ClassNotFoundException, it means the JVM has traversed the entire classpath and not found the class you've attempted to reference. The solution, as so often in the Java world, is to check your classpath.

You define a classpath on the command line by saying java -cp and then your classpath. In an IDE such as Eclipse, you'll have a menu option to specify your classpath.

How does facebook, gmail send the real time notification?

Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.

Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E

Note: my answers best fits for mobile devices.

adb connection over tcp not working now

This answer is late, but hopefully it helps others.

I have had the same experience of not being able to connect. Rebooting phone and PC does not help. I found the fix at: http://developer.android.com/tools/help/adb.html at the bottom of the page.

Basically you follow these steps:

  1. Connect phone with usb cable to PC.
  2. Issue command: adb usb
  3. Issue command: adb tcpip 5555
  4. Issue command: adb connect xxx.xxx.xxx.xxx

Where xxx.xxx.xxx.xxx is your phone's IP address.

How to create json by JavaScript for loop?

If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.

I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.

Here is example code. Tryout on your FireBug Console

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

Use Font Awesome icon as CSS content

Here's my webpack 4 + font awesome 5 solution:

webpack plugin:

new CopyWebpackPlugin([
    { from: 'node_modules/font-awesome/fonts', to: 'font-awesome' }
  ]),

global css style:

@font-face {
    font-family: 'FontAwesome';
    src: url('/font-awesome/fontawesome-webfont.eot');
    src: url('/font-awesome/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
    url('/font-awesome/fontawesome-webfont.woff2') format('woff2'),
    url('/font-awesome/fontawesome-webfont.woff') format('woff'),
    url('/font-awesome/fontawesome-webfont.ttf') format('truetype'),
    url('/font-awesome/fontawesome-webfont.svgfontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

i {
    font-family: "FontAwesome";
}

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

For future readers, one easy way is as follows if they wish to export in bulk using bash,

akshay@ideapad:/tmp$ mysql -u someuser -p test -e "select * from offices"
Enter password: 
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| officeCode | city          | phone            | addressLine1             | addressLine2 | state      | country   | postalCode | territory |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| 1          | San Francisco | +1 650 219 4782  | 100 Market Street        | Suite 300    | CA         | USA       | 94080      | NA        |
| 2          | Boston        | +1 215 837 0825  | 1550 Court Place         | Suite 102    | MA         | USA       | 02107      | NA        |
| 3          | NYC           | +1 212 555 3000  | 523 East 53rd Street     | apt. 5A      | NY         | USA       | 10022      | NA        |
| 4          | Paris         | +33 14 723 4404  | 43 Rue Jouffroy D'abbans | NULL         | NULL       | France    | 75017      | EMEA      |
| 5          | Tokyo         | +81 33 224 5000  | 4-1 Kioicho              | NULL         | Chiyoda-Ku | Japan     | 102-8578   | Japan     |
| 6          | Sydney        | +61 2 9264 2451  | 5-11 Wentworth Avenue    | Floor #2     | NULL       | Australia | NSW 2010   | APAC      |
| 7          | London        | +44 20 7877 2041 | 25 Old Broad Street      | Level 7      | NULL       | UK        | EC2N 1HN   | EMEA      |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+

If you're exporting by non-root user then set permission like below

root@ideapad:/tmp# mysql -u root -p
MariaDB[(none)]> UPDATE mysql.user SET File_priv = 'Y' WHERE user='someuser' AND host='localhost';

Restart or Reload mysqld

akshay@ideapad:/tmp$ sudo su
root@ideapad:/tmp#  systemctl restart mariadb

Sample code snippet

akshay@ideapad:/tmp$ cat test.sh 
#!/usr/bin/env bash

user="someuser"
password="password"
database="test"

mysql -u"$user" -p"$password" "$database" <<EOF
SELECT * 
INTO OUTFILE '/tmp/csvs/offices.csv' 
FIELDS TERMINATED BY '|' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n'
FROM offices;
EOF

Execute

akshay@ideapad:/tmp$ mkdir -p /tmp/csvs
akshay@ideapad:/tmp$ chmod +x test.sh
akshay@ideapad:/tmp$ ./test.sh 
akshay@ideapad:/tmp$ cat /tmp/csvs/offices.csv 
"1"|"San Francisco"|"+1 650 219 4782"|"100 Market Street"|"Suite 300"|"CA"|"USA"|"94080"|"NA"
"2"|"Boston"|"+1 215 837 0825"|"1550 Court Place"|"Suite 102"|"MA"|"USA"|"02107"|"NA"
"3"|"NYC"|"+1 212 555 3000"|"523 East 53rd Street"|"apt. 5A"|"NY"|"USA"|"10022"|"NA"
"4"|"Paris"|"+33 14 723 4404"|"43 Rue Jouffroy D'abbans"|\N|\N|"France"|"75017"|"EMEA"
"5"|"Tokyo"|"+81 33 224 5000"|"4-1 Kioicho"|\N|"Chiyoda-Ku"|"Japan"|"102-8578"|"Japan"
"6"|"Sydney"|"+61 2 9264 2451"|"5-11 Wentworth Avenue"|"Floor #2"|\N|"Australia"|"NSW 2010"|"APAC"
"7"|"London"|"+44 20 7877 2041"|"25 Old Broad Street"|"Level 7"|\N|"UK"|"EC2N 1HN"|"EMEA"

Unable to Install Any Package in Visual Studio 2015

I found a solution for this in my case, try to update the NuGet Package Manager.

To do this:

  1. From VS, go to Tools -> Extensions and Updates
  2. Open the Updates menu option at the left, then select Visual Studio Gallery.
  3. If there is an update for Nuget Package Installer, it should show in the list to the right. Click Update
  4. Restart Visual Studio

This let me install packages without problem again.

Hope this helps!

Display an image into windows forms

I display images in windows forms when I put it in Load event like this:

    private void Form1_Load( object sender , EventArgs e )
    {
        pictureBox1.ImageLocation = "./image.png"; //path to image
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

How to change column datatype from character to numeric in PostgreSQL 8.4

Step 1: Add new column with integer or numeric as per your requirement

Step 2: Populate data from varchar column to numeric column

Step 3: drop varchar column

Step 4: change new numeric column name as per old varchar column

tar: add all files and directories in current directory INCLUDING .svn and so on

Actually the problem is with the compression options. The trick is the pipe the tar result to a compressor instead of using the built-in options. Incidentally that can also give you better compression, since you can set extra compresion options.

Minimal tar:

tar --exclude=*.tar* -cf workspace.tar .

Pipe to a compressor of your choice. This example is verbose and uses xz with maximum compression:

tar --exclude=*.tar* -cv . | xz -9v >workspace.tar.xz

Solution was tested on Ubuntu 14.04 and Cygwin on Windows 7. It's a community wiki answer, so feel free to edit if you spot a mistake.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

mvc:annotation-driven is a tag added in Spring 3.0 which does the following:

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)

context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

Can we cast a generic object to a custom object type in javascript?

This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

CustomObject.create = function (obj) {
    var field = new CustomObject();
    for (var prop in obj) {
        if (field.hasOwnProperty(prop)) {
            field[prop] = obj[prop];
        }
    }

    return field;
}

Use like this

var typedObj = CustomObject.create(genericObj);

Cannot refer to a non-final variable inside an inner class defined in a different method

use ClassName.this.variableName to reference the non-final variable

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

How do I restore a dump file from mysqldump?

Using a 200MB dump file created on Linux to restore on Windows w/ mysql 5.5 , I had more success with the

source file.sql

approach from the mysql prompt than with the

mysql  < file.sql

approach on the command line, that caused some Error 2006 "server has gone away" (on windows)

Weirdly, the service created during (mysql) install refers to a my.ini file that did not exist. I copied the "large" example file to my.ini which I already had modified with the advised increases.

My values are

[mysqld]
max_allowed_packet = 64M
interactive_timeout = 250
wait_timeout = 250

Delete all data rows from an Excel table (apart from the first)

The codes above wouldn't work in Excel 2010 My code bellow allows you to go through number of sheets you would like then select tables and delete rows

Sub DeleteTableRows()
Dim table As ListObject
Dim SelectedCell As Range
Dim TableName As String
Dim ActiveTable As ListObject

'select ammount of sheets want to this to run
For i = 1 To 3
    Sheets(i).Select
    Range("A1").Select
    Set SelectedCell = ActiveCell
    Selection.AutoFilter

    'Determine if ActiveCell is inside a Table
    On Error GoTo NoTableSelected
    TableName = SelectedCell.ListObject.Name
    Set ActiveTable = ActiveSheet.ListObjects(TableName)
    On Error GoTo 0

    'Clear first Row
    ActiveTable.DataBodyRange.Rows(1).ClearContents
    'Delete all the other rows `IF `they exist
    On Error Resume Next
    ActiveTable.DataBodyRange.Offset(1, 0).Resize(ActiveTable.DataBodyRange.Rows.Count - 1, _
    ActiveTable.DataBodyRange.Columns.Count).Rows.Delete
    Selection.AutoFilter
    On Error GoTo 0
Next i
Exit Sub
'Error Handling
NoTableSelected:
  MsgBox "There is no Table currently selected!", vbCritical

End Sub

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

How to check if directory exist using C++ and winAPI

If linking to the shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function

How do I remove the title bar from my app?

For Beginner Like Me. Just Do it what I say.From your Android Project.

app -> res -> values -> style.xml

replace this code

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

</resources>

Enjoy.

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

HTML code for INR

Use this for Indian rupee sign:

&#2352; — र

How do I retrieve my MySQL username and password?

Stop the MySQL process.

Start the MySQL process with the --skip-grant-tables option.

Start the MySQL console client with the -u root option.

List all the users;

SELECT * FROM mysql.user;

Reset password;

UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';

But DO NOT FORGET to

Stop the MySQL process

Start the MySQL Process normally (i.e. without the --skip-grant-tables option)

when you are finished. Otherwise, your database's security could be compromised.

How to len(generator())

You can use send as a hack:

def counter():
    length = 10
    i = 0
    while i < length:
        val = (yield i)
        if val == 'length':
            yield length
        i += 1

it = counter()
print(it.next())
#0
print(it.next())
#1
print(it.send('length'))
#10
print(it.next())
#2
print(it.next())
#3

Can I use DIV class and ID together in CSS?

#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

How to split an integer into an array of digits?

Another solution that does not involve converting to/from strings:

from math import log10

def decompose(n):
    if n == 0:
        return [0]
    b = int(log10(n)) + 1
    return [(n // (10 ** i)) % 10 for i in reversed(range(b))]

Vertical Align text in a Label

You can use flexbox in 2018+:

.label-class {
    display: flex;
    align-items: center;
}

Browser support: https://caniuse.com/#search=flexbox

How do I check for null values in JavaScript?

Try this:

if (!variable && typeof variable === "object") {
    // variable is null
}

Get access to parent control from user control - C#

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

pip install returning invalid syntax

You need to be in the specific folder where pip.exe exists, then do the following steps:

  1. open cmd.exe
  2. write the following command:
    cd "The path to the python folder"

or in my case, i wrote

    cd C:\Users\username\AppData\Local\Programs\Python\Python37-32\Scripts
  1. then write the following command
    pip install *anypackage*

Positioning <div> element at center of screen

If there are anyone looking for a solution,

I found this,

Its the best solution i found yet!

div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

http://dabblet.com/gist/2872671

Hope you enjoy!

Find closing HTML tag in Sublime Text

Under the "Goto" menu, Control + M is Jump to Matching Bracket. Works for parentheses as well.

Unknown URL content://downloads/my_downloads

I got the same issue and after a lot of time spent on the search I found the solution

Just change your method especially // DownloadsProvider part

getpath()

to

@SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            // This is for checking Main Memory
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    return Environment.getExternalStorageDirectory() + "/";
                }
                // This is for checking SD Card
            } else {
                return "storage" + "/" + docId.replace(":", "/");
            }

        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

For more solution click on the link here

https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8

I hope will do the same for you!

Android disable screen timeout while app is running

Simple add below line into your MainActivity and your App never turn lights off.

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

Can't use WAMP , port 80 is used by IIS 7.5

Yes, you can just change the port to to any number. For instance change Listen 80 to Listen 81 in the httpd.conf file. Now try with http://localhost:81 and it will respond on port 81!!

How to use ClassLoader.getResources() correctly?

MRalwasser, I'd give you a hint, cast the URL.getConnection() to JarURLConnection. Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.

The rest I leave to you.

Hope this helps!

How to align linearlayout to vertical center?

Use android:weightSum property to the parent LinearLayout and give value 3. Then in the children LinearLayout use android:layout_weight 2 and 1 respectively. Then in the First Chil LinearLayout use android:layout_gravity="center_vertical". As shown in the following code

<LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="3"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="2"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">
                        <TextView
                            android:id="@+id/status_text"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="00"
                            android:textColor="@color/red"
                            android:textSize="@dimen/default_text_size"
                            />
                          <TextView
                            android:id="@+id/status_text"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="00"
                            android:textColor="@color/red"
                            android:textSize="@dimen/default_text_size"
                            />
                    </LinearLayout>
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1">
                        <Button
                          android:layout_width="fill_parent"
                          android:layout_height="wrap_content"
                          android:text="Delete"/>
                    </LinearLayout>
                </LinearLayout>

Working with Enums in android

According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!

Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

There are many solutions for the problem. This worked for me

Right click on Service -> Properties -> Log on as system account.

enter image description here

Java: Static vs inner class

static inner class: can declare static & non static members but can only access static members of its parents class.

non static inner class: can declare only non static members but can access static and non static member of its parent class.

Easiest way to read/write a file's content in Python

contents = open(filename)

This gives you generator so you must save somewhere the values though, or

contents = [line for line in open(filename)]

This does the saving to list explicit close is not then possible (at least with my knowledge of Python).

Does VBA have Dictionary Structure?

Building off cjrh's answer, we can build a Contains function requiring no labels (I don't like using labels).

Public Function Contains(Col As Collection, Key As String) As Boolean
    Contains = True
    On Error Resume Next
        err.Clear
        Col (Key)
        If err.Number <> 0 Then
            Contains = False
            err.Clear
        End If
    On Error GoTo 0
End Function

For a project of mine, I wrote a set of helper functions to make a Collection behave more like a Dictionary. It still allows recursive collections. You'll notice Key always comes first because it was mandatory and made more sense in my implementation. I also used only String keys. You can change it back if you like.

Set

I renamed this to set because it will overwrite old values.

Private Sub cSet(ByRef Col As Collection, Key As String, Item As Variant)
    If (cHas(Col, Key)) Then Col.Remove Key
    Col.Add Array(Key, Item), Key
End Sub

Get

The err stuff is for objects since you would pass objects using set and variables without. I think you can just check if it's an object, but I was pressed for time.

Private Function cGet(ByRef Col As Collection, Key As String) As Variant
    If Not cHas(Col, Key) Then Exit Function
    On Error Resume Next
        err.Clear
        Set cGet = Col(Key)(1)
        If err.Number = 13 Then
            err.Clear
            cGet = Col(Key)(1)
        End If
    On Error GoTo 0
    If err.Number <> 0 Then Call err.raise(err.Number, err.Source, err.Description, err.HelpFile, err.HelpContext)
End Function

Has

The reason for this post...

Public Function cHas(Col As Collection, Key As String) As Boolean
    cHas = True
    On Error Resume Next
        err.Clear
        Col (Key)
        If err.Number <> 0 Then
            cHas = False
            err.Clear
        End If
    On Error GoTo 0
End Function

Remove

Doesn't throw if it doesn't exist. Just makes sure it's removed.

Private Sub cRemove(ByRef Col As Collection, Key As String)
    If cHas(Col, Key) Then Col.Remove Key
End Sub

Keys

Get an array of keys.

Private Function cKeys(ByRef Col As Collection) As String()
    Dim Initialized As Boolean
    Dim Keys() As String

    For Each Item In Col
        If Not Initialized Then
            ReDim Preserve Keys(0)
            Keys(UBound(Keys)) = Item(0)
            Initialized = True
        Else
            ReDim Preserve Keys(UBound(Keys) + 1)
            Keys(UBound(Keys)) = Item(0)
        End If
    Next Item

    cKeys = Keys
End Function

Disable Enable Trigger SQL server for a table

if you want to execute ENABLE TRIGGER Directly From Source :

we can't write like this:

Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"

instead, we can write :

Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"

Trying to mock datetime.date.today(), but not working

Maybe you could use your own "today()" method that you will patch where needed. Example with mocking utcnow() can be found here: https://bitbucket.org/k_bx/blog/src/tip/source/en_posts/2012-07-13-double-call-hack.rst?at=default

How do I prevent a Gateway Timeout with FastCGI on Nginx

For those using nginx with unicorn and rails, most likely the timeout is in your unicorn.rb file

put a large timeout in unicorn.rb

timeout 500

if you're still facing issues, try having fail_timeout=0 in your upstream in nginx and see if this fixes your issue. This is for debugging purposes and might be dangerous in a production environment.

upstream foo_server {
        server 127.0.0.1:3000 fail_timeout=0;
}

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

SQL Server 2008- Get table constraints

You Can Get With This Query

Unique Constraint,

Default Constraint With Value,

Foreign Key With referenced Table And Column

And Primary Key Constraint.

Select C.*, (Select definition From sys.default_constraints Where object_id = C.object_id) As dk_definition,
(Select definition From sys.check_constraints Where object_id = C.object_id) As ck_definition,
(Select name From sys.objects Where object_id = D.referenced_object_id) As fk_table,
(Select name From sys.columns Where column_id = D.parent_column_id And object_id = D.parent_object_id) As fk_col
From sys.objects As C
Left Join (Select * From sys.foreign_key_columns) As D On D.constraint_object_id = C.object_id 
Where C.parent_object_id = (Select object_id From sys.objects Where type = 'U'
And name = 'Table Name Here');

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

You should remove the comment before extension on your driver.

The driver came disactivated by default you should active by yourself. after that it will work well.

I hope this do.

Remove trailing spaces automatically or with a shortcut

<Ctr>-<Shift>-<F> 

Format, does it as well.

This removes trailing whitespace and formats/indents your code.

How to 'insert if not exists' in MySQL?

Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.

This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.

Look into innodb_autoinc_lock_mode = 0 (server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).

Parsing Query String in node.js

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query

PostgreSQL, checking date relative to "today"

You could also check using the age() function

select * from mytable where age( mydate, now() ) > '1 year';

age() wil return an interval.

For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131

See postgresql documentation

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

What is the difference between g++ and gcc?

gcc and g++ are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler).

Even though they automatically determine which backends (cc1 cc1plus ...) to call depending on the file-type, unless overridden with -x language, they have some differences.

The probably most important difference in their defaults is which libraries they link against automatically.

According to GCC's online documentation link options and how g++ is invoked, g++ is equivalent to gcc -xc++ -lstdc++ -shared-libgcc (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v option (it displays the backend toolchain commands being run).

How can I find the current OS in Python?

I usually use sys.platform (docs) to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is "posix" for all of them.

For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.

Spring boot Security Disable security

In order to avoid security you can use annotations. Use this annotation on top of configure class:

@EnableWebSecurity

For example:

@EnableWebSecurity
@Configuration
public class AuthFilter{
   // configured method 
}

What is newline character -- '\n'

I think this post by Jeff Attwood addresses your question perfectly. It takes you through the differences between newlines on Dos, Mac and Unix, and then explains the history of CR (Carriage return) and LF (Line feed).

Datatables - Search Box outside datatable

This one helped me for DataTables Version 1.10.4, because its new API

var oTable = $('#myTable').DataTable();    
$('#myInputTextField').keyup(function(){
   oTable.search( $(this).val() ).draw();
})

Android Studio SDK location

create a new folder in your android studio parent directory folder. Name it sdk or whatever you want. Select that folder from the drop down list when asked. Thats what solves it for me.

Tool to generate JSON schema from JSON data

You might be looking for this:

http://www.jsonschema.net

It is an online tool that can automatically generate JSON schema from JSON string. And you can edit the schema easily.

Convert Object to JSON string

jQuery does only make some regexp checking before calling the native browser method window.JSON.parse(). If that is not available, it uses eval() or more exactly new Function() to create a Javascript object.

The opposite of JSON.parse() is JSON.stringify() which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js from http://www.json.org

JSON.stringify() is available in all major browsers, but to be compatible with older browsers you still need that fallback.

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

How do I build an import library (.lib) AND a DLL in Visual C++?

OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.

#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif

Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:

BARNABY_API int add(){
}

This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.

oracle SQL how to remove time from date

When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:

select 
    p1.PA_VALUE as StartDate,
    p2.PA_VALUE as EndDate
from WP_Work p 
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
LEFT JOIN PARAMETER p2 on p2.WP_ID=p.WP_ID AND p2.NAME = 'Date_To'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')

What parameters should I use in a Google Maps URL to go to a lat-lon?

All the answers didn't work for me (the loc: and @ options). So here is my solution for the new Google maps (April 2014)

Use the q= for query description, for example the street or the name of the place. Use ll= for the lat, long coordinates.

You can add extra parameters like t=h (hybrid) and z=19 (zoom)

https://maps.google.com/?q=11+wall+street+new+york&ll=40.7060471,-74.0088901

https://maps.google.com/?q=new+york+stock+exchange&ll=40.7060471,-74.0088901

https://maps.google.com/?q=new+york+stock+exchange&ll=40.7060471,-74.0088901&t=h&z=19

How to solve java.lang.NullPointerException error?

Just a shot in the dark(since you did not share the compiler initialization code with us): the way you retrieve the compiler causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE.

Using Java generics for JPA findAll() query with WHERE clause

you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with

entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();

MySQL - UPDATE query with LIMIT

You should highly consider using an ORDER BY if you intend to LIMIT your UPDATE, because otherwise it will update in the ordering of the table, which might not be correct.

But as Will A said, it only allows limit on row_count, not offset.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

A new solution if you use Android Studio 3.2, I solved this issue by added mavenCentral() to build.gradle of the project:

buildscript {
    ext.kotlin_version = '1.3.0'
    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        mavenCentral()
        google()
        jcenter()
    }
}

You should add the line as this order, the credited is for this answer

DateTime "null" value

You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

Spring - download response as a file

I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...

  1. To clarify on @dnc253's answer, $window.open(URL) is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universal window.open().) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method: location.href = "uriString", which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:

    $http.post(url, payload).then(function(returnData){
        var uriString = parseReturn(returnData);
        location.href="uriString"
    })
    
  2. You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)

Is there an easy way to reload css without reloading the page?

One more jQuery solution

For a single stylesheet with id "css" try this:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

Center the content inside a column in Bootstrap 4

There are multiple horizontal centering methods in Bootstrap 4...

  • text-center for center display:inline elements
  • offset-* or mx-auto can be used to center column (col-*)
  • or, justify-content-center on the row to center columns (col-*)
  • mx-auto for centering display:block elements inside d-flex

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo of the Bootstrap 4 Centering Methods

In your case, use mx-auto to center the col-3 and text-center to center it's content..

<div class="row">
    <div class="col-3 mx-auto">
        <div class="text-center">
            center
        </div>
    </div>
</div>

https://codeply.com/go/GRUfnxl3Ol

or, using justify-content-center on flexbox elements (.row):

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            center
        </div>
    </div>
</div>

Also see:
Vertical Align Center in Bootstrap 4

Error converting data types when importing from Excel to SQL Server 2008

There is a workaround.

  1. Import excel sheet with numbers as float (default).
  2. After importing, Goto Table-Design
  3. Change DataType of the column from Float to Int or Bigint
  4. Save Changes
  5. Change DataType of the column from Bigint to any Text Type (Varchar, nvarchar, text, ntext etc)
  6. Save Changes.

That's it.

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

CSS background image to fit width, height should auto-scale in proportion

Background image is not Set Perfect then his css is problem create so his css file change to below code

_x000D_
_x000D_
html {  _x000D_
  background-image: url("example.png");  _x000D_
  background-repeat: no-repeat;  _x000D_
  background-position: 0% 0%;_x000D_
  background-size: 100% 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

%; background-size: 100% 100%;"

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

How to fix ReferenceError: primordials is not defined in node

Use following commands and install node v11.15.0:

npm install -g n

sudo n 11.15.0

will solve

ReferenceError: primordials is not defined in node

Referred from @Terje Norderhaug @Tom Corelis answers.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

phpmyadmin.pma_table_uiprefs doesn't exist

I use Windows 7 Xampp's version of phpmyadmin and none of the above, or below if this post gets upvoted, answers worked. I have tried uninstalling Xampp and upgrading to a higher version, manually changing values in the config folder, importing .sql files from some github page, and even viewing youtube videos but none of the suggestions worked.

Solution:

Delete EVERYTHING in the C:\xampp\phpMyAdmin folder > go to https://www.phpmyadmin.net/ and download the latest version > extract everything to the C:\xampp\phpMyAdmin folder and your problem is solved.

^^^^^ Read this if you don't want to waste hours searching Google for tons of failed solutions. It's far simpler too! ^^^^^^

C default arguments

Another trick using macros:

#include <stdio.h>

#define func(...) FUNC(__VA_ARGS__, 15, 0)
#define FUNC(a, b, ...) func(a, b)

int (func)(int a, int b)
{
    return a + b;
}

int main(void)
{
    printf("%d\n", func(1));
    printf("%d\n", func(1, 2));
    return 0;
}

If only one argument is passed, b receives the default value (in this case 15)

How to decide when to use Node.js?

My one more reason to choose Node.js for a new project is:

Be able to do pure cloud based development

I have used Cloud9 IDE for a while and now I can't imagine without it, it covers all the development lifecycles. All you need is a browser and you can code anytime anywhere on any devices. You don't need to check in code in one Computer(like at home), then checkout in another computer(like at work place).

Of course, there maybe cloud based IDE for other languages or platforms (Cloud 9 IDE is adding supports for other languages as well), but using Cloud 9 to do Node.js developement is really a great experience for me.

Get Character value from KeyCode in JavaScript... then trim

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode(). For values of keyCode <= 96 it seems to map using the function:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:

chrCode = keyCode

If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    let keyCode = e.keyCode;_x000D_
    let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
    let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
    console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_
_x000D_
_x000D_

How to configure the web.config to allow requests of any length

It will also generate error when you pass large string in ajax call parameter.

so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.

// var UserId= array of 1000 userids

$.ajax({ global: false, url: SitePath + "/User/getAussizzMembersData", "data": { UserIds: UserId}, "type": "POST", "dataType": "JSON" }}

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

If you get Cannot redirect after HTTP headers have been sent then try this below code.

HttpContext.Current.Server.ClearError();
// Response.Headers.Clear();
HttpContext.Current.Response.Redirect("/Home/Login",false);

changing the language of error message in required field in html5 contact form

I know this is an old post but i want to share my experience.

HTML:

<input type="text" placeholder="Username or E-Mail" required data-required-message="E-Mail or Username is Required!">

Javascript (jQuery):

$('input[required]').on('invalid', function() {
    this.setCustomValidity($(this).data("required-message"));
});

This is a very simple sample. I hope this can help to anyone.

How can I get device ID for Admob

If you are testing your app on actual device then you can try this small android app which gives you the device id:

https://play.google.com/store/apps/details?id=pe.go_com.admobdeviceidfinder&hl=en

You will get the hashed device id directly. Hope this helps.

Why aren't programs written in Assembly more often?

If an average production program has say 100k lines of code, and each line is about 8-12 assembler instructions, that would be 1 million of assembler instructions.

Even if you could write all this by hand at a decent speed (remember, its 8 times more code that you have to write), what happens if you want to change some of the functionality? Understanding something you wrote a few weeks ago out of those 1 million instructions is a nightmare! There's no modules, no classes, no object-oriented design, no frameworks, no nothing. And the amount of similar looking code you have to write for even the simplest things is daunting at best.

Besides, you can't optimize your code nearly as well as a high level language. Where C for example performs an insane number of optimizations because you describe your intent, not only your code, in assembler you only write code, the assembler can't really perform any note-worthy optimizations on your code. What you write is what you get, and trust me, you can't reliably optimize 1 million instructions that you patch and patch as you write it.

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

Cross origin requests are only supported for HTTP but it's not cross-domain

I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.

  1. Install express npm install express

  2. Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

  3. Put something like the following in the server.js file and read about this on the express gihub site:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. After you've saved server.js, you can run the server using:

node server.js

  1. Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

When creating your own library, you can can create *.d.ts files by using the tsc (TypeScript Compiler) command like so: (assuming you're building your library to the dist/lib folder)

tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly
  • -d (--declaration): generates the *.d.ts files
  • --declarationDir dist/lib: Output directory for generated declaration files.
  • --declarationMap: Generates a sourcemap for each corresponding ‘.d.ts’ file.
  • --emitDeclarationOnly: Only emit ‘.d.ts’ declaration files. (no compiled JS)

(see the docs for all command line compiler options)

Or for instance in your package.json:

"scripts": {
    "build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}

and then run: yarn build:types (or npm run build:types)

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

How to delete an element from a Slice in Golang

The best way to do it is to use the append function:

package main

import (
    "fmt"
)

func main() {
    x := []int{4, 5, 6, 7, 88}
    fmt.Println(x)
    x = append(x[:2], x[4:]...)//deletes 6 and 7
    fmt.Println(x)
}

https://play.golang.org/p/-EEFCsqse4u

A button to start php script, how?

Having 2 files like you suggested would be the easiest solution.

For instance:

2 files solution:

index.html

(.. your html ..)
<form action="script.php" method="get">
  <input type="submit" value="Run me now!">
</form>
(...)

script.php

<?php
  echo "Hello world!"; // Your code here
?>

Single file solution:

index.php

<?php
  if (!empty($_GET['act'])) {
    echo "Hello world!"; //Your code here
  } else {
?>
(.. your html ..)
<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Run me now!">
</form>
<?php
  }
?>

What is the difference between require and require-dev sections in composer.json?

General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.

Packages in require-dev section are packages which help you debug app, run tests etc.

At staging and production environment you probably want only packages from require section.

But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.

Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :

  1. speed
  2. potential of expose some debuging info
  3. etc

Some good candidates for require-dev are :

"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"

you can see what above packages are doing and you will see why you don't need them on production.

See more here : https://getcomposer.org/doc/04-schema.md

How can I declare a global variable in Angular 2 / Typescript?

I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.

First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}

export let globalVariables: Object = {
 version: '1.3.3.7',
 author: '0x1ad2',
 everything: 42
};

After that import it

import {globalVariables} from "path/to/your/globals.ts"

And use it

console.log(globalVariables);

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you consider using fastjson, you can solve your problem, note the version

 <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.56</version>
 </dependency>

How can I transform string to UTF-8 in C#?

string utf8String = "Acción";
string propEncodeString = string.Empty;

byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
   utf8_Bytes[i] = (byte)utf8String[i];
}

propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);

Output should look like

Acción

day’s displays day's

call DecodeFromUtf8();

private static void DecodeFromUtf8()
{
    string utf8_String = "day’s";
    byte[] bytes = Encoding.Default.GetBytes(utf8_String);
    utf8_String = Encoding.UTF8.GetString(bytes);
}

Convert Variable Name to String?

By using the the unpacking operator:

>>> def tostr(**kwargs):
    return kwargs

>>> var = {}
>>> something_else = 3
>>> tostr(var = var,something_else=something_else)
{'var' = {},'something_else'=3}

How to use color picker (eye dropper)?

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

Rendering HTML inside textarea

I have the same problem but in reverse, and the following solution. I want to put html from a div in a textarea (so I can edit some reactions on my website; I want to have the textarea in the same location.)

To put the content of this div in a textarea I use:

_x000D_
_x000D_
var content = $('#msg500').text();_x000D_
$('#msg500').wrapInner('<textarea>' + content + '</textarea>');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="msg500">here some <strong>html</strong> <i>tags</i>.</div>
_x000D_
_x000D_
_x000D_

Sending mass email using PHP

I already did it using Lotus Notus and PHP.

This solution works if you have access to the mail server or you can request something to the mail server Administrator:

1) Create a group in the mail server: Sales Department

2) Assign to the group the accounts you need to be in the group

3) Assign an internet address to the group: [email protected]

4) Create your PHP script using the mail function:

$to = "[email protected]";
mail($to, $subject, $message, $headers);



It worked for me and all the accounts included in the group receive the mail.

The best of the lucks.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If I had to guess, I'd say you installed the PPA 7.1.8 as CLI only (php7-cli). You're getting your version info from that, but your libapache2-mod-php package is still 14.04 main which is 5.6. Check your phpinfo in your browser to confirm the version. You might also consider migrating to Ubuntu 16.04 to get PHP 7.0 in main.

Could not load the Tomcat server configuration

You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

  • Close Eclipse
  • Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config
  • Start Eclipse
  • Expand the Servers project, click on the Tomcat 7 project and hit F5
  • Start Tomcat from Eclipse

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

SELECT datetime(CURRENT_TIMESTAMP, 'localtime')

Convert bytes to bits in python

The other answers here provide the bits in big-endian order ('\x01' becomes '00000001')

In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:

def bits_little_endian_from_bytes(s):
    return ''.join(bin(ord(x))[2:].rjust(8,'0')[::-1] for x in s)

And for the other direction:

def bytes_from_bits_little_endian(s):
    return ''.join(chr(int(s[i:i+8][::-1], 2)) for i in range(0, len(s), 8))

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

The ideal scenario is to have <add value="default.aspx" /> in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.

We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:

<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <remove value="default.aspx" />
        <add value="default.aspx" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>

Works OK for us.

How to detect if CMD is running as Administrator/has elevated privileges?

Here's a simple method I've used on Windows 7 through Windows 10. Basically, I simply use the "IF EXIST" command to check for the Windows\System32\WDI\LogFiles folder. The WDI folder exists on every install of Windows from at least 7 onward, and it requires admin privileges to access. The WDI folder always has a LogFiles folder inside it. So, running "IF EXIST" on the WDI\LogFiles folder will return true if run as admin, and false if not run as admin. This can be used in a batch file to check privilege level, and branch to whichever commands you desire based on that result.

Here's a brief snippet of example code:

IF EXIST %SYSTEMROOT%\SYSTEM32\WDI\LOGFILES GOTO GOTADMIN
(Commands for running with normal privileges)

:GOTADMIN
(Commands for running with admin privileges)

Keep in mind that this method assumes the default security permissions have not been modified on the WDI folder (which is unlikely to happen in most situations, but please see caveat #2 below). Even in that case, it's simply a matter of modifying the code to check for a different common file/folder that requires admin access (System32\config\SAM may be a good alternate candidate), or you could even create your own specifically for that purpose.

There are two caveats about this method though:

  1. Disabling UAC will likely break it through the simple fact that everything would be run as admin anyway.

  2. Attempting to open the WDI folder in Windows Explorer and then clicking "Continue" when prompted will add permanent access rights for that user account, thus breaking my method. If this happens, it can be fixed by removing the user account from the WDI folder security permissions. If for any reason the user MUST be able to access the WDI folder with Windows Explorer, then you'd have to modify the code to check a different folder (as mentioned above, creating your own specifically for this purpose may be a good choice).

So, admittedly my method isn't perfect since it can be broken, but it's a relatively quick method that's easy to implement, is equally compatible with all versions of Windows 7, 8 and 10, and provided I stay mindful of the mentioned caveats has been 100% effective for me.

Convert XLS to CSV on command line

Why not write your own?

I see from your profile you have at least some C#/.NET experience. I'd create a Windows console application and use a free Excel reader to read in your Excel file(s). I've used Excel Data Reader available from CodePlex without any problem (one nice thing: this reader doesn't require Excel to be installed). You can call your console application from the command line.

If you find yourself stuck post here and I'm sure you'll get help.

Charts for Android

To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:

Open Source:

Paid:

** - means I didn't try those so I can't really recommend it but other users suggested it..

Disable activity slide-in animation when launching new activity?

This works for me when disabling finish Activity animation.

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

Live Video Streaming with PHP

Same problem/answer here, quoted below

I'm assuming you mean that you want to run your own private video calls, not simply link to Skype calls or similar. You really have 2 options here: host it yourself, or use a hosted solution and integrate it into your product.


Self-Hosted ----------------- This is messy. This can all be accomplished with PHP, but that is probably not the most advisable solution, as it is not the best tool for the job on all sides. Flash is much more efficient at a/v capture and transport on the user end. You can try to do this without flash, but you will have headaches. HTML5 may make your life easier, but if you're shooting for maximum compatibility, flash is the simplest way to go for creating the client. Then, as far as the actual server side that will relay the audio/video, you could write a chat server in php, but you're better off using an open source project, like janenz00's mention of red5, that's already built and interfacing with it through your client (if it doesn't already have one). Or you could homebrew a flash client as mentioned before and hook it up to a flash streaming server on both sides...either way it gets complicated fast, and is beyond my expertise to help you with at all.


Hosted Service ----------------- All in, my recommendation, unless you want to administer a ridiculous setup of many complex servers and failure points is to use a hosted service like UserPlane or similar and offload all the processing and technical work to people who are good at that, and then worry about interfacing with their api and getting their client well integrated into your site. You will be a happier developer if you do.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Browser detection in JavaScript?

Not exactly what you want, but close to it:

var jscriptVersion = /*@cc_on @if(@_jscript) @_jscript_version @else @*/ false /*@end @*/;
var geckoVersion = navigator.product === 'Gecko' && navigator.productSub;
var operaVersion = 'opera' in window && 'version' in opera && opera.version();

The variables will contain the appropriate version or false if it is not available.

I'd appreciate it if someone using Chrome could find out if you can use window.chrome in a similar way to window.opera.

How do I move an existing Git submodule within a Git repository?

[Update: 2014-11-26] As Yar summarizes nicely below, before you do anything, make sure you know the URL of the submodule. If unknown, open .git/.gitmodules and examine the keysubmodule.<name>.url.

What worked for me was to remove the old submodule using git submodule deinit <submodule> followed by git rm <submodule-folder>. Then add the submodule again with the new folder name and commit. Checking git status before committing shows the old submodule renamed to the new name and .gitmodule modified.

$ git submodule deinit foo
$ git rm foo
$ git submodule add https://bar.com/foo.git new-foo
$ git status
renamed:    foo -> new-foo
modified:   .gitmodules
$ git commit -am "rename foo submodule to new-foo"

How do I create a self-signed certificate for code signing on Windows?

It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.

1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My

2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText

3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword

Your certificate selfsigncert.pfx will be located @ D:/


Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"

How to hide soft keyboard on android after clicking outside EditText?

I modified the answer @navneeth-g a bit, adding null activity focus processing, avoiding multiple instance creation OnTouchListener, remove focus when keyboard is hiding, and removed hiding the keyboard when the screen scrolls, convenient on small devices.

//In general, the view parameter is root layout
fun Activity.hideKeyboardOnClickOutsideEditText(view: View) {
    // Set up touch listener for non-text box views to hide keyboard.
    var previousAction = 0
    val onTouchListener = View.OnTouchListener { v, event ->
        if (currentFocus != null
            && event.action != MotionEvent.ACTION_DOWN
            && event.action != MotionEvent.ACTION_MOVE
            && previousAction != MotionEvent.ACTION_MOVE
        ) {
            currentFocus?.clearFocus()
            v?.hideKeyboard()
        }
        previousAction = event.action
        false
    }

    if (view !is EditText) {
        view.setOnTouchListener(onTouchListener)
    }

    //If a layout container, iterate over children and seed recursion.
    if (view is ViewGroup) {
        for (i in 0 until view.childCount) {
            val innerView = view.getChildAt(i)
            hideKeyboardOnClickOutsideEditText(innerView)
        }
    }
}
   
//in root layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

Undoing a 'git push'

git revert is less dangerous than some of the approaches suggested here:

prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
 4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>

Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.

how to destroy bootstrap modal window completely?

Also works on bootstrap 4.x

$('#modal_ID').modal( 'hide' ).data( 'bs.modal', null );

Node.js + Nginx - What now?

I made a repository in Github which you can clone, vagrant-node-nginx-boilerplate

basically the node.js app at /var/www/nodeapp is

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(4570, '127.0.0.1');

console.log('Node Server running at 127.0.0.1:4570/');

and the nginx config at /etc/nginx/sites-available/ is

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/nodeapp;
        index index.html index.htm;

        server_name localhost;

        location / {
          proxy_pass http://127.0.0.1:4570;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_cache_bypass $http_upgrade;
        }
}

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.

  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
  <script>
    $("#contactForm").validate({
      submitHandler: function (form) {
        var response = grecaptcha.getResponse();
        //recaptcha failed validation
        if (response.length == 0) {
          $('#recaptcha-error').show();
          return false;
        }
          //recaptcha passed validation
        else {
          $('#recaptcha-error').hide();
          return true;
        }
      }
    });
  </script>

Adding a leading zero to some values in column in MySQL

Change the field back to numeric and use ZEROFILL to keep the zeros

or

use LPAD()

SELECT LPAD('1234567', 8, '0');

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is difference between sleep() method and yield() method of multi threading?

Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.

Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.

Both are static menthod.

PHP - iterate on string characters

You can also just access $s1 like an array, if you only need to access it:

$s1 = "hello world";
echo $s1[0]; // -> h

PHP Change Array Keys

I think that he want:

$a = array(1=>'first_name', 2=>'last_name');
$a = array_flip($a);

$a['first_name'] = 3;
$a = array_flip($a);

print_r($a);

Hibernate Delete query

instead of using

session.delete(object)

use

getHibernateTemplate().delete(object)

In both place for select query and also for delete use getHibernateTemplate()

In select query you have to use DetachedCriteria or Criteria

Example for select query

List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);

In hibernate avoid use of session,here I am not sure but problem occurs just because of session use

Height of an HTML select box (dropdown)

The Chi Row answer is a good option for the problem, but I've found an error i the onclick arguments. Instead, would be:

<select size="1" position="absolute" onclick="size=(size!=1)?1:n;" ...>

(And mention you must replace the "n" with the number of lines you need)

How to change icon on Google map marker

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'your-icon.png'
});

Python and SQLite: insert into table

Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:

def sqlite_insert(conn, table, row):
    cols = ', '.join('"{}"'.format(col) for col in row.keys())
    vals = ', '.join(':{}'.format(col) for col in row.keys())
    sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
    conn.cursor().execute(sql, row)
    conn.commit()

Example of use:

sqlite_insert(conn, 'stocks', {
        'created_at': '2016-04-17',
        'type': 'BUY',
        'amount': 500,
        'price': 45.00})

Note, that table name and column names should be validated beforehand.

Maven Unable to locate the Javac Compiler in:

For others facing this issue in Eclipse even with path set to JDK correctly, you need to remove the other JREs from Installed JREs.

Go to Window -> Preferences -> Java -> Installed JREs

Select unused JREs individually and Remove

It worked for me.

Make the console wait for a user input to close

public static void main(String args[])
{
    Scanner s = new Scanner(System.in);

    System.out.println("Press enter to continue.....");

    s.nextLine();   
}

This nextline is a pretty good option as it will help us run next line whenever the enter key is pressed.

C++ pass an array by reference

If you want to modify just the elements:

void foo(double *bar);

is enough.

If you want to modify the address to (e.g.: realloc), but it doesn't work for arrays:

void foo(double *&bar);

is the correct form.

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

matplotlib does not show my drawings although I call pyplot.show()

%matplotlib inline

For me working with notebook, adding the above line before the plot works.

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

How to send json data in the Http request using NSURLRequest

Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

The receivedData is then handled by:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

X-Frame-Options on apache

  1. You can add to .htaccess, httpd.conf or VirtualHost section
  2. Header set X-Frame-Options SAMEORIGIN this is the best option

Allow from URI is not supported by all browsers. Reference: X-Frame-Options on MDN

How do I check for a network connection?

Call this method to check the network Connection.

public static bool IsConnectedToInternet()
        {
            bool returnValue = false;
            try
            {

                int Desc;
                returnValue = Utility.InternetGetConnectedState(out Desc, 0);
            }
            catch
            {
                returnValue = false;
            }
            return returnValue;
        }

Put this below line of code.

[DllImport("wininet.dll")]
        public extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

Get a worksheet name using Excel VBA

Extend Code for Show Selected Sheet(s) [ one or more sheets].

Sub Show_SelectSheet()
  For Each xSheet In ThisWorkbook.Worksheets
     For Each xSelectSheet In ActiveWindow.SelectedSheets
         If xSheet.Name = xSelectSheet.Name Then
            '=== Show Selected Sheet ===
            GoTo xNext_SelectSheet
         End If
     Next xSelectSheet
  xSheet.Visible = False  
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub

How to redirect to logon page when session State time out is completed in asp.net mvc

One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.

But this is very hectic method To over come this you need to create your own ActionFilterAttribute which will do this, you just need to add this attribute in every action method.

Here is the Class which overrides ActionFilterAttribute.

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer();
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }

Then in action just add this attribute like so:

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

This will do you work.

How do I create a simple 'Hello World' module in Magento?

And,

I suggest you to learn about system configuration.

How to Show All Categories on System Configuration Field?

Here I solved with a good example. It working. You can check and learn the flow of code.

There are other too many examples also that you should learn.

Generate random numbers following a normal distribution in C/C++

A quick and easy method is just to sum a number of evenly distributed random numbers and take their average. See the Central Limit Theorem for a full explanation of why this works.

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

Symfony2 : How to get form validation errors after binding the request to the form

SYMFONY 3.1

I simply implemented a static method to handle the display of errors

static function serializeFormErrors(Form\Form $form)
{
    $errors = array();
    /**
     * @var  $key
     * @var Form\Form $child
     */
    foreach ($form->all() as $key => $child) {
        if (!$child->isValid()) {
            foreach ($child->getErrors() as $error) {
                $errors[$key] = $error->getMessage();
            }
        }
    }

    return $errors;
}

Hoping to help

Cannot read configuration file due to insufficient permissions

When you grant permissions to IIS_IUSRS you should check that in the IIS/Authentication section of your Web Application, the Anonymous Authentication Credentials uses Application Pool Identity and not IUSR.

enter image description here

Changing text color of menu item in navigation drawer

You can also define a custom theme that is derived from your base theme:

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_view_header"
        app:menu="@layout/nav_view_menu"
        app:theme="@style/MyTheme.NavMenu" />

and then in your styles.xml file:

  <style name="MyTheme.NavMenu" parent="MyTheme.Base">
    <item name="android:textColorPrimary">@color/yourcolor</item>
  </style>

you can also apply more attributes to the custom theme.

Virtualenv Command Not Found

The simplest answer. Just:

pip uninstall virtualenv

and then:

pip install virtualenv

Or you maybe installed virtualenv with sudo, in that case:

pip install --user virtualenv

What are the lesser known but useful data structures?

I personally find sparse matrix data structures to be very interesting. http://www.netlib.org/linalg/html_templates/node90.html

The famous BLAS libraries use these. And when you deal with linear systems that contain 100,000's of rows and columns, it becomes critical to use these. Some of these also resemble the compact grid (basically like a bucket-sorted grid) which is common in computer graphics. http://www.cs.kuleuven.be/~ares/publications/LD08CFRGRT/LD08CFRGRT.pdf

Also as far as computer graphics is concerned, MAC grids are somewhat interesting, but only because they're clever. http://www.seas.upenn.edu/~cis665/projects/Liquation_665_Report.pdf

Android Studio and Gradle build error

The only solution I've found is to first create the project in Android Studio, then close the project, then import the project. I searched all over and could not find the root cause and all other solutions people posted didn't work.

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

How can I select an element in a component template?

to get the immediate next sibling ,use this

event.source._elementRef.nativeElement.nextElementSibling

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Make sure that you are building your web app as "Any CPU". Right click your web project --> Properties --> Build --> and look for the "Platform Target". Choose "Any CPU" or play around with it.

Hope this helps!

How to make a vertical SeekBar in Android?

You can do it by yourself - it's now so difficult. Here is an example from my project: https://github.com/AlShevelev/WizardCamera

Let start from settings (attrs.xml).

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpositionBar">
        <attr name="button_icon" format="reference" />
        <attr name="button_icon_size" format="dimension" />

        <attr name="stroke_width" format="dimension" />

        <attr name="stroke_color" format="color" />
        <attr name="button_color" format="color" />
        <attr name="button_color_pressed" format="color" />

        <attr name="min_value" format="float" />
        <attr name="max_value" format="float" />
    </declare-styleable>
</resources>

Here is a couple of utility functions:

fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
    when {
        this < range.lower -> range.lower
        this > range.upper -> range.upper
        else -> this
    }

fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
    when {
        this == rangeFrom.lower -> rangeTo.lower
        this == rangeFrom.upper -> rangeTo.upper
        else -> {
            val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
            ((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
        }
    }

And at last, but not least - a class for vertical seek bar:

class ExpositionBar
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val drawingRect = RectF(0f, 0f, 0f, 0f)
    private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val strokeWidth: Float

    @ColorInt
    private val strokeColor: Int
    @ColorInt
    private val buttonFillColor: Int
    @ColorInt
    private val buttonFillColorPressed: Int

    private val icon: VectorDrawable

    private val valuesRange: Range<Float>

    private var centerX = 0f
    private var minY = 0f
    private var maxY = 0f

    private var buttonCenterY = 0f
    private var buttonRadiusExt = 0f
    private var buttonRadiusInt = 0f
    private var buttonMinY = 0f
    private var buttonMaxY = 0f
    private var buttonCenterBoundsRange = Range(0f, 0f)

    private var iconTranslationX = 0f
    private var iconTranslationY = 0f

    private var isInDragMode = false

    private var onValueChangeListener: ((Float) -> Unit)? = null

    private var oldOutputValue = Float.MIN_VALUE

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)

        icon =  typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
        val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
        icon.setBounds(0, 0, iconSize, iconSize)

        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
        drawingPaint.strokeWidth = strokeWidth

        strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
        buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
        buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)

        val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
        val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
        valuesRange = Range(minValue, maxValue)

        typedArray.recycle()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        drawingRect.right = width.toFloat()
        drawingRect.bottom = height.toFloat()

        buttonCenterY = drawingRect.centerY()

        recalculateDrawingValues()
    }

    override fun onDraw(canvas: Canvas) {
        drawingPaint.color = strokeColor
        drawingPaint.style = Paint.Style.STROKE

        // Draw the center line
        canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
        canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)

        // Draw the button
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
        drawingPaint.style = Paint.Style.FILL
        drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)

        // Draw button icon
        canvas.translate(iconTranslationX, iconTranslationY)
        icon.draw(canvas)
        canvas.translate(-iconTranslationX, -iconTranslationY)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if(!isEnabled) {
            return false
        }

        when(event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if(isButtonHit(event.y)){
                    isInDragMode = true
                    invalidate()
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if(isInDragMode) {
                    buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
                    recalculateDrawingValues()
                    invalidate()

                    val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
                    if (outputValue != oldOutputValue) {
                        onValueChangeListener?.invoke(outputValue)
                        oldOutputValue = outputValue
                    }
                }
            }
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL -> {
                isInDragMode = false
                invalidate()
            }
        }
        return true
    }

    fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
        onValueChangeListener = listener
    }

    private fun recalculateDrawingValues() {
        centerX = drawingRect.left + drawingRect.width()/2
        minY = drawingRect.top
        maxY = drawingRect.bottom

        buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
        buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
        buttonMinY = buttonCenterY - buttonRadiusExt
        buttonMaxY = buttonCenterY + buttonRadiusExt

        val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
        val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
        buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)

        iconTranslationX = centerX - icon.bounds.width() / 2
        iconTranslationY = buttonCenterY - icon.bounds.height() / 2
    }

    private fun isButtonHit(y: Float): Boolean {
        return y >= buttonMinY && y <= buttonMaxY
    }
}

You can use it as shown here:

<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
    android:id="@+id/expositionBar"
    android:layout_width="@dimen/mainButtonSize"
    android:layout_height="300dp"
    android:layout_gravity="end|center_vertical"

    android:layout_marginEnd="@dimen/marginNormal"
    android:layout_marginBottom="26dp"

    app:button_icon = "@drawable/ic_brightness"
    app:button_icon_size = "@dimen/toolButtonIconSize"
    app:stroke_width = "@dimen/strokeWidthNormal"
    app:stroke_color = "@color/mainButtonsForeground"
    app:button_color = "@color/mainButtonsBackground"
    app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
    app:min_value="-100"
    app:max_value="100"
/>

Voila!

How to run Pip commands from CMD

Newer versions of Python come with py, the Python Launcher, which is always in the PATH.

Here is how to invoke pip via py:

py -m pip install <packagename>

py allows having several versions of Python on the same machine.

As an example, here is how to invoke the pip from Python 2.7:

py -2.7 -m pip install <packagename>