Programs & Examples On #Vmware tools

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms

The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.

The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.

The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.

How to add a JAR in NetBeans

You want to add libraries to your project and in doing so you have two options as you yourself identified:

Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.

This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).

Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.

As for the other alernatives you have either global libraries using Library Manageror jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager.

How is the AND/OR operator represented as in Regular Expressions?

'^(part1|part2|part1,part2)$'

does it work?

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

Run Function After Delay

You can simply use jQuery’s delay() method to set the delay time interval.

HTML code:

  <div class="box"></div>

JQuery code:

  $(document).ready(function(){ 
    $(".show-box").click(function(){
      $(this).text('loading...').delay(1000).queue(function() {
        $(this).hide();
        showBox(); 
        $(this).dequeue();
      });        
    });
  });

You can see an example here: How to Call a Function After Some Time in jQuery

Bootstrap fullscreen layout with 100% height

If there is no vertical scrolling then you can use position:absolute and height:100% declared on html and body elements.

Another option is to use viewport height units, see Make div 100% height of browser window

Absolute position Example:

_x000D_
_x000D_
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
  height:50%;_x000D_
  background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
  height:100vh;_x000D_
  }_x000D_
.col-50vh {_x000D_
  height:50vh;_x000D_
  }_x000D_
#mmenu_screen--information{_x000D_
  background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
   background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
  background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
    <div class="row col-100vh">_x000D_
        <div class="col-xs-6 col-100vh">_x000D_
            _x000D_
                <div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
                    BOOKING BUTTON_x000D_
                </div>_x000D_
           _x000D_
                <div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
                    INFO BUTTON_x000D_
                </div>_x000D_
            _x000D_
        </div>_x000D_
        <div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
           DIRECT ACTION BUTTON_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

What is the difference between HTML tags <div> and <span>?

The significance of "block element" is implied but never stated explicitly. If we ignore all the theory (theory is good) then the following is a pragmatic comparison. The following:

<p>This paragraph <span>has</span> a span.</p>
<p>This paragraph <div>has</div> a div.</p>

produces:

This paragraph has a span.

This paragraph

has
a div.

That shows that not only should a div not be used inline, it simply won't produce the desired affect.

Java Date vs Calendar

  • Date and Calendar are really the same fundamental concept (both represent an instant in time and are wrappers around an underlying long value).

  • One could argue that Calendar is actually even more broken than Date is, as it seems to offer concrete facts about things like day of the week and time of day, whereas if you change its timeZone property, the concrete turns into blancmange! Neither objects are really useful as a store of year-month-day or time-of-day for this reason.

  • Use Calendar only as a calculator which, when given Date and TimeZone objects, will do calculations for you. Avoid its use for property typing in an application.

  • Use SimpleDateFormat together with TimeZone and Date to generate display Strings.

  • If you're feeling adventurous use Joda-Time, although it is unnecessarily complicated IMHO and is soon to be superceded by the JSR-310 date API in any event.

  • I have answered before that it is not difficult to roll your own YearMonthDay class, which uses Calendar under the hood for date calculations. I was downvoted for the suggestion but I still believe it is a valid one because Joda-Time (and JSR-310) are really so over-complicated for most use-cases.

How do I run a terminal inside of Vim?

This question is rather old, but for those finding it, there's a new possible solution: Neovim contains a full-fledged, first-class terminal emulator, which does exactly what ConqueTerm tried to. Simply run :term <your command here>.

<C-\><C-n> will exit term mode back to normal-mode. If you're like me and prefer that escape still exit term mode, you can add this to your nvimrc:

tnoremap <ESC><ESC> <C-\><C-N>

And then hitting ESC twice will exit terminal mode back to normal-mode, so you can manipulate the buffer that the still-running command is writing to.

Though keep in mind, as nvim is under heavy development at the time I'm posting this answer, another way to exit terminal mode may be added. As Ctrl+\Ctrl+n switches to normal mode from almost any mode, I don't expect that this answer will become wrong, but be aware that if it doesn't work, this answer might be out of date.

https://github.com/neovim/neovim

Python DNS module import error

I faced the same problem and solved this like i described below: As You have downloaded and installed dnspython successfully so

  1. Enter into folder dnspython
  2. You will find dns directory, now copy it
  3. Then paste it to inside site-packages directory

That's all. Now your problem will go

If dnspython isn't installed you can install it this way :

  1. go to your python installation folder site-packages directory
  2. open cmd here and enter the command : pip install dnspython

Now, dnspython will be installed successfully.

"Cross origin requests are only supported for HTTP." error when loading a local file

If you use Mozilla Firefox, It will work as expected without any issues;

P.S. Surprisingly, IntenetExplorer_Edge works absolutely fine!!!

Selecting last element in JavaScript array

In case you are using ES6 you can do:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

How to plot two columns of a pandas data frame using points?

Pandas uses matplotlib as a library for basic plots. The easiest way in your case will using the following:

import pandas as pd
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')

enter image description here

However, I would recommend to use seaborn as an alternative solution if you want have more customized plots while not going into the basic level of matplotlib. In this case you the solution will be following:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)

enter image description here

Nested lists python

I think you want to access list values and their indices simultaneously and separately:

l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
    for j in range(l_item_len):
        print(f'List[{i}][{j}] : {l[i][j]}'  )

In MS DOS copying several files to one file

If this is part of a batch script (.bat file) and you have a large list of files, you can use a multi-line ^, and optional /Y flag to suppresses prompting to confirm you want to overwrite an existing destination file.

REM Concatenate several files to one
COPY /Y ^
    this_is_file_1.csv + ^
    this_is_file_2.csv + ^
    this_is_file_3.csv + ^
    this_is_file_4.csv + ^
    this_is_file_5.csv + ^
    this_is_file_6.csv + ^
    this_is_file_7.csv + ^
    this_is_file_8.csv + ^
    this_is_file_9.csv ^
        output_file.csv

This is tidier than performing the command on one line.

Can I change the checkbox size using CSS?

My reputation is slightly too low to post comments, but I made a modification to Jack Miller's code above in order to get it to not change size when you check and uncheck it. This was causing text alignment problems for me.

_x000D_
_x000D_
    input[type=checkbox] {
        width: 17px;
        -webkit-appearance: none;
        -moz-appearance: none;
        height: 17px;
        border: 1px solid black;
    }

    input[type=checkbox]:checked {
        background-color: #F58027;
    }

    input[type=checkbox]:checked:after {
        margin-left: 4px;
        margin-top: -1px;
        width: 4px;
        height: 12px;
        border: solid white;
        border-width: 0 2px 2px 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        content: "";
        display: inline-block;
    }
    input[type=checkbox]:after {
        margin-left: 4px;
        margin-top: -1px;
        width: 4px;
        height: 12px;
        border: solid white;
        border-width: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        content: "";
        display: inline-block;
    }
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
_x000D_
_x000D_

jquery find class and get the value

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

Can I restore a single table from a full mysql mysqldump file?

You can use vi editor. Type:

vi -o mysql.dump mytable.dump

to open both whole dump mysql.dump and a new file mytable.dump. Find the appropriate insert into line by pressing / and then type a phrase, for example: "insert into `mytable`", then copy that line using yy. Switch to next file by ctrl+w then down arrow key, paste the copied line with pp. Finally save the new file by typing :wq and quite vi editor by :q.

Note that if you have dumped the data using multiple inserts you can copy (yank) all of them at once using Nyy in which N is the number of lines to be copied.

I have done it with a file of 920 MB size.

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

Reversing a String with Recursion in Java

The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"

Serving static web resources in Spring Boot & Spring Security application

There are a couple of things to be aware of:

  • The Ant matchers match against the request path and not the path of the resource on the filesystem.
  • Resources placed in src/main/resources/public will be served from the root of your application. For example src/main/resources/public/hello.jpg would be served from http://localhost:8080/hello.jpg

This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/** to work, you would have to place the resources in src/main/resources/public/resources and access them at http://localhost:8080/resources/your-resource.

As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**, /js/**, /images/**, and /**/favicon.ico. You could, for example, have a file named src/main/resources/public/images/hello.jpg and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.

Store List to session

I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:

HttpContext.Current.Session.Add("currentUser", appUser);

and

(AppUser) HttpContext.Current.Session["currentUser"]

Otherwise the compiler was expecting a string when I pointed the object at the session object.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Try using chown -R on the var/lib/gems directory, assigning ownership to the user [rubyusername] in this example, the user that will be installing and developing with gems.

 # chown -R rubyusername:rubyusername /var/lib/gems 

This recursively changes everything under the gems directory. For extra security on multi-user systems, you can also create a group, rather than chowning the individual rubyusername, and add users to that group.

How to use BOOLEAN type in SELECT statement

select get_something('NAME', sys.diutil.int_to_bool(1)) from dual;

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

Sticky Header after scrolling down

window bottom scroll to top scroll using jquery.

 <script> 

 var lastScroll = 0;

 $(document).ready(function($) {

 $(window).scroll(function(){

 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {

        $("header").removeClass("menu-sticky");

    } 
    if (scroll == 0) {
    $("header").removeClass("menu-sticky");

    }
    else if (scroll < lastScroll - 5) {


        $("header").addClass("menu-sticky");

    }
    lastScroll = scroll;
    },0);
    });
   });
 </script>

How to remove all debug logging calls before building the release version of an Android app?

Easy with kotlin, just declare a few top level functions

val isDebug: Boolean
    get() = BuildConfig.DEBUG

fun logE(tag: String, message: String) {
    if (isDebug) Log.e(tag, message)
}

fun logD(tag: String, message: String) {
    if (isDebug) Log.d(tag, message)
}

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

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

Error in launching AVD with AMD processor

First, you must enable Intel virtualization technology from the BIOS:

Enter image description here

Second, navigate to your SDK ...\extras\intel\Hardware_Accelerated_Execution_Manager:

Enter image description here

Then install intelhaxm-android.exe.

Note that if you can't find this file in the directory, make sure you install the package from your SDK manager:

Enter image description here

text-align: right; not working for <label>

As stated in other answers, label is an inline element. However, you can apply display: inline-block to the label and then center with text-align.

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;
}

Why display: inline-block and not display: inline? For the same reason that you can't align label, it's inline.

Why display: inline-block and not display: block? You could use display: block, but it will be on another line. display: inline-block combines the properties of inline and block. It's inline, but you can also give it a width, height, and align it.

Storing an object in state of a React component?

Easier way to do it in one line of code

this.setState({ object: { ...this.state.object, objectVarToChange: newData } })

Convert a python dict to a string and back

I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.

Write

from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)

Read back

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

Vertically align text next to an image?

On a button in jQuery mobile, for instance, you can tweak it a bit by applying this style to the image:

.btn-image {
    vertical-align:middle;
    margin:0 0 3px 0;
}

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here's the real answer.

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

Create Directory if it doesn't exist with Ruby

Another simple way:

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

What are the differences between Abstract Factory and Factory design patterns?

Abstract factory creates a base class with abstract methods defining methods for the objects that should be created. Each factory class which derives the base class can create their own implementation of each object type.

enter image description here

Factory method is just a simple method used to create objects in a class. It's usually added in the aggregate root (The Order class has a method called CreateOrderLine)

enter image description here

Abstract factory

In the example below we design an interface so that we can decouple queue creation from a messaging system and can therefore create implementations for different queue systems without having to change the code base.

interface IMessageQueueFactory
{
  IMessageQueue CreateOutboundQueue(string name);
  IMessageQueue CreateReplyQueue(string name);
}

public class AzureServiceBusQueueFactory : IMessageQueueFactory
{
      IMessageQueue CreateOutboundQueue(string name)
      {
           //init queue
           return new AzureMessageQueue(/*....*/);
      }

      IMessageQueue CreateReplyQueue(string name)
      {
           //init response queue
           return new AzureResponseMessageQueue(/*....*/);
      }

}

public class MsmqFactory : IMessageQueueFactory
{
      IMessageQueue CreateOutboundQueue(string name)
      {
           //init queue
           return new MsmqMessageQueue(/*....*/);
      }

      IMessageQueue CreateReplyQueue(string name)
      {
           //init response queue
           return new MsmqResponseMessageQueue(/*....*/);
      }
}

Factory method

The problem in HTTP servers is that we always need an response for every request.

public interface IHttpRequest
{
    // .. all other methods ..

    IHttpResponse CreateResponse(int httpStatusCode);
}

Without the factory method, the HTTP server users (i.e. programmers) would be forced to use implementation specific classes which defeat the purpose of the IHttpRequest interface.

Therefore we introduce the factory method so that the creation of the response class also is abstracted away.

Summary

The difference is that the intended purpose of the class containing a factory method is not to create objects, while an abstract factory should only be used to create objects.

One should take care when using factory methods since it's easy to break the LSP (Liskov Substitution principle) when creating objects.

Programmatically check Play Store for app updates

You can get current Playstore Version using JSoup with some modification like below:

@Override
protected String doInBackground(Void... voids) {

    String newVersion = null;
    try {
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select(".hAyfc .htlgb")
                .get(7)
                .ownText();
        return newVersion;
    } catch (Exception e) {
        return newVersion;
    }
}

@Override
protected void onPostExecute(String onlineVersion) {
    super.onPostExecute(onlineVersion);

    Log.d("update", "playstore version " + onlineVersion);
}

answer of @Tarun is not working anymore.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Android ListView with onClick items

listview.setOnItemClickListener(new OnItemClickListener(){

//setting onclick to items in the listview.

@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){

// case 0 is the first item in the listView.

  case 0:
    intent = new Intent(Activity.this,firstActivity.class);
    break;
//case 1 is the second item in the listView.

  case 1:
    intent = new Intent(Activity.this,secondActivity.class);
    break;
 case 2:
    intent = new Intent(Activity.this,thirdActivity.class);
    break;
//add more if you have more items in listView
startActivity(intent);
}

});

C++ correct way to return pointer to array from function

New answer to new question:

You cannot return pointer to automatic variable (int c[5]) from the function. Automatic variable ends its lifetime with return enclosing block (function in this case) - so you are returning pointer to not existing array.

Either make your variable dynamic:

int* test (int a[5], int b[5]) {
    int* c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

Or change your implementation to use std::array:

std::array<int,5> test (const std::array<int,5>& a, const std::array<int,5>& b) 
{
   std::array<int,5> c;
   for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
   return c;
}

In case your compiler does not provide std::array you can replace it with simple struct containing an array:

struct array_int_5 { 
   int data[5];
   int& operator [](int i) { return data[i]; } 
   int operator const [](int i) { return data[i]; } 
};

Old answer to old question:

Your code is correct, and ... hmm, well, ... useless. Since arrays can be assigned to pointers without extra function (note that you are already using this in your function):

int arr[5] = {1, 2, 3, 4, 5};
//int* pArr = test(arr);
int* pArr = arr;

Morever signature of your function:

int* test (int in[5])

Is equivalent to:

int* test (int* in)

So you see it makes no sense.

However this signature takes an array, not pointer:

int* test (int (&in)[5])

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

Fuzzy matching using T-SQL

I've found that the stuff SQL Server gives you to do fuzzy matching is pretty clunky. I've had really good luck with my own CLR functions using the Levenshtein distance algorithm and some weighting. Using that algorithm, I've then made a UDF called GetSimilarityScore that takes two strings and returns a score between 0.0 and 1.0. The closer to 1.0 the match is, the better. Then, query with a threshold of >=0.8 or so to get the most likely matches. Something like this:

if object_id('tempdb..#similar') is not null drop table #similar
select a.id, (
    select top 1 x.id
   from MyTable x
   where x.id <> a.id
   order by dbo.GetSimilarityScore(a.MyField, x.MyField) desc
) as MostSimilarId
into #similar
from MyTable a

select *, dbo.GetSimilarityScore(a.MyField, c.MyField)
from MyTable a
join #similar b on a.id = b.id
join MyTable c on b.MostSimilarId = c.id

Just don't do it with really large tables. It's a slow process.

Here's the CLR UDFs:

''' <summary>
''' Compute the distance between two strings.
''' </summary>
''' <param name="s1">The first of the two strings.</param>
''' <param name="s2">The second of the two strings.</param>
''' <returns>The Levenshtein cost.</returns>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function ComputeLevenstheinDistance(ByVal string1 As SqlString, ByVal string2 As SqlString) As SqlInt32
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null
    Dim s1 As String = string1.Value
    Dim s2 As String = string2.Value

    Dim n As Integer = s1.Length
    Dim m As Integer = s2.Length
    Dim d As Integer(,) = New Integer(n, m) {}

    ' Step 1
    If n = 0 Then Return m
    If m = 0 Then Return n

    ' Step 2
    For i As Integer = 0 To n
        d(i, 0) = i
    Next

    For j As Integer = 0 To m
        d(0, j) = j
    Next

    ' Step 3
    For i As Integer = 1 To n
        'Step 4
        For j As Integer = 1 To m
            ' Step 5
            Dim cost As Integer = If((s2(j - 1) = s1(i - 1)), 0, 1)

            ' Step 6
            d(i, j) = Math.Min(Math.Min(d(i - 1, j) + 1, d(i, j - 1) + 1), d(i - 1, j - 1) + cost)
        Next
    Next
    ' Step 7
    Return d(n, m)
End Function

''' <summary>
''' Returns a score between 0.0-1.0 indicating how closely two strings match.  1.0 is a 100%
''' T-SQL equality match, and the score goes down from there towards 0.0 for less similar strings.
''' </summary>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function GetSimilarityScore(string1 As SqlString, string2 As SqlString) As SqlDouble
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null

    Dim s1 As String = string1.Value.ToUpper().TrimEnd(" "c)
    Dim s2 As String = string2.Value.ToUpper().TrimEnd(" "c)
    If s1 = s2 Then Return 1.0F ' At this point, T-SQL would consider them the same, so I will too

    Dim flatLevScore As Double = InternalGetSimilarityScore(s1, s2)

    Dim letterS1 As String = GetLetterSimilarityString(s1)
    Dim letterS2 As String = GetLetterSimilarityString(s2)
    Dim letterScore As Double = InternalGetSimilarityScore(letterS1, letterS2)

    'Dim wordS1 As String = GetWordSimilarityString(s1)
    'Dim wordS2 As String = GetWordSimilarityString(s2)
    'Dim wordScore As Double = InternalGetSimilarityScore(wordS1, wordS2)

    If flatLevScore = 1.0F AndAlso letterScore = 1.0F Then Return 1.0F
    If flatLevScore = 0.0F AndAlso letterScore = 0.0F Then Return 0.0F

    ' Return weighted result
    Return (flatLevScore * 0.2F) + (letterScore * 0.8F)
End Function

Private Shared Function InternalGetSimilarityScore(s1 As String, s2 As String) As Double
    Dim dist As SqlInt32 = ComputeLevenstheinDistance(s1, s2)
    Dim maxLen As Integer = If(s1.Length > s2.Length, s1.Length, s2.Length)
    If maxLen = 0 Then Return 1.0F
    Return 1.0F - Convert.ToDouble(dist.Value) / Convert.ToDouble(maxLen)
End Function

''' <summary>
''' Sorts all the alpha numeric characters in the string in alphabetical order
''' and removes everything else.
''' </summary>
Private Shared Function GetLetterSimilarityString(s1 As String) As String
    Dim allChars = If(s1, "").ToUpper().ToCharArray()
    Array.Sort(allChars)
    Dim result As New StringBuilder()
    For Each ch As Char In allChars
        If Char.IsLetterOrDigit(ch) Then
            result.Append(ch)
        End If
    Next
    Return result.ToString()
End Function

''' <summary>
''' Removes all non-alpha numeric characters and then sorts
''' the words in alphabetical order.
''' </summary>
Private Shared Function GetWordSimilarityString(s1 As String) As String
    Dim words As New List(Of String)()
    Dim curWord As StringBuilder = Nothing
    For Each ch As Char In If(s1, "").ToUpper()
        If Char.IsLetterOrDigit(ch) Then
            If curWord Is Nothing Then
                curWord = New StringBuilder()
            End If
            curWord.Append(ch)
        Else
            If curWord IsNot Nothing Then
                words.Add(curWord.ToString())
                curWord = Nothing
            End If
        End If
    Next
    If curWord IsNot Nothing Then
        words.Add(curWord.ToString())
    End If

    words.Sort(StringComparer.OrdinalIgnoreCase)
    Return String.Join(" ", words.ToArray())
End Function

Loop through list with both content and index

>>> for i, s in enumerate(S):

How do I find out what keystore my JVM is using?

This works for me:

#! /bin/bash

CACERTS=$(readlink -e $(dirname $(readlink -e $(which keytool)))/../lib/security/cacerts)

if keytool -list -keystore $CACERTS -storepass changeit > /dev/null ; then
    echo $CACERTS
else
    echo 'Can not find cacerts file.' >&2
    exit 1
fi

Only for Linux. My Solaris has no readlink. In the end I used this Perl-Script:

#! /usr/bin/env perl
use strict;
use warnings;
use Cwd qw(realpath);
$_ = realpath((grep {-x && -f} map {"$_/keytool"} split(':', $ENV{PATH}))[0]);
die "Can not find keytool" unless defined $_;
my $keytool = $_;
print "Using '$keytool'.\n";
s/keytool$//;
$_ = realpath($_ . '../lib/security/cacerts');
die "Can not find cacerts" unless -f $_;
my $cacerts = $_;
print "Importing into '$cacerts'.\n";
`$keytool -list -keystore "$cacerts" -storepass changeit`;
die "Can not read key container" unless $? == 0;
exit if $ARGV[0] eq '-d';
foreach (@ARGV) {
    my $cert = $_;
    s/\.[^.]+$//;
    my $alias = $_;
    print "Importing '$cert' as '$alias'.\n";
    `keytool -importcert -file "$cert" -alias "$alias" -keystore "$cacerts" -storepass changeit`;
    warn "Can not import certificate: $?" unless $? == 0;
}

! [rejected] master -> master (fetch first)

Sometimes it happens when you duplicate files typically README sort of.

How do I copy items from list to list without foreach?

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

How to send Basic Auth with axios

Hi you can do this in the following way

var username = '';
var password = ''

const token = `${username}:${password}`;
const encodedToken = Buffer.from(token).toString('base64');
const session_url = 'http://api_address/api/session_endpoint';

var config = {
  method: 'get',
  url: session_url,
  headers: { 'Authorization': 'Basic '+ encodedToken }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

Build Maven Project Without Running Unit Tests

I like short version: mvn clean install -DskipTests

It's work too: mvn clean install -DskipTests=true

If you absolutely must, you can also use the maven.test.skip property to skip compiling the tests. maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin. mvn clean install -Dmaven.test.skip=true

and you can add config in maven.xml

<project>
      [...]
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.16</version>
            <configuration>
              <skipTests>true</skipTests>
            </configuration>
          </plugin>
        </plugins>
      </build>
      [...]
    </project>

How to get height of <div> in px dimension

Use .height() like this:

var result = $("#myDiv").height();

There's also .innerHeight() and .outerHeight() depending on exactly what you want.

You can test it here, play with the padding/margins/content to see how it changes around.

Using OpenGl with C#?

OpenTK is an improvement over the Tao API, as it uses idiomatic C# style with overloading, strongly-typed enums, exceptions, and standard .NET types:

GL.Begin(BeginMode.Points);
GL.Color3(Color.Yellow);
GL.Vertex3(Vector3.Up);

as opposed to Tao which merely mirrors the C API:

Gl.glBegin(Gl.GL_POINTS);   // double "gl" prefix
Gl.glColor3ub(255, 255, 0); // have to pass RGB values as separate args
Gl.glVertex3f(0, 1, 0);     // explicit "f" qualifier

This makes for harder porting but is incredibly nice to use.

As a bonus it provides font rendering, texture loading, input handling, audio, math...

Update 18th January 2016: Today the OpenTK maintainer has stepped away from the project, leaving its future uncertain. The forums are filled with spam. The maintainer recommends moving to MonoGame or SDL2#.

Update 30th June 2020: OpenTK has had new maintainers for a while now and has an active discord community. So the previous recommendation of using another library isn't necessarily true.

How to find the index of an element in an array in Java?

I am providing the proper method to do this one

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

Apache shutdown unexpectedly

on your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

This trick works for me.

You don't have this problem on remote server, because on remote server, the last insert command waits for the result of previous command to execute. It's not the case on same server.

Profit that situation for a workaround.

If you have the right permission to create a Linked Server, do it. Create the same server as linked server.

  • in SSMS, log into your server
  • go to "Server Object
  • Right Click on "Linked Servers", then "New Linked Server"
  • on the dialog, give any name of your linked server : eg: THISSERVER
  • server type is "Other data source"
  • Provider : Microsoft OLE DB Provider for SQL server
  • Data source: your IP, it can be also just a dot (.), because it's localhost
  • Go to the tab "Security" and choose the 3rd one "Be made using the login's current security context"
  • You can edit the server options (3rd tab) if you want
  • Press OK, your linked server is created

now your Sql command in the SP1 is

insert into @myTempTable
exec THISSERVER.MY_DATABASE_NAME.MY_SCHEMA.SP2

Believe me, it works even you have dynamic insert in SP2

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

changing textbox border colour using javascript

I'm agree with Vicente Plata you should try using jQuery IMHO is the best javascript library. You can create a class in your CSS file and just do the following with jquery:

$('#fName').addClass('name_of_the_class'); 

and that's all, and of course you won't be worried about incompatibility of the browsers, that's jquery's team problem :D LOL

How to validate a date?

Though this was raised long ago, still a most wanted validation. I found an interesting blog with few function.

/* Please use these function to check the reuslt only. do not check for otherewise. other than utiljs_isInvalidDate

Ex:-

utiljs_isFutureDate() retuns only true for future dates. false does not mean it is not future date. it may be an invalid date.

practice :

call utiljs_isInvalidDate first and then use the returned date for utiljs_isFutureDate()

var d = {};

if(!utiljs_isInvalidDate('32/02/2012', d))

if(utiljs_isFutureDate(d))

//date is a future date

else

// date is not a future date



 */

function utiljs_isInvalidDate(dateStr, returnDate) {

    /*dateStr | format should be dd/mm/yyyy, Ex:- 31/10/2017

     *returnDate will be in {date:js date object}.

     *Ex:- if you only need to check whether the date is invalid,

     * utiljs_isInvalidDate('03/03/2017')

     *Ex:- if need the date, if the date is valid,

     * var dt = {};

     * if(!utiljs_isInvalidDate('03/03/2017', dt)){

     *  //you can use dt.date

     * }

     */

    if (!dateStr)
        return true;
    if (!dateStr.substring || !dateStr.length || dateStr.length != 10)
        return true;
    var day = parseInt(dateStr.substring(0, 2), 10);
    var month = parseInt(dateStr.substring(3, 5), 10);
    var year = parseInt(dateStr.substring(6), 10);
    var fullString = dateStr.substring(0, 2) + dateStr.substring(3, 5) + dateStr.substring(6);
    if (null == fullString.match(/^\d+$/)) //to check for whether there are only numbers
        return true;
    var dt = new Date(month + "/" + day + "/" + year);
    if (dt == 'Invalid Date' || isNaN(dt)) { //if the date string is not valid, new Date will create this string instead
        return true;
    }
    if (dt.getFullYear() != year || dt.getMonth() + 1 != month || dt.getDate() != day) //to avoid 31/02/2018 like dates
        return true;
    if (returnDate)
        returnDate.date = dt;
    return false;
}

function utiljs_isFutureDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, true);
}

function utiljs_isPastDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, false);
}

function utiljs_isValidDateObjectOrDateString(dateStrOrObject, returnDate) { //this is an internal function
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (typeof dateStrOrObject.getMonth === 'function')
        dt.date = new Date(dateStrOrObject); //to avoid modifying original date
    else if (utiljs_isInvalidDate(dateStrOrObject, dt))
        return false;
    if (returnDate)
        returnDate.date = dt.date;
    return true;

}

function utiljs_isFuturePast(dateStrOrObject, returnDate, isFuture) { //this is an internal function, please use isFutureDate or isPastDate function
    if (!dateStrOrObject)
        return false;
    var dt = {};
    if (!utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt))
        return false;
    today = new Date();
    today.setHours(0, 0, 0, 0);
    if (dt.date)
        dt.date.setHours(0, 0, 0, 0);
    if (returnDate)
        returnDate.date = dt.date;
    //creating new date using only current d/m/y. as td.date is created with string. otherwise same day selection will not be validated.
    if (isFuture && dt.date && dt.date.getTime && dt.date.getTime() > today.getTime()) {
        return true;
    }
    if (!isFuture && dt.date && dt.date.getTime && dt.date.getTime() < today.getTime()) {
        return true;
    }
    return false;
}

function utiljs_isLeapYear(dateStrOrObject, returnDate) {
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt)) {
        if (returnDate)
            returnDate.date = dt.date;
        return dt.date.getFullYear() % 4 == 0;
    }
    return false;
}

function utiljs_firstDateLaterThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() > dt2.date.getTime())
        return true;
    return false;
}

function utiljs_isEqual(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() == dt2.date.getTime())
        return true;
    return false;
}

function utiljs_firstDateEarlierThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() < dt2.date.getTime())
        return true;
    return false;
}

copy the whole code into a file and include.

hope this helps.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

To understand the problem it's useful to make comparison to arrays.

List<Dog> is not subclass of List<Animal>.
But Dog[] is subclass of Animal[].

Arrays are reifiable and covariant.
Reifiable means their type information is fully available at runtime.
Therefore arrays provide runtime type safety but not compile-time type safety.

    // All compiles but throws ArrayStoreException at runtime at last line
    Dog[] dogs = new Dog[10];
    Animal[] animals = dogs; // compiles
    animals[0] = new Cat(); // throws ArrayStoreException at runtime

It's vice versa for generics:
Generics are erased and invariant.
Therefore generics can't provide runtime type safety, but they provide compile-time type safety.
In the code below if generics were covariant it will be possible to make heap pollution at line 3.

    List<Dog> dogs = new ArrayList<>();
    List<Animal> animals = dogs; // compile-time error, otherwise heap pollution
    animals.add(new Cat());

getting the ng-object selected with ng-change

This might give you some ideas

.NET C# View Model

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

How do I change select2 box height

edit select2.css file. Go to the height option and change:

.select2-container .select2-choice {
    display: block;
    height: 36px;
    padding: 0 0 0 8px;
    overflow: hidden;
    position: relative;

    border: 1px solid #aaa;
    white-space: nowrap;
    line-height: 26px;
    color: #444;
    text-decoration: none;

    border-radius: 4px;

    background-clip: padding-box;

    -webkit-touch-callout: none;
      -webkit-user-select: none;
       -khtml-user-select: none;
         -moz-user-select: none;
          -ms-user-select: none;
              user-select: none;

    background-color: #fff;
    background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eee), color-stop(0.5, #fff));
    background-image: -webkit-linear-gradient(center bottom, #eee 0%, #fff 50%);
    background-image: -moz-linear-gradient(center bottom, #eee 0%, #fff 50%);
    background-image: -o-linear-gradient(bottom, #eee 0%, #fff 50%);
    background-image: -ms-linear-gradient(top, #fff 0%, #eee 50%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#ffffff', endColorstr = '#eeeeee', GradientType = 0);
    background-image: linear-gradient(top, #fff 0%, #eee 50%);
}

Hive load CSV with commas in quoted fields

As of Hive 0.14, the CSV SerDe is a standard part of the Hive install

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'

(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

Easy way to prevent Heroku idling?

Most of the answers here are outdated or currently not working. The current free tier for personal accounts are gives a base of 550 free dyno hours each month.

And a verified free account gives you 1000 hours of free dyno. I wrote an article on how I made my free app stay awake.

https://link.medium.com/uDHrk5HAD0

Hope it helps anyone who is in need of a solution in 2019

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

How do I find the size of a struct?

I assume you mean struct and not strict, but on a 32-bit system it'll be either 5 or 8 bytes, depending on if the compiler is padding the struct.

How to generate auto increment field in select query

If it is MySql you can try

SELECT @n := @n + 1 n,
       first_name, 
       last_name
  FROM table1, (SELECT @n := 0) m
 ORDER BY first_name, last_name

SQLFiddle

And for SQLServer

SELECT row_number() OVER (ORDER BY first_name, last_name) n,
       first_name, 
       last_name 
  FROM table1 

SQLFiddle

Pretty Printing a pandas dataframe

Following up on Mark's answer, if you're not using Jupyter for some reason, e.g. you want to do some quick testing on the console, you can use the DataFrame.to_string method, which works from -- at least -- Pandas 0.12 (2014) onwards.

import pandas as pd

matrix = [(1, 23, 45), (789, 1, 23), (45, 678, 90)]
df = pd.DataFrame(matrix, columns=list('abc'))
print(df.to_string())

#  outputs:
#       a    b   c
#  0    1   23  45
#  1  789    1  23
#  2   45  678  90

Check if an element contains a class in JavaScript?

This is a little old, but maybe someone will find my solution helpfull:

// Fix IE's indexOf Array
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement) {
        if (this == null) throw new TypeError();
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) n = 0;
            else if (n != 0 && n != Infinity && n != -Infinity) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
        if (n >= len) return -1;
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) if (k in t && t[k] === searchElement) return k;
        return -1;
    }
}
// add hasClass support
if (!Element.prototype.hasClass) {
    Element.prototype.hasClass = function (classname) {
        if (this == null) throw new TypeError();
        return this.className.split(' ').indexOf(classname) === -1 ? false : true;
    }
}

Routing with multiple Get methods in ASP.NET Web API

I have two get methods with same or no parameters

[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}

[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}

Just define custom routes in AppStart=>WebApiConfig.cs => under register method

config.Routes.MapHttpRoute(
       name: "GetFirstList",
       routeTemplate: "api/Controllername/FirstList"          
       );
config.Routes.MapHttpRoute(
       name: "GetSecondList",
       routeTemplate: "api/Controllername/SecondList"          
       );

Flatten nested dictionaries, compressing keys

here's a solution using a stack. No recursion.

def flatten_nested_dict(nested):
    stack = list(nested.items())
    ans = {}
    while stack:
        key, val = stack.pop()
        if isinstance(val, dict):
            for sub_key, sub_val in val.items():
                stack.append((f"{key}_{sub_key}", sub_val))
        else:
            ans[key] = val
    return ans

How to add font-awesome to Angular 2 + CLI project

UPDATE Feb 2020:
fortawesome package now supports ng add but it is available only for angular 9:

ng add @fortawesome/angular-fontawesome

UPDATE 8 Oct 2019:

You can use a new package https://www.npmjs.com/package/@fortawesome/angular-fontawesome

npm install @fortawesome/angular-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons

Add FontAwesomeModule to imports in src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
 
@NgModule({
  imports: [
    BrowserModule,
    FontAwesomeModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

Tie the icon to the property in your component src/app/app.component.ts:

import { Component } from '@angular/core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  faCoffee = faCoffee;
}

Use the icon in the template src/app/app.component.html:

<fa-icon [icon]="faCoffee"></fa-icon>

ORIGINAL ANSWER:

Option 1:

You can use angular-font-awesome npm module

npm install --save font-awesome angular-font-awesome

Import the module:

...
//
import { AngularFontAwesomeModule } from 'angular-font-awesome';
@NgModule({
  //...
  imports: [
    //...
    AngularFontAwesomeModule
  ],
  //...
})
export class AppModule { }

If you're using Angular CLI, add the font-awesome CSS to styles inside the angular-cli.json

"styles": [
    "styles.css",
    "../node_modules/font-awesome/css/font-awesome.css"
],

NOTE: If using SCSS preprocessor just change the css for scss

Example Use:

<fa name="cog" animation="spin"></fa>

Option 2:

There is an official story for that now

Install the font-awesome library and add the dependency to package.json

npm install --save font-awesome

Using CSS

To add Font Awesome CSS icons to your app...

// in .angular-cli.json

"styles": [
  "styles.css",
  "../node_modules/font-awesome/css/font-awesome.css"
]

Using SASS

Create an empty file _variables.scss in src/.

Add the following to _variables.scss:

$fa-font-path : '../node_modules/font-awesome/fonts'; In styles.scss add the following:

@import 'variables';
@import '../node_modules/font-awesome/scss/font-awesome';

Test

Run ng serve to run your application in develop mode, and navigate to http://localhost:4200.

To verify Font Awesome has been set up correctly, change src/app/app.component.html to the following...

<h1>
  {{title}} <i class="fa fa-check"></i>
</h1>

After saving this file, return to the browser to see the Font Awesome icon next to the app title.

Also there is a related question Angular CLI outputs the font-awesome font files the dist root as by default angular cli outputs the fonts in to the dist root, which is by the way not an issue at all.

Eclipse: Frustration with Java 1.7 (unbound library)

1) Find out where java is installed on your drive, open a cmd prompt, go to that location and run ".\java -version" to find out the exact version. Or, quite simply, check the add/remove module in the control panel.

2) After you actually install jdk 7, you need to tell Eclipse about it. Window -> Preferences -> Java -> Installed JREs.

How to install Visual Studio 2015 on a different drive

Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!

C - Convert an uppercase letter to lowercase

#include<stdio.h>

void main()
{
 char a;

 clrscr();
 printf("enter a character:");
 scanf("%c",&a);

 if(a>=65&&a<=90)
   printf("%c",a+32);
 else
   printf("type a capital letter");

 getch();
}

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

If you have IE8 installed in your machine, you can test how your site works in IE7 too. When you are in the page you need to test in IE7 browser, Open "Tools"->"developer tools". And then in the menu of that "Developer tools" dialog box, Click on "Browser Mode:[CURRENT MODE]" and there you can select 3 options. that is,

  1. IE7
  2. IE8
  3. IE8 Compatibility Mode

Turning error reporting off php

Read up on the configuration settings (e.g., display_errors, display_startup_errors, log_errors) and update your php.ini or .htaccess or .user.ini file, whichever is appropriate.

It works.

Inline style to act as :hover in CSS

If that <p> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'. https://cssinjs.org/

Why .NET String is immutable?

Why are string types immutable in C#

String is a reference type, so it is never copied, but passed by reference. Compare this to the C++ std::string object (which is not immutable), which is passed by value. This means that if you want to use a String as a key in a Hashtable, you're fine in C++, because C++ will copy the string to store the key in the hashtable (actually std::hash_map, but still) for later comparison. So even if you later modify the std::string instance, you're fine. But in .Net, when you use a String in a Hashtable, it will store a reference to that instance. Now assume for a moment that strings aren't immutable, and see what happens: 1. Somebody inserts a value x with key "hello" into a Hashtable. 2. The Hashtable computes the hash value for the String, and places a reference to the string and the value x in the appropriate bucket. 3. The user modifies the String instance to be "bye". 4. Now somebody wants the value in the hashtable associated with "hello". It ends up looking in the correct bucket, but when comparing the strings it says "bye"!="hello", so no value is returned. 5. Maybe somebody wants the value "bye"? "bye" probably has a different hash, so the hashtable would look in a different bucket. No "bye" keys in that bucket, so our entry still isn't found.

Making strings immutable means that step 3 is impossible. If somebody modifies the string he's creating a new string object, leaving the old one alone. Which means the key in the hashtable is still "hello", and thus still correct.

So, probably among other things, immutable strings are a way to enable strings that are passed by reference to be used as keys in a hashtable or similar dictionary object.

How can I select an element in a component template?

import the ViewChild decorator from @angular/core, like so:

HTML Code:

<form #f="ngForm"> 
  ... 
  ... 
</form>

TS Code:

import { ViewChild } from '@angular/core';

class TemplateFormComponent {

  @ViewChild('f') myForm: any;
    .
    .
    .
}

now you can use 'myForm' object to access any element within it in the class.

Source

Error: "setFile(null,false) call failed" when using log4j

Please changes your log file location to another drive. it will work.

this happen's the permission of creating log file.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Quickest possible solution (just 1 step)

Use git checkout -

You will see Switched to branch <branch_name>. Confirm it's the branch you want.


Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.


Mnemonic: this approach is a lot like using cd - to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).


More methodical solution (2-steps, but memorable)

The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.

1. Pick the branch you need

Use git branch -v

You see a list of existing local branches. Grab the branch name that suits your needs.

2. Move HEAD to it

Use git checkout <branch_name>

You will see Switched to branch <branch_name>. Success!


Outcomes

With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>.

Note that both git checkout - and git checkout <branch_name> will give additional instructions if you have committed changes while HEAD was detached.

Swap x and y axis without manually swapping values

In Numbers, click on the chart. Then in the BOTTOM LEFT corner there is the the option to either 'Plot Rows as Series'or 'Plot Columns as series'

find all the name using mysql query which start with the letter 'a'

Try this simple select:

select * 
from artists 
where name like "a%"

How can a file be copied?

Here is a simple way to do it, without any module. It's similar to this answer, but has the benefit to also work if it's a big file that doesn't fit in RAM:

with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:
    while True:
        block = f.read(16*1024*1024)  # work by blocks of 16 MB
        if not block:  # end of file
            break
        g.write(block)

Since we're writing a new file, it does not preserve the modification time, etc.
We can then use os.utime for this if needed.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Pandas index column title or name

Use df.index.rename('foo', inplace=True) to set the index name.

Seems this api is available since pandas 0.13.

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

Python group by

I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set

result = pandas.DataFrame(input).groupby(1).groups

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

Python, HTTPS GET with basic authentication

Update: OP uses Python 3. So adding an example using httplib2

import httplib2

h = httplib2.Http(".cache")

h.add_credentials('name', 'password') # Basic authentication

resp, content = h.request("https://host/path/to/resource", "POST", body="foobar")

The below works for python 2.6:

I use pycurl a lot in production for a process which does upwards of 10 million requests per day.

You'll need to import the following first.

import pycurl
import cStringIO
import base64

Part of the basic authentication header consists of the username and password encoded as Base64.

headers = { 'Authorization' : 'Basic %s' % base64.b64encode("username:password") }

In the HTTP header you will see this line Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=. The encoded string changes depending on your username and password.

We now need a place to write our HTTP response to and a curl connection handle.

response = cStringIO.StringIO()
conn = pycurl.Curl()

We can set various curl options. For a complete list of options, see this. The linked documentation is for the libcurl API, but the options does not change for other language bindings.

conn.setopt(pycurl.VERBOSE, 1)
conn.setopt(pycurlHTTPHEADER, ["%s: %s" % t for t in headers.items()])

conn.setopt(pycurl.URL, "https://host/path/to/resource")
conn.setopt(pycurl.POST, 1)

If you do not need to verify certificate. Warning: This is insecure. Similar to running curl -k or curl --insecure.

conn.setopt(pycurl.SSL_VERIFYPEER, False)
conn.setopt(pycurl.SSL_VERIFYHOST, False)

Call cStringIO.write for storing the HTTP response.

conn.setopt(pycurl.WRITEFUNCTION, response.write)

When you're making a POST request.

post_body = "foobar"
conn.setopt(pycurl.POSTFIELDS, post_body)

Make the actual request now.

conn.perform()

Do something based on the HTTP response code.

http_code = conn.getinfo(pycurl.HTTP_CODE)
if http_code is 200:
   print response.getvalue()

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

How do I convert a String object into a Hash object?

The solutions so far cover some cases but miss some (see below). Here's my attempt at a more thorough (safe) conversion. I know of one corner case which this solution doesn't handle which is single character symbols made up of odd, but allowed characters. For example {:> => :<} is a valid ruby hash.

I put this code up on github as well. This code starts with a test string to exercise all the conversions

require 'json'

# Example ruby hash string which exercises all of the permutations of position and type
# See http://json.org/
ruby_hash_text='{"alpha"=>{"first second > third"=>"first second > third", "after comma > foo"=>:symbolvalue, "another after comma > foo"=>10}, "bravo"=>{:symbol=>:symbolvalue, :aftercomma=>10, :anotheraftercomma=>"first second > third"}, "charlie"=>{1=>10, 2=>"first second > third", 3=>:symbolvalue}, "delta"=>["first second > third", "after comma > foo"], "echo"=>[:symbol, :aftercomma], "foxtrot"=>[1, 2]}'

puts ruby_hash_text

# Transform object string symbols to quoted strings
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')

# Transform object string numbers to quoted strings
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')

# Transform object value symbols to quotes strings
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')

# Transform array value symbols to quotes strings
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')

# Transform object string object value delimiter to colon delimiter
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')

puts ruby_hash_text

puts JSON.parse(ruby_hash_text)

Here are some notes on the other solutions here

adding a datatable in a dataset

DataSet ds = new DataSet();

DataTable activity = DTsetgvActivity.Copy();
activity.TableName = "activity";
ds.Tables.Add(activity);

DataTable Honer = DTsetgvHoner.Copy();
Honer.TableName = "Honer";
ds.Tables.Add(Honer);

DataTable Property = DTsetgvProperty.Copy();
Property.TableName = "Property";
ds.Tables.Add(Property);


DataTable Income = DTsetgvIncome.Copy();
Income.TableName = "Income";
ds.Tables.Add(Income);

DataTable Dependant = DTsetgvDependant.Copy();
Dependant.TableName = "Dependant";
ds.Tables.Add(Dependant);

DataTable Insurance = DTsetgvInsurance.Copy();
Insurance.TableName = "Insurance";
ds.Tables.Add(Insurance);

DataTable Sacrifice = DTsetgvSacrifice.Copy();
Sacrifice.TableName = "Sacrifice";
ds.Tables.Add(Sacrifice);

DataTable Request = DTsetgvRequest.Copy();
Request.TableName = "Request";
ds.Tables.Add(Request);

DataTable Branchs = DTsetgvBranchs.Copy();
Branchs.TableName = "Branchs";
ds.Tables.Add(Branchs);

Reading settings from app.config or web.config in .NET

Read From Config:

You'll need to add a reference to the configuration:

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code:

    string value = Properties.Settings.Default.keyname;
    

Save to the configuration:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();

How to get all selected values from <select multiple=multiple>?

$('#select-meal-type :selected') will contain an array of all of the selected items.

$('#select-meal-type option:selected').each(function() {
    alert($(this).val());
});

?

How to solve "The specified service has been marked for deletion" error

In my case, I execute taskkill /f /im dongleserver.exe , where dongleserver.exe is my program's exe file.

Then I can able to reinstall my program already.

How to correctly link php-fpm and Nginx Docker containers?

As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.

Updated my example files below with this latest revelation (thank you @alkaline )

This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)

docker-compose.yml:

version: '2'
services:
  php:
    container_name: test-php
    image: php:fpm
    volumes:
      - ./code:/var/www/html/site
  nginx:
    container_name: test-nginx
    image: nginx:latest
    volumes:
      - ./code:/var/www/html/site
      - ./site.conf:/etc/nginx/conf.d/site.conf:ro
    ports:
      - 80:80

(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)

In the same folder:

site.conf:

server
{
    listen   80;
    server_name site.local.[YOUR URL].com;

    root /var/www/html/site;
    index index.php;

    location /
    {
        try_files $uri =404;
    }

    location ~ \.php$ {
        fastcgi_pass   test-php:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

In folder code:

./code/index.php:

<?php
phpinfo();

and don't forget to update your hosts file:

127.0.0.1 site.local.[YOUR URL].com

and run your docker-compose up

$docker-compose up -d

and try the URL from your favorite browser

site.local.[YOUR URL].com/index.php

Git push error: Unable to unlink old (Permission denied)

I had the same issue and none of the solutions above worked for me. I deleted the offending folder. Then:

git reset --hard

Deleted any lingering files to clean up the git status, then did:

git pull

It finally worked.

NOTE: If the folder was, for instance, a public folder with build files, remember to rebuild the files

Rails get index of "each" loop

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

View list of all JavaScript variables in Google Chrome Console

To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.

Spring jUnit Testing properties file

Firstly, application.properties in the @PropertySource should read application-test.properties if that's what the file is named (matching these things up matters):

@PropertySource("classpath:application-test.properties ")

That file should be under your /src/test/resources classpath (at the root).

I don't understand why you'd specify a dependency hard coded to a file called application-test.properties. Is that component only to be used in the test environment?

The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.

In a typically laid out application, you'd have:

src/test/resources/application.properties

and

src/main/resources/application.properties

And then inject it like this:

@PropertySource("classpath:application.properties")

The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?

Format certain floating dataframe columns into percentage in pandas

style.format is vectorized, so we can simply apply it to the entire df (or just its numerical columns):

df[num_cols].style.format('{:,.3f}')

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

How to get a dependency tree for an artifact?

I know this post is quite old, but still, if anyone using IntelliJ any want to see dependency tree directly in IDE then they can install Maven Helper Plugin plugin.

Once installed open pom.xml and you would able to see Dependency Analyze tab like below. It also provides option to see dependency that is conflicted only and also as a tree structure.

enter image description here

Git Bash won't run my python files?

Add following line in you .bashrc file

############################
# Environment path setting #
############################
export PATH=/c/Python27:/c/Python27/Scripts:$PATH

How to connect to my http://localhost web server from Android Emulator

Another workaround is to get a free domain from no-ip.org and point it to your local ip address. Then, instead of using http://localhost/yourwebservice you can try http://yourdomain.no-ip.org/yourwebservice

Trigger css hover with JS

I know what you're trying to do, but why not simply do this:

$('div').addClass('hover');

The class is already defined in your CSS...

As for you original question, this has been asked before and it is not possible unfortunately. e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover

However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

Hope this helps!

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

Remove the last three characters from a string

items.Remove(items.Length - 3)

string.Remove() removes all items from that index to the end. items.length - 3 gets the index 3 chars from the end

Accessing localhost (xampp) from another computer over LAN network - how to?

These are the steps to follow when you want your PHP application to be installed on a LAN server (not on web)

  1. Get the internal IP or Static IP of the server (Ex: 192.168.1.193)
  2. Open XAMPP>apache>conf>httpd.conf file in notepad
  3. Search for Listen 80
  4. Above line would read like- #Listen 0.0.0.0:80 / 12.34.56.78:80
  5. Change the IP address and replace it with the static IP
  6. Save the httpd.conf file ensuring that the server is pointed to #Listen 192.168.1.193:80
  7. In the application root config.php (db connection) replace localhost with IP address of the server

Note: If firewall is installed, ensure that you add the http port 80 and 8080 to exceptions and allow to listen. Go to Control Panel>Windows Firewall>Allow a program to communicate through windows firewall>Add another program Name: http Port: 80 Add one more as http - 8080

If IIS (Microsoft .Net Application Internet Information Server) is installed with any Microsoft .Net application already on server, then it would have already occupied 80 port. In that case change the #Listen 192.168.1.193:80 to #Listen 192.168.1.193:8080

Hope this helps! :)

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

Render HTML to PDF in Django site

Try wkhtmltopdf with either one of the following wrappers

django-wkhtmltopdf or python-pdfkit

This worked great for me,supports javascript and css or anything for that matter which a webkit browser supports.

For more detailed tutorial please see this blog post

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

Angularjs how to upload multipart form data and a file?

It is more efficient to send the files directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

Doing Multiple $http.post Requests Directly from a FileList

$scope.upload = function(url, fileList) {
    var config = {
      headers: { 'Content-Type': undefined },
      transformResponse: angular.identity
    };
    var promises = fileList.map(function(file) {
      return $http.post(url, file, config);
    });
    return $q.all(promises);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.


Working Demo of "select-ng-files" Directive that Works with ng-model1

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_

How to select only the records with the highest date in LINQ

It could be something like:

var qry = from t in db.Lasttraces
          group t by t.AccountId into g
          orderby t.Date
          select new { g.AccountId, Date = g.Max(e => e.Date) };

JSLint is suddenly reporting: Use the function form of "use strict"

This is how simple it is: If you want to be strict with all your code, add "use strict"; at the start of your JavaScript.

But if you only want to be strict with some of your code, use the function form. Anyhow, I would recomend you to use it at the beginning of your JavaScript because this will help you be a better coder.

How to know the size of the string in bytes?

From MSDN:

A String object is a sequential collection of System.Char objects that represent a string.

So you can use this:

var howManyBytes = yourString.Length * sizeof(Char);

Compare two DataFrames and output their differences side-by-side

If you found this thread trying to compare data fames in tests, then take a look at assert_frame_equal method: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.testing.assert_frame_equal.html

What precisely does 'Run as administrator' do?

When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group.

Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access.

With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges.

When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

?????????????

I got some information from the developer's website

????

val cursor = context.contentResolver.query(fileUri, null, null, null, null)

??????????????

val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.moveToFirst()
val fileName = cursor.getString(nameIndex)
val size = cursor.getLong(sizeIndex)

???????

Don't forget to close resources

Retrieving file information

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

JQuery / JavaScript - trigger button click from another button click event

Well, you just fire the desired click event:

$(".first").click(function(){
    $(".second").click(); 
    return false;
});

nvm is not compatible with the npm config "prefix" option:

Delete and Reset the prefix

$ npm config delete prefix 
$ npm config set prefix $NVM_DIR/versions/node/v6.11.1

Note: Change the version number with the one indicated in the error message.

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local" Run "npm config delete prefix" or "nvm use --delete-prefix v6.11.1 --silent" to unset it.


Credits to @gabfiocchi on Github - "You need to overwrite nvm prefix"

undefined offset PHP error

Undefined offset means there's an empty array key for example:

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}

How do I remove/delete a folder that is not empty?

Recursion-based, pure pathlib solution:

from pathlib import Path

def remove_path(path: Path):
    if path.is_file() or path.is_symlink():
        path.unlink()
        return
    for p in path.iterdir():
        remove_path(p)
    path.rmdir()

Supports Windows and symbolic links

How to convert interface{} to string?

To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

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.

how to get selected row value in the KendoUI

One way is to use the Grid's select() and dataItem() methods.

In single selection case, select() will return a single row which can be passed to dataItem()

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model

For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
  var selectedItem = entityGrid.dataItem(row);
  // selectedItem has EntityVersionId and the rest of your model
});

Add Bean Programmatically to Spring Web App Context

Actually AnnotationConfigApplicationContext derived from AbstractApplicationContext, which has empty postProcessBeanFactory method left for override

/**
 * Modify the application context's internal bean factory after its standard
 * initialization. All bean definitions will have been loaded, but no beans
 * will have been instantiated yet. This allows for registering special
 * BeanPostProcessors etc in certain ApplicationContext implementations.
 * @param beanFactory the bean factory used by the application context
 */
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

To leverage this, Create AnnotationConfigApplicationContextProvider class which may look like following(given for Vertx instance example, you can use MyClass instead)...

public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;

public CustomAnnotationApplicationContextProvider(Vertx vertx) {
    this.vertx = vertx;
}

/**
 * Register all beans to spring bean factory
 *
 * @param beanFactory, spring bean factory to register your instances
 */
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.registerSingleton("vertx", vertx);
}

/**
 * Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
 *
 * @return {@link AnnotationConfigApplicationContext} instance
 */
public AnnotationConfigApplicationContext get() {
    return new AnnotationConfigApplicationContext() {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
 *
 * @param beanFactory bean factory for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
 */
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
    return new AnnotationConfigApplicationContext(beanFactory) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
 *
 * @param annotatedClasses, set of annotated classes for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
 */
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
    return new AnnotationConfigApplicationContext(annotatedClasses) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}

/**
 * proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
 *
 * @param basePackages set of base packages for spring
 * @return
 * @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
 */
public AnnotationConfigApplicationContext get(String... basePackages) {
    return new AnnotationConfigApplicationContext(basePackages) {

        @Override
        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.postProcessBeanFactory(beanFactory);
            configureBeans(beanFactory);
        }
    };
}
}

While creating ApplicationContext you can create it using

Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);

How do I get the color from a hexadecimal color code using .NET?

You could use the following code:

Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");

How to install wget in macOS?

I update mac to Sierra , 10.12.3

My wget stop working.

When I tried to install by typing

brew install wget --with-libressl

I got the following warning

Warning: wget-1.19.1 already installed, it's just not linked.

Then tried to unsintall by typing

brew uninstall wget --with-libressl

Then I reinstalled by typing

brew install wget --with-libressl

Finally I got it worked.Thank God!

SVG fill color transparency / alpha?

fill="#044B9466"

This is an RGBA color in hex notation inside the SVG, defined with hex values. This is valid, but not all programs can display it properly...

You can find the browser support for this syntax here: https://caniuse.com/#feat=css-rrggbbaa

As of August 2017: RGBA fill colors will display properly on Mozilla Firefox (54), Apple Safari (10.1) and Mac OS X Finder's "Quick View". However Google Chrome did not support this syntax until version 62 (was previously supported from version 54 with the Experimental Platform Features flag enabled).

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;

Live video streaming using Java?

Yes if you want to stream live video you can use RTSP protoco this will allow you to create a video file, which can be play while creating, both operation will work simultaneously. RTSP-Client-Server

javascript password generator

here is a simply smart code :

function generate(l) {
    if (typeof l==='undefined'){var l=8;}
    /* c : alphanumeric character string */
    var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
    n=c.length,
    /* p : special character string */
    p='!@#$+-*&_',
    o=p.length,
    r='',
    n=c.length,
    /* s : determinate the position of the special character */
    s=Math.floor(Math.random() * (p.length-1));

    for(var i=0; i<l; ++i){
        if(s == i){
            /* special charact insertion (random position s) */
            r += p.charAt(Math.floor(Math.random() * o));
        }else{
            /* alphanumeric insertion */
            r += c.charAt(Math.floor(Math.random() * n));
        }
    }
    return r;
}

Simply call generate(), and it do key containing one special character (!@#$+-*&_) for security.

Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_

There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/

How do I add PHP code/file to HTML(.html) files?

You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php

ORA-12154 could not resolve the connect identifier specified

This is an old question but Oracle's latest installers are no improvement, so I recently found myself back in this swamp, thrashing around for several days ...

My scenario was SQL Server 2016 RTM. 32-bit Oracle 12c Open Client + ODAC was eventually working fine for Visual Studio Report Designer and Integration Services designer, and also SSIS packages run through SQL Server Agent (with 32-bit option). 64-bit was working fine for Report Portal when defining and Testing an Data Source, but running the reports always gave the dreaded "ORA-12154" error.

My final solution was to switch to an EZCONNECT connection string - this avoids the TNSNAMES mess altogether. Here's a link to a detailed description, but it's basically just: host:port/sid

http://www.oracledistilled.com/oracle-database/oracle-net/using-easy-connect-ezconnect-naming-method-to-connect-to-oracle-databases/

In case it helps anyone in the future (or I get stuck on this again), here are my Oracle install steps (the full horror):

Install Oracle drivers: Oracle Client 12c (32-bit) plus ODAC.

a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html ):

i. winnt_12102_client32.zip

ii. ODAC112040Xcopy_32bit.zip

b. Run winnt_12102_client32\client32\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12. Accept other defaults.

c. Start a Command Prompt “As Administrator” and change directory (cd) to your ODAC112040Xcopy_32bit folder.

d. Enter the command: install.bat all C:\Oracle\Oracle12 odac

e. Copy the tnsnames.ora file from another machine to these folders: *

i. C:\Oracle\Oracle12\network\admin *

ii. C:\Oracle\Oracle12\product\12.1.0\client_1\network\admin *

Install Oracle Client 12c (x64) plus ODAC

a. Download and unzip the following files from http://www.oracle.com/technetwork/database/enterprise-edition/downloads/database12c-win64-download-2297732.html and http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html ):

i. winx64_12102_client.zip

ii. ODAC121024Xcopy_x64.zip

b. Run winx64_12102_client\client\setup.exe. For the Installation Type, choose Admin. For the installation location enter C:\Oracle\Oracle12_x64. Accept other defaults.

c. Start a Command Prompt “As Administrator” and change directory (cd) to the C:\Software\Oracle Client\ODAC121024Xcopy_x64 folder.

d. Enter the command: install.bat all C:\Oracle\Oracle12_x64 odac

e. Copy the tnsnames.ora file from another machine to these folders: *

i. C:\Oracle\Oracle12_x64\network\admin *

ii. C:\Oracle\Oracle12_x64\product\12.1.0\client_1\network\admin *

* If you are going with the EZCONNECT method, then these steps are not required.

The ODAC installs are tricky and obscure - thanks to Dan English who gave me the method (detailed above) for that.

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);

OR

 var bytes = web.DownloadData(url);

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]

The error was with :

 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

AND RESOLVED WITH :

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

How do I get started with Node.js

Use the source, Luke.

No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.

Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.

PHP json_decode() returns NULL with valid JSON?

Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this

if(get_magic_quotes_gpc()){
   $param = stripslashes($row['your column name']);
}else{
  $param = $row['your column name'];
}

$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);

Resize a picture to fit a JLabel

public static void main(String s[]) 
  {

    BufferedImage image = null;
    try 
    {
        image = ImageIO.read(new File("your image path"));

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
    jLabel1.setIcon(imageIcon);
}


private Image fitimage(Image img , int w , int h)
{
    BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedimage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0,w,h,null);
    g2.dispose();
    return resizedimage;
}

Eclipse Build Path Nesting Errors

I had the same issue and correct answer above did not work for me. What I did to resolve it was to go to Build Path->Configure Build Path and under the source tab I removed all the sources (which only had one source) and reconfigured them from there. I ended up removing the project from eclipse and import the maven project again in order to clear up the error.

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

Efficient way to insert a number into a sorted array of numbers?

Very good and remarkable question with a very interesting discussion! I also was using the Array.sort() function after pushing a single element in an array with some thousands of objects.

I had to extend your locationOf function for my purpose because of having complex objects and therefore the need for a compare function like in Array.sort():

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than dividing by 2

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var patientCompare = function (a, b) {
    if (a.lastName < b.lastName) return -1;
    if (a.lastName > b.lastName) return 1;
    return 0;
};

Is there a better alternative than this to 'switch on type'?

After having compared the options a few answers here provided to F# features, I discovered F# to have a way better support for type-based switching (although I'm still sticking to C#).
You might want to see here and here.

jQuery Dialog Box

Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:

$(document).ready({
    $('a.TOClink').click(function(){
        showTOC();
    });
});

function showTOC() {
    $('#example').dialog({modal:true});
}

A more concise example which accomplishes the desired effect using the jQuery UI dialog is:

   <div id="terms" style="display:none;">
       Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
   <a id="showTerms" href="#">Show Terms &amp; Conditions</a>      
   <script type="text/javascript">
       $(document).ready(function(){
           $('#showTerms').click(function(){
               $('#terms').dialog({modal:true});   
           });
       });
   </script>

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

Can I call methods in constructor in Java?

You can: this is what constructors are for. Also you make it clear that the object is never constructed in an unknown state (without configuration loaded).

You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.

Python - Passing a function into another function

For passing both a function, and any arguments to the function:

from typing import Callable    

def looper(fn: Callable, n:int, *args, **kwargs):
    """
    Call a function `n` times

    Parameters
    ----------
    fn: Callable
        Function to be called.
    n: int
        Number of times to call `func`.
    *args
        Positional arguments to be passed to `func`.
    **kwargs
        Keyword arguments to be passed to `func`.

    Example
    -------
    >>> def foo(a:Union[float, int], b:Union[float, int]):
    ...    '''The function to pass'''
    ...    print(a+b)
    >>> looper(foo, 3, 2, b=4)
    6
    6
    6       
    """
    for i in range(n):
        fn(*args, **kwargs)

Depending on what you are doing, it could make sense to define a decorator, or perhaps use functools.partial.

PowerShell array initialization

If I don't know the size up front, I use an arraylist instead of an array.

$al = New-Object System.Collections.ArrayList
for($i=0; $i -lt 5; $i++)
{
    $al.Add($i)
}

CodeIgniter removing index.php from url

You can eliminate index.php from URL by create .htaccess file in the base directory of your porject, that file its content as

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|uploads|favicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]

save that file also your changed in config.php file is right

$config['index_page'] = '';

I wish to run successfully

How do I turn a C# object into a JSON string in .NET?

It is as easy as this (it works for dynamic objects as well (type object)):

string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);

Is there an XSLT name-of element?

For those interested, there is no:

<xsl:tag-of select="."/>

However you can re-create the tag/element by going:

<xsl:element name="{local-name()}">
  <xsl:value-of select="substring(.,1,3)"/>
</xsl:element>

This is useful in an xslt template that for example handles formatting data values for lots of different elements. When you don't know the name of the element being worked on and you can still output the same element, and modify the value if need be.

How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text = event.target.value;
    onChange(id, text);
  };

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />
    </div>
  );
};

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });
  };

  const fields = props.fields.map(field => (
    <FieldEditor
      key={field}
      id={field}
      onChange={handleFieldChange}
      value={values[field]}
    />
  ));

  return (
    <div>
      {fields}
      <pre>{JSON.stringify(values, null, 2)}</pre>
    </div>
  );
};

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;
};

Original - pre-hooks version:

_x000D_
_x000D_
class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleChange(event) {_x000D_
    const text = event.target.value;_x000D_
    this.props.onChange(this.props.id, text);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {};_x000D_
_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    const fields = this.props.fields.map(field => (_x000D_
      <FieldEditor_x000D_
        key={field}_x000D_
        id={field}_x000D_
        onChange={this.handleFieldChange}_x000D_
        value={this.state[field]}_x000D_
      />_x000D_
    ));_x000D_
_x000D_
    return (_x000D_
      <div>_x000D_
        {fields}_x000D_
        <div>{JSON.stringify(this.state)}</div>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
_x000D_
  return <FormEditor fields={fields} />;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<App />, document.body);
_x000D_
_x000D_
_x000D_

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I added the control to the Triggers tag in the update panel:

    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="exportLinkButton" />
    </Triggers>
</asp:UpdatePanel>

This way the exportLinkButton will trigger the UpdatePanel to update.
More info here.

C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

tweaked @David Wolever solution slightly:

function closePopoversOnDocumentEvents() {
  var visiblePopovers = [];

  var $body = $("body");

  function hideVisiblePopovers() {
    /* this was giving problems and had a bit of overhead
      $.each(visiblePopovers, function() {
        $(this).popover("hide");
      });
    */
    while (visiblePopovers.length !== 0) {
       $(visiblePopovers.pop()).popover("hide");
    }
  }

  function onBodyClick(event) {
    if (event.isDefaultPrevented())
      return;

    var $target = $(event.target);
    if ($target.data("bs.popover"))
      return;

    if ($target.parents(".popover").length)
      return;

    hideVisiblePopovers();
  }

  function onBodyKeyup(event) {
    if (event.isDefaultPrevented())
      return;

    if (event.keyCode != 27) // esc
      return;

    hideVisiblePopovers();
    event.preventDefault();
  }

  function onPopoverShow(event) {
    if (!visiblePopovers.length) {
      $body.on("click", onBodyClick);
      $body.on("keyup", onBodyKeyup);
    }
    visiblePopovers.push(event.target);
  }

  function onPopoverHide(event) {
    var target = event.target;
    var index = visiblePopovers.indexOf(target);
    if (index > -1) {
      visiblePopovers.splice(index, 1);
    }
    if (visiblePopovers.length == 0) {
      $body.off("click", onBodyClick);
      $body.off("keyup", onBodyKeyup);
    }
  }

  $body.on("show.bs.popover", onPopoverShow);
  $body.on("hide.bs.popover", onPopoverHide);
}

Command line: search and replace in all filenames matched by grep

The answer already given of using find and sed

find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g' instead of the sed command.

For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:

rpl -R foo bar .

It's not available by default on most Linux distros but is quick to install (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents (including moving files between directories and creating new parent directories).
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

Check the README for examples.

How do I pass variables and data from PHP to JavaScript?

Here is is the trick:

  1. Here is your 'PHP' to use that variable:

    <?php
        $name = 'PHP variable';
        echo '<script>';
        echo 'var name = ' . json_encode($name) . ';';
        echo '</script>';
    ?>
    
  2. Now you have a JavaScript variable called 'name', and here is your JavaScript code to use that variable:

    <script>
         console.log("I am everywhere " + name);
    </script>
    

Generating Unique Random Numbers in Java

This is the most simple method to generate unique random values in a range or from an array.

In this example, I will be using a predefined array but you can adapt this method to generate random numbers as well. First, we will create a sample array to retrieve our data from.

  1. Generate a random number and add it to the new array.
  2. Generate another random number and check if it is already stored in the new array.
  3. If not then add it and continue
  4. else reiterate the step.
ArrayList<Integer> sampleList = new ArrayList<>();
sampleList.add(1);
sampleList.add(2);
sampleList.add(3);
sampleList.add(4);
sampleList.add(5);
sampleList.add(6);
sampleList.add(7);
sampleList.add(8);

Now from the sampleList we will produce five random numbers that are unique.

int n;
randomList = new ArrayList<>();
for(int  i=0;i<5;i++){
    Random random = new Random();
    n=random.nextInt(8);     //Generate a random index between 0-7

    if(!randomList.contains(sampleList.get(n)))
    randomList.add(sampleList.get(n));
    else
        i--;    //reiterating the step
}
        

This is conceptually very simple. If the random value generated already exists then we will reiterate the step. This will continue until all the values generated are unique.

If you found this answer useful then you can vote it up as it is much simple in concept as compared to the other answers.

HTML "overlay" which allows clicks to fall through to elements behind it

My team ran into this issue and resolved it very nicely.

  • add a class "passthrough" or something to each element you want clickable and which is under the overlay.
  • for each ".passthrough" element append a div and position it exactly on top of its parent. add class "element-overlay" to this new div.
  • The ".element-overlay" css should have a high z-index (above the page's overlay), and the elements should be transparent.

This should resolve your problem as the events on the ".element-overlay" should bubble up to ".passthrough". If you still have problems (we did not see any so far) you can play around with the binding.

This is an enhancement to @jvenema's solution.

The nice thing about this is that

  • you don't pass through ALL events to ALL elements. Just the ones you want. (resolved @jvenema's argument)
  • All events will work properly. (hover for example).

If you have any problems please let me know so I can elaborate.

String Array object in Java

First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.

However, if you really want to use that Getter and Setter, change the public modifier to private instead.

Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:

public String name;

public Person(String name){
    this.name = name; // This is Shadowing
}

In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");

Variable name will be equal to "theolc".
----------End of shadowing----------

Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.

public class Athlete {

public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};

public Athlete() {

}

In your main method, you could do this.

public static void main(String[] args) {
       Athlete art = new Athlete();   

       System.out.println(art.name[0]);
       System.out.println(art.country[0]);
    }
}

How to get json key and value in javascript?

A simple approach instead of using JSON.parse

 success: function(response){
     var resdata = response;
     alert(resdata['name']);
}

Get escaped URL parameter

function getURLParameters(paramName) 
{
        var sURL = window.document.URL.toString();  
    if (sURL.indexOf("?") > 0)
    {
       var arrParams = sURL.split("?");         
       var arrURLParams = arrParams[1].split("&");      
       var arrParamNames = new Array(arrURLParams.length);
       var arrParamValues = new Array(arrURLParams.length);     
       var i = 0;
       for (i=0;i<arrURLParams.length;i++)
       {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
       }

       for (i=0;i<arrURLParams.length;i++)
       {
                if(arrParamNames[i] == paramName){
            //alert("Param:"+arrParamValues[i]);
                return arrParamValues[i];
             }
       }
       return "No Parameters Found";
    }

}

How to delete from multiple tables in MySQL?

I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.

enter image description here

How to count the number of columns in a table using SQL?

select count(*) 
from user_tab_columns
where table_name='MYTABLE' --use upper case

Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';

How to set selected value on select using selectpicker plugin from bootstrap

$('selector').selectpicker('val',value);

in place of selector you can give you selector either class or id for example: $('#mySelect').selectpicker('val',your_value)

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Use this command

gcc -dM -E - < /dev/null

to get this

    #define _LP64 1
#define _STDC_PREDEF_H 1
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
#define __BIGGEST_ALIGNMENT__ 16
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __CHAR16_TYPE__ short unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __CHAR_BIT__ 8
#define __DBL_DECIMAL_DIG__ 17
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __DBL_DIG__ 15
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define __DBL_HAS_DENORM__ 1
#define __DBL_HAS_INFINITY__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __DBL_MANT_DIG__ 53
#define __DBL_MAX_10_EXP__ 308
#define __DBL_MAX_EXP__ 1024
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __DBL_MIN_10_EXP__ (-307)
#define __DBL_MIN_EXP__ (-1021)
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __DEC128_EPSILON__ 1E-33DL
#define __DEC128_MANT_DIG__ 34
#define __DEC128_MAX_EXP__ 6145
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __DEC128_MIN_EXP__ (-6142)
#define __DEC128_MIN__ 1E-6143DL
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __DEC32_EPSILON__ 1E-6DF
#define __DEC32_MANT_DIG__ 7
#define __DEC32_MAX_EXP__ 97
#define __DEC32_MAX__ 9.999999E96DF
#define __DEC32_MIN_EXP__ (-94)
#define __DEC32_MIN__ 1E-95DF
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __DEC64_EPSILON__ 1E-15DD
#define __DEC64_MANT_DIG__ 16
#define __DEC64_MAX_EXP__ 385
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __DEC64_MIN_EXP__ (-382)
#define __DEC64_MIN__ 1E-383DD
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DECIMAL_BID_FORMAT__ 1
#define __DECIMAL_DIG__ 21
#define __DEC_EVAL_METHOD__ 2
#define __ELF__ 1
#define __FINITE_MATH_ONLY__ 0
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DECIMAL_DIG__ 9
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __FLT_DIG__ 6
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __FLT_EVAL_METHOD__ 0
#define __FLT_HAS_DENORM__ 1
#define __FLT_HAS_INFINITY__ 1
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MANT_DIG__ 24
#define __FLT_MAX_10_EXP__ 38
#define __FLT_MAX_EXP__ 128
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __FLT_MIN_10_EXP__ (-37)
#define __FLT_MIN_EXP__ (-125)
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __FLT_RADIX__ 2
#define __FXSR__ 1
#define __GCC_ASM_FLAG_OUTPUTS__ 1
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __GCC_HAVE_DWARF2_CFI_ASM 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_IEC_559 2
#define __GCC_IEC_559_COMPLEX 2
#define __GNUC_MINOR__ 3
#define __GNUC_PATCHLEVEL__ 0
#define __GNUC_STDC_INLINE__ 1
#define __GNUC__ 6
#define __GXX_ABI_VERSION 1010
#define __INT16_C(c) c
#define __INT16_MAX__ 0x7fff
#define __INT16_TYPE__ short int
#define __INT32_C(c) c
#define __INT32_MAX__ 0x7fffffff
#define __INT32_TYPE__ int
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
#define __INT8_C(c) c
#define __INT8_MAX__ 0x7f
#define __INT8_TYPE__ signed char
#define __INTMAX_C(c) c ## L
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INTMAX_TYPE__ long int
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST32_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_FAST64_TYPE__ long int
#define __INT_FAST8_MAX__ 0x7f
#define __INT_FAST8_TYPE__ signed char
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT_LEAST16_TYPE__ short int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_LEAST32_TYPE__ int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST8_TYPE__ signed char
#define __INT_MAX__ 0x7fffffff
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __LDBL_DIG__ 18
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __LDBL_HAS_DENORM__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __LDBL_HAS_QUIET_NAN__ 1
#define __LDBL_MANT_DIG__ 64
#define __LDBL_MAX_10_EXP__ 4932
#define __LDBL_MAX_EXP__ 16384
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __LDBL_MIN_10_EXP__ (-4931)
#define __LDBL_MIN_EXP__ (-16381)
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __LONG_LONG_MAX__ 0x7fffffffffffffffLL
#define __LONG_MAX__ 0x7fffffffffffffffL
#define __LP64__ 1
#define __MMX__ 1
#define __NO_INLINE__ 1
#define __ORDER_BIG_ENDIAN__ 4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 3412
#define __PIC__ 2
#define __PIE__ 2
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __PTRDIFF_MAX__ 0x7fffffffffffffffL
#define __PTRDIFF_TYPE__ long int
#define __REGISTER_PREFIX__ 
#define __SCHAR_MAX__ 0x7f
#define __SEG_FS 1
#define __SEG_GS 1
#define __SHRT_MAX__ 0x7fff
#define __SIG_ATOMIC_MAX__ 0x7fffffff
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __SIG_ATOMIC_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __SIZEOF_FLOAT128__ 16
#define __SIZEOF_FLOAT80__ 16
#define __SIZEOF_FLOAT__ 4
#define __SIZEOF_INT128__ 16
#define __SIZEOF_INT__ 4
#define __SIZEOF_LONG_DOUBLE__ 16
#define __SIZEOF_LONG_LONG__ 8
#define __SIZEOF_LONG__ 8
#define __SIZEOF_POINTER__ 8
#define __SIZEOF_PTRDIFF_T__ 8
#define __SIZEOF_SHORT__ 2
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WCHAR_T__ 4
#define __SIZEOF_WINT_T__ 4
#define __SIZE_MAX__ 0xffffffffffffffffUL
#define __SIZE_TYPE__ long unsigned int
#define __SSE2_MATH__ 1
#define __SSE2__ 1
#define __SSE_MATH__ 1
#define __SSE__ 1
#define __SSP_STRONG__ 3
#define __STDC_HOSTED__ 1
#define __STDC_IEC_559_COMPLEX__ 1
#define __STDC_IEC_559__ 1
#define __STDC_ISO_10646__ 201605L
#define __STDC_NO_THREADS__ 1
#define __STDC_UTF_16__ 1
#define __STDC_UTF_32__ 1
#define __STDC_VERSION__ 201112L
#define __STDC__ 1
#define __UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define __UINT16_TYPE__ short unsigned int
#define __UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define __UINT32_TYPE__ unsigned int
#define __UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define __UINT64_TYPE__ long unsigned int
#define __UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define __UINT8_TYPE__ unsigned char
#define __UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define __UINTMAX_TYPE__ long unsigned int
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define __UINTPTR_TYPE__ long unsigned int
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST16_TYPE__ long unsigned int
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST32_TYPE__ long unsigned int
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_FAST64_TYPE__ long unsigned int
#define __UINT_FAST8_MAX__ 0xff
#define __UINT_FAST8_TYPE__ unsigned char
#define __UINT_LEAST16_MAX__ 0xffff
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define __UINT_LEAST32_TYPE__ unsigned int
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define __UINT_LEAST64_TYPE__ long unsigned int
#define __UINT_LEAST8_MAX__ 0xff
#define __UINT_LEAST8_TYPE__ unsigned char
#define __USER_LABEL_PREFIX__ 
#define __VERSION__ "6.3.0 20170406"
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_TYPE__ int
#define __WINT_MAX__ 0xffffffffU
#define __WINT_MIN__ 0U
#define __WINT_TYPE__ unsigned int
#define __amd64 1
#define __amd64__ 1
#define __code_model_small__ 1
#define __gnu_linux__ 1
#define __has_include(STR) __has_include__(STR)
#define __has_include_next(STR) __has_include_next__(STR)
#define __k8 1
#define __k8__ 1
#define __linux 1
#define __linux__ 1
#define __pic__ 2
#define __pie__ 2
#define __unix 1
#define __unix__ 1
#define __x86_64 1
#define __x86_64__ 1
#define linux 1
#define unix 1

How can I create a UIColor from a hex string?

You can use this library

https://github.com/burhanuddin353/TFTColor

Swift

UIColor.colorWithRGB(hexString: "FF34AE" alpha: 1.0)

Objective-C

[UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]

SELECT query with CASE condition and SUM()

select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

Cheers -

Disable single warning error

Use #pragma warning ( push ), then #pragma warning ( disable ), then put your code, then use #pragma warning ( pop ) as described here:

#pragma warning( push )
#pragma warning( disable : WarningCode)
// code with warning
#pragma warning( pop ) 

Failed to connect to mailserver at "localhost" port 25

Change SMTP=localhost to SMTP=smtp.gmail.com

how to do file upload using jquery serialization

A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {
    $('#ifoftheform').ajaxForm(function(result) {
        alert('the form was successfully processed');
    });
});

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...