Programs & Examples On #Linkfieldvalue

Sorting a list with stream.sorted() in Java

Collection<Map<Item, Integer>> itemCollection = basket.values();
Iterator<Map<Item, Integer>> itemIterator =   itemCollection.stream().sorted(new TestComparator()).collect(Collectors.toList()).iterator();



package com.ie.util;

import com.ie.item.Item;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class TestComparator implements Comparator<Map<Item, Integer>> {

// comparator is used to sort the Items based on the price


    @Override
    public int compare(Map<Item, Integer> o1, Map<Item, Integer> o2) {


      //  System.out.println("*** compare method will be called *****");


        Item item1 = null;
        Item item2 = null;


        Set<Item> itemSet1 = o1.keySet();
        Iterator<Item> itemIterator1 = itemSet1.iterator();
        if(itemIterator1.hasNext()){
           item1 =   itemIterator1.next();
        }

        Set<Item> itemSet2 = o2.keySet();
        Iterator<Item> itemIterator2 = itemSet2.iterator();
        if(itemIterator2.hasNext()){
            item2 =   itemIterator2.next();
        }


        return -item1.getPrice().compareTo(item2.getPrice());


    }
}

**** this is helpful to sort the nested map objects like Map> here i sorted based on the Item object price .

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

event Action<> vs event EventHandler<>

The advantage of a wordier approach comes when your code is inside a 300,000 line project.

Using the action, as you have, there is no way to tell me what bool, int, and Blah are. If your action passed an object that defined the parameters then ok.

Using an EventHandler that wanted an EventArgs and if you would complete your DiagnosticsArgs example with getters for the properties that commented their purpose then you application would be more understandable. Also, please comment or fully name the arguments in the DiagnosticsArgs constructor.

Java Date vs Calendar

Date should be re-developed. Instead of being a long interger, it should hold year, month, date, hour, minute, second, as separate fields. It might be even good to store the calendar and time zone this date is associated with.

In our natural conversation, if setup an appointment at Nov. 1, 2013 1pm NY Time, this is a DateTime. It is NOT a Calendar. So we should be able to converse like this in Java as well.

When Date is stored as a long integer (of mili seconds since Jan 1 1970 or something), calculating its current date depends on the calendar. Different calendars will give different date. This is from the prospective of giving an absolute time (eg 1 trillion seconds after Big Bang). But often we also need a convenient way of conversation, like an object encapsulating year, month etc.

I wonder if there are new advances in Java to reconcile these 2 objectives. Maybe my java knowledge is too old.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

The other answers only show the changed files.

git log -p DIR is very useful, if you need the full diff of all changed files in a specific subdirectory.

Example: Show all detailed changes in a specific version range

git log -p 8a5fb..HEAD -- A B

commit 62ad8c5d
Author: Scott Tiger
Date:   Mon Nov 27 14:25:29 2017 +0100

    My comment

...
@@ -216,6 +216,10 @@ public class MyClass {

+  Added
-  Deleted

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How to keep Docker container running after starting services?

Capture the PID of the ngnix process in a variable (for example $NGNIX_PID) and at the end of the entrypoint file do

wait $NGNIX_PID 

In that way, your container should run until ngnix is alive, when ngnix stops, the container stops as well

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

According to the comments, the data-type in the datatable is DATE. So you should simply use: "select date_column from table;"

Now if you execute the select you will get back a date data-type, which should be what you need for the .xsd.

Culture-dependent formating of the date should be done in the GUI (most languages have convenient ways to do so), not in the select-statement.

Page vs Window in WPF?

Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame

Windows are just normal WPF application Windows, but can host Pages via a Frame container

How to round down to nearest integer in MySQL?

Both Query is used for round down the nearest integer in MySQL

  1. SELECT FLOOR(445.6) ;
  2. SELECT NULL(222.456);

Cannot open Windows.h in Microsoft Visual Studio

Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.

You should see:

$(WindowsSdkDir)\include

If this is missing, you found a problem. If not, search for a file. It should be located in

32 bit systems:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include

64 bit systems:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include

if VS was installed in the default directory.

Source: http://forums.codeguru.com/showthread.php?465935-quot-windows-h-no-such-file-or-directory-quot-in-Visual-Studio-2008!-Help&p=1786039#post1786039

How to create a string with format?

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)"

Update: I wrote this answer before Swift had String(format:) added to it's API. Use the method given by the top answer.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

Please always check your certificate expiry date first because most of the certificates have an expiry date. In my case certificate has expired and I was trying to build project.

How to find the extension of a file in C#?

private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Regular Expression: Any character that is NOT a letter or number

This is way way too late, but since there is no accepted answer I'd like to provide what I think is the simplest one: \D - matches all non digit characters.

_x000D_
_x000D_
var x = "123 235-25%";_x000D_
x.replace(/\D/g, '');
_x000D_
_x000D_
_x000D_

Results in x: "12323525"

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Find all zero-byte files in directory and subdirectories

No, you don't have to bother grep.

find $dir -size 0 ! -name "*.xml"

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

WebSockets is definitely the future.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.

Comparison:

of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia

Advantages:

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).

P.S.

Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

Command to find information about CPUs on a UNIX machine

My favorite is to look at the boot messages. If it's been recently booted try running /etc/dmesg. Otherwise find the boot messages, logged in /var/adm or some place in /var.

Best practice multi language website

I've been asking myself related questions over and over again, then got lost in formal languages... but just to help you out a little I'd like to share some findings:

I recommend to give a look at advanced CMS

Typo3 for PHP (I know there is a lot of stuff but thats the one I think is most mature)

Plone in Python

If you find out that the web in 2013 should work different then, start from scratch. That would mean to put together a team of highly skilled/experienced people to build a new CMS. May be you'd like to give a look at polymer for that purpose.

If it comes to coding and multilingual websites / native language support, I think every programmer should have a clue about unicode. If you don't know unicode you'll most certainly mess up your data. Do not go with the thousands of ISO codes. They'll only save you some memory. But you can do literally everything with UTF-8 even store chinese chars. But for that you'd need to store either 2 or 4 byte chars that makes it basically a utf-16 or utf-32.

If it's about URL encoding, again there you shouldn't mix encodings and be aware that at least for the domainname there are rules defined by different lobbies that provide applications like a browser. e.g. a Domain could be very similar like:

?ankofamerica.com or bankofamerica.com samesamebutdifferent ;)

Of course you need the filesystem to work with all encodings. Another plus for unicode using utf-8 filesystem.

If its about translations, think about the structure of documents. e.g. a book or an article. You have the docbook specifications to understand about those structures. But in HTML its just about content blocks. So you'd like to have a translation on that level, also on webpage level or domain level. So if a block doesn't exist its just not there, if a webpage doesn't exist you'll get redirected to the upper navigation level. If a domain should be completely different in navigation structure, then.. its a complete different structure to manage. This can already be done with Typo3.

If its about frameworks, the most mature ones I know, to do the general stuff like MVC(buzzword I really hate it! Like "performance" If you want to sell something, use the word performance and featurerich and you sell... what the hell) is Zend. It has proven to be a good thing to bring standards to php chaos coders. But, typo3 also has a Framework besides the CMS. Recently it has been redeveloped and is called flow3 now. The frameworks of course cover database abstraction, templating and concepts for caching, but have individual strengths.

If its about caching... that can be awefully complicated / multilayered. In PHP you'll think about accellerator, opcode, but also html, httpd, mysql, xml, css, js ... any kinds of caches. Of course some parts should be cached and dynamic parts like blog answers shouldn't. Some should be requested over AJAX with generated urls. JSON, hashbangs etc.

Then, you'd like to have any little component on your website to be accessed or managed only by certain users, so conceptually that plays a big role.

Also you'd like to make statistics, maybe have distributed system / a facebook of facebooks etc. any software to be built on top of your over the top cms ... so you need different type of databases inmemory, bigdata, xml, whatsoever.

well, I think thats enough for now. If you haven't heard of either typo3 / plone or mentioned frameworks, you have enough to study. On that path you'll find a lot of solutions for questions you haven't asked yet.

If then you think, lets make a new CMS because its 2013 and php is about to die anyway, then you r welcome to join any other group of developers hopefully not getting lost.

Good luck!

And btw. how about people will not having any websites anymore in the future? and we'll all be on google+? I hope developers become a little more creative and do something usefull(to not be assimilated by the borgle)

//// Edit /// Just a little thought for your existing application:

If you have a php mysql CMS and you wanted to embed multilang support. you could either use your table with an aditional column for any language or insert the translation with an object id and a language id in the same table or create an identical table for any language and insert objects there, then make a select union if you want to have them all displayed. For the database use utf8 general ci and of course in the front/backend use utf8 text/encoding. I have used url path segments for urls in the way you already explaned like

domain.org/en/about you can map the lang ID to your content table. anyway you need to have a map of parameters for your urls so you'd like to define a parameter to be mapped from a pathsegment in your URL that would be e.g.

domain.org/en/about/employees/IT/administrators/

lookup configuration

pageid| url

1 | /about/employees/../..

1 | /../about/employees../../

map parameters to url pathsegment ""

$parameterlist[lang] = array(0=>"nl",1=>"en"); // default nl if 0
$parameterlist[branch] = array(1=>"IT",2=>"DESIGN"); // default nl if 0
$parameterlist[employertype] = array(1=>"admin",1=>"engineer"); //could be a sql result 

$websiteconfig[]=$userwhatever;
$websiteconfig[]=$parameterlist;
$someparameterlist[] = array("branch"=>$someid);
$someparameterlist[] = array("employertype"=>$someid);
function getURL($someparameterlist){ 
// todo foreach someparameter lookup pathsegment 
return path;
}

per say, thats been covered already in upper post.

And to not forget, you'd need to "rewrite" the url to your generating php file that would in most cases be index.php

Can't load IA 32-bit .dll on a AMD 64-bit platform

Be sure you are setting PATH to Program Files (x86) not Program Files. That solved my problem.

window.history.pushState refreshing the browser

As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.

If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").

But this function is not intended to reload the browser.

All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).

For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.

Hence the need for the function

history.pushState({},"Results for `Cats`",'url.html?s=cats');

It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.

When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.

If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.

As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.

See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.

HTML table sort

Here is another library.

Changes required are -

  1. Add sorttable js

  2. Add class name sortable to table.

Click the table headers to sort the table accordingly:

_x000D_
_x000D_
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:0001</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:0002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:0003</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:0004</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:0005</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>
_x000D_
_x000D_
_x000D_

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

Add a CSS class to <%= f.submit %>

By default, Rails 4 uses the 'value' attribute to control the visible button text, so to keep the markup clean I would use

<%= f.submit :value => "Visible Button Text", :class => 'class_name' %>

What is the purpose of Looper and how to use it?

I will try to explain the purpose of looper class as simple as possible. With a normal thread of Java when the run method completes the execution we say the thread has done it's job and thread lives no longer after that. what if we want to execute more tasks throughout our program with that same thread which is not living anymore? Oh there is a problem now right? Yes because we want to execute more tasks but the thread in not alive anymore. It is where the Looper comes in to rescue us. Looper as the name suggests loops. Looper is nothing more than an infinite loop inside your thread. So, it keeps the thread alive for an infinite time until we explicitly calls quit() method. Calling quit() method on the infinitely alive thread will make the condition false in the infinite loop inside the thread thus, infinite loop will exit. so, the thread will die or will no longer be alive. And it's critical to call the quit() method on our Thread to which looper is attached otherwise they will be there in your system just like Zombies. So, for example if we want to create a background thread to do some multiple tasks over it. we will create a simple Java's thread and will use Looper class to prepare a looper and attach the prepared looper with that thread so that our thread can live as longer as we want them because we can always call quit() anytime whenever we want to terminate our thread. So our the looper will keep our thread alive thus we will be able to execute multiple tasks with the same thread and when we are done we will call quit() to terminate the thread. What if we want our Main thread or UI thread to display the results computed by the background thread or non-UI thread on some UI elements? for that purpose there comes in the concept of Handlers; via handlers we can do inter-process communication or say via handlers two threads can communicate with each other. So, the main thread will have an associated Handler and Background thread will communicate with Main Thread via that handler to get the task done of displaying the results computed by it on some UI elements on Main thread. I know I am explaining only theory here but try to understand the concept because understanding the concept in depth is very important. And I am posting a link below which will take you to a small video series about Looper, Handler and HandlerThread and I will highly recommend watching it and all these concepts will get cleared with examples there.

https://www.youtube.com/watch?v=rfLMwbOKLRk&list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2&index=1

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

ImportError: No module named - Python

Make sure if root project directory is coming up in sys.path output. If not, please add path of root project directory to sys.path.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I also received this error and tried everything I could find online and it wouldn't go away. In the end, I just downgraded MVC from 5.2.3 to 4.0.40804. I don't like this solution because eventually I'll need to use MVC 5, but it works for now. Hope this helps others.

Start index for iterating Python list

If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):

dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 
            'Friday', 'Saturday',  ]

startDayName = 'Monday'

startIndex = dayNames.index( startDayName )
print ( startIndex )

rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]

for x in rotatedDayNames:
    print ( x )

ExpressionChangedAfterItHasBeenCheckedError Explained

Update

I highly recommend starting with the OP's self response first: properly think about what can be done in the constructor vs what should be done in ngOnChanges().

Original

This is more a side note than an answer, but it might help someone. I stumbled upon this problem when trying to make the presence of a button depend on the state of the form:

<button *ngIf="form.pristine">Yo</button>

As far as I know, this syntax leads to the button being added and removed from the DOM based on the condition. Which in turn leads to the ExpressionChangedAfterItHasBeenCheckedError.

The fix in my case (although I don't claim to grasp the full implications of the difference), was to use display: none instead:

<button [style.display]="form.pristine ? 'inline' : 'none'">Yo</button>

jQuery scrollTop not working in Chrome but working in Firefox

A better way to solve this problem is to use a function like this:

function scrollToTop(callback, q) {

    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, function() {
            console.log('html scroll');
            callback(q)
        });
        return;
    }

    if ($('body').scrollTop()) {
        $('body').animate({ scrollTop: 0 }, function() {
            console.log('body scroll');
            callback(q)
        });
        return;
    }

    callback(q);
}

This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");).

How may I reference the script tag that loaded the currently-executing script?

I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.

//handle on-demand loading of javascripts
makescript = function(url){
    var v = document.createElement('script');
    v.src=url;
    v.type='text/javascript';

    //insertAfter. Get last <script> tag in DOM
    d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
    d.parentNode.insertBefore( v, d.nextSibling );
}

How to hide html source & disable right click and text copy?

View source is not disabled in my browser (Chrome).

But they have added a lot of blank lines to the source, so you have to scroll down to view it. Try to scroll down and you will see.

the disabled right click is possible with javascript, but dont do it. Its very irritating for the user.

Adding placeholder text to textbox

This is not my code, but I use it a lot and it works perfect... XAML ONLY

<TextBox x:Name="Textbox" Height="23" Margin="0,17,18.8,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" HorizontalAlignment="Right" ></TextBox>

<TextBlock x:Name="Placeholder" IsHitTestVisible="False" TextWrapping="Wrap" Text="Placeholder Text" VerticalAlignment="Top" Margin="0,20,298.8,0" Foreground="DarkGray" HorizontalAlignment="Right" Width="214">
  <TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Visibility" Value="Collapsed"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Text, ElementName=Textbox}" Value="">
          <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>
</TextBlock>

How to hide app title in android?

You can do it programatically: Or without action bar

//It's enough to remove the line
     requestWindowFeature(Window.FEATURE_NO_TITLE);

//But if you want to display  full screen (without action bar) write too

     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     WindowManager.LayoutParams.FLAG_FULLSCREEN);

     setContentView(R.layout.your_activity);

MongoDB running but can't connect using shell

On Ubuntu:

Wed Jan 27 10:21:32 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84 exception: connect failed

Solution

look for if mongodb is running by following command:

ps -ef | grep mongo

If mongo is not running you get:

 vimal     1806  1698  0 10:11 pts/0    00:00:00 grep --color=auto mongo

You are seeing that the mongo daemon is not there.

Then start it through configuration file(with root priev):

root@vimal:/data# mongod --config /etc/mongodb.conf &
[1] 2131
root@vimal:/data# all output going to: /var/log/mongodb/mongodb.log

you can see the other details:

root@vimal:~# more /etc/mongodb.conf

Open a new terminal to see the result of mongod --config /etc/mongodb.conf & then type mongo. It should be running or grep

root@vimal:/data# ps -ef | grep mongo

root      3153     1  2 11:39 ?        00:00:23 mongod --config /etc/mongodb.conf
root      3772  3489  0 11:55 pts/1    00:00:00 grep --color=auto mongo 

NOW

root@vimal:/data# mongo

MongoDB shell version: 2.0.4
connecting to: test

you get the mongoDB shell

This is not the end of story. I will post the repair method so that it starts automatically every time, most development machine shutdowns every day and the VM must have mongo started automatically at next boot.

Spring Could not Resolve placeholder

If your config file is in a different path than classpath, you can add the configuration file path as a system property:

java -Dapp.config.path=path_to_config_file -jar your.jar

What is the official "preferred" way to install pip and virtualenv systemwide?

I use get-pip and virtualenv-burrito to install all this. Not sure if python-setuptools is required.

# might be optional. I install as part of my standard ubuntu setup script
sudo apt-get -y install python-setuptools

# install pip (using get-pip.py from pip contrib)
curl -O https://raw.github.com/pypa/pip/develop/contrib/get-pip.py && sudo python get-pip.py

# one-line virtualenv and virtualenvwrapper using virtualenv-burrito
curl -s https://raw.github.com/brainsik/virtualenv-burrito/master/virtualenv-burrito.sh | bash

MySQL "Group By" and "Order By"

I struggled with both these approaches for more complex queries than those shown, because the subquery approach was horribly ineficient no matter what indexes I put on, and because I couldn't get the outer self-join through Hibernate

The best (and easiest) way to do this is to group by something which is constructed to contain a concatenation of the fields you require and then to pull them out using expressions in the SELECT clause. If you need to do a MAX() make sure that the field you want to MAX() over is always at the most significant end of the concatenated entity.

The key to understanding this is that the query can only make sense if these other fields are invariant for any entity which satisfies the Max(), so in terms of the sort the other pieces of the concatenation can be ignored. It explains how to do this at the very bottom of this link. http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

If you can get am insert/update event (like a trigger) to pre-compute the concatenation of the fields you can index it and the query will be as fast as if the group by was over just the field you actually wanted to MAX(). You can even use it to get the maximum of multiple fields. I use it to do queries against multi-dimensional trees expresssed as nested sets.

HTML5 Email Validation

It is very difficult to validate Email correctly simply using HTML5 attribute "pattern". If you do not use a "pattern" someone@ will be processed. which is NOT valid email.

Using pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" will require the format to be [email protected] however if the sender has a format like [email protected] (or similar) will not be validated to fix this you could put pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" this will validate ".com.au or .net.au or alike.

However using this, it will not permit [email protected] to validate. So as far as simply using HTML5 to validate email addresses is still not totally with us. To Complete this you would use something like this:

<form>
<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<br>
<input type="submit" value="Submit The Form">
</form>

or:

<form>
<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<br>
<input type="submit" value="Submit The Form">
</form>

However, I do not know how to validate both or all versions of email addresses using HTML5 pattern attribute.

How to connect to a secure website using SSL in Java with a pkcs12 file?

The following steps will help you to sort your problem out.

Steps: developer_identity.cer <= download from Apple mykey.p12 <= Your private key

Commands to follow:

    openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM

    openssl pkcs12 -nocerts -in mykey.p12 -out mykey.pem

    openssl pkcs12 -export -inkey mykey.pem -in developer_identity.pem -out iphone_dev.p12

Final p12 that we will require is iphone_dev.p12 file and the passphrase.

use this file as your p12 and then try. This indeed is the solution.:)

What's the difference between '$(this)' and 'this'?

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

How to remove duplicates from Python list and keep order?

If it's clarity you're after, rather than speed, I think this is very clear:

def sortAndUniq(input):
  output = []
  for x in input:
    if x not in output:
      output.append(x)
  output.sort()
  return output

It's O(n^2) though, with the repeated use of not in for each element of the input list.

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Delete specific line from a text file?

If the line you want to delete is based on the content of the line:

string line = null;
string line_to_delete = "the line i want to delete";

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            if (String.Compare(line, line_to_delete) == 0)
                continue;

            writer.WriteLine(line);
        }
    }
}

Or if it is based on line number:

string line = null;
int line_number = 0;
int line_to_delete = 12;

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            line_number++;

            if (line_number == line_to_delete)
                continue;

            writer.WriteLine(line);
        }
    }
}

java.lang.IllegalArgumentException: No converter found for return value of type

The problem was that one of the nested objects in Foo didn't have any getter/setter

Best practice to return errors in ASP.NET Web API

ASP.NET Web API 2 really simplified it. For example, the following code:

public HttpResponseMessage GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        var message = string.Format("Product with id = {0} not found", id);
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

returns the following content to the browser when the item is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51

{
  "Message": "Product with id = 12 not found"
}

Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)

Links:

How do you create a static class in C++?

One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.

class Class {
 public:
  void foo() { Static::bar(*this); }    

 private:
  int member{0};
  friend class Static;
};    

class Static {
 public:
  template <typename T>
  static void bar(T& t) {
    t.member = 1;
  }
};

How to make a variadic macro (variable number of arguments)

I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.

#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))

Accessing value inside nested dictionaries

No, those are nested dictionaries, so that is the only real way (you could use get() but it's the same thing in essence). However, there is an alternative. Instead of having nested dictionaries, you can use a tuple as a key instead:

tempDict = {("ONE", "TWO", "THREE"): 10}
tempDict["ONE", "TWO", "THREE"]

This does have a disadvantage, there is no (easy and fast) way of getting all of the elements of "TWO" for example, but if that doesn't matter, this could be a good solution.

dropdownlist set selected value in MVC3 Razor

To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.

ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");

Async/Await Class Constructor

The other answers are missing the obvious. Simply call an async function from your constructor:

constructor() {
    setContentAsync();
}

async setContentAsync() {
    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
}

JVM option -Xss - What does it do exactly?

Each thread in a Java application has its own stack. The stack is used to hold return addresses, function/method call arguments, etc. So if a thread tends to process large structures via recursive algorithms, it may need a large stack for all those return addresses and such. With the Sun JVM, you can set that size via that parameter.

Delete from two tables in one query

DELETE a.*, b.* 
FROM messages a 
LEFT JOIN usersmessages b 
ON b.messageid = a.messageid 
WHERE a.messageid = 1

translation: delete from table messages where messageid =1, if table uersmessages has messageid = messageid of table messages, delete that row of uersmessages table.

Which loop is faster, while or for?

Some optimizing compilers will be able to do better loop unrolling with a for loop, but odds are that if you're doing something that can be unrolled, a compiler smart enough to unroll it is probably also smart enough to interpret the loop condition of your while loop as something it can unroll as well.

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion



    public new void Clear()
    {
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;


        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);


    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

Linux : Search for a Particular word in a List of files under a directory

You can use this command:

grep -rn "string" *

n for showing line number with the filename r for recursive

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

Html table tr inside td

_x000D_
_x000D_
<table border="1px;" width="100%">
  <tr align="center">
    <td>Product</td>
    <td>quantity</td>
    <td>Price</td>
    <td>Totall</td>
  </tr>
  <tr align="center">
    <td>Item-1</td>
    <td>Item-1</td>
    <td>
      <table border="1px;" width="100%">
        <tr align="center">
          <td>Name1</td>
          <td>Price1</td>
        </tr>
        <tr align="center">
          <td>Name2</td>
          <td>Price2</td>
        </tr>
        <tr align="center">
          <td>Name3</td>
          <td>Price3</td>
        </tr>
        <tr>
          <td>Name4</td>
          <td>Price4</td>
        </tr>
      </table>
    </td>
    <td>Item-1</td>
  </tr>
  <tr align="center">
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
  </tr>
  <tr align="center">
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

How to use addTarget method in swift 3

Instead of

let loginRegisterButton:UIButton = {
//...  }()

Try:

lazy var loginRegisterButton:UIButton = {
//...  }()

That should fix the compile error!!!

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Get current AUTO_INCREMENT value for any table

    Query to check percentage "usage" of AUTO_INCREMENT for all tables of one given schema (except columns with type bigint unsigned):

    SELECT 
      c.TABLE_NAME,
      c.COLUMN_TYPE,
      c.MAX_VALUE,
      t.AUTO_INCREMENT,
      IF (c.MAX_VALUE > 0, ROUND(100 * t.AUTO_INCREMENT / c.MAX_VALUE, 2), -1) AS "Usage (%)" 
    FROM 
      (SELECT 
         TABLE_SCHEMA,
         TABLE_NAME,
         COLUMN_TYPE,
         CASE 
            WHEN COLUMN_TYPE LIKE 'tinyint(1)' THEN 127
            WHEN COLUMN_TYPE LIKE 'tinyint(1) unsigned' THEN 255
            WHEN COLUMN_TYPE LIKE 'smallint(%)' THEN 32767
            WHEN COLUMN_TYPE LIKE 'smallint(%) unsigned' THEN 65535
            WHEN COLUMN_TYPE LIKE 'mediumint(%)' THEN 8388607
            WHEN COLUMN_TYPE LIKE 'mediumint(%) unsigned' THEN 16777215
            WHEN COLUMN_TYPE LIKE 'int(%)' THEN 2147483647
            WHEN COLUMN_TYPE LIKE 'int(%) unsigned' THEN 4294967295
            WHEN COLUMN_TYPE LIKE 'bigint(%)' THEN 9223372036854775807
            WHEN COLUMN_TYPE LIKE 'bigint(%) unsigned' THEN 0
            ELSE 0
         END AS "MAX_VALUE" 
       FROM 
         INFORMATION_SCHEMA.COLUMNS
         WHERE EXTRA LIKE '%auto_increment%'
       ) c
    
       JOIN INFORMATION_SCHEMA.TABLES t ON (t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME)
    
    WHERE
     c.TABLE_SCHEMA = 'YOUR_SCHEMA' 
    ORDER BY
     `Usage (%)` DESC;
    

    How to call base.base.method()?

    public class A
    {
        public int i = 0;
        internal virtual void test()
        {
            Console.WriteLine("A test");
        }
    }
    
    public class B : A
    {
        public new int i = 1;
        public new void test()
        {
            Console.WriteLine("B test");
        }
    }
    
    public class C : B
    {
        public new int i = 2;
        public new void test()
        {
            Console.WriteLine("C test - ");
            (this as A).test(); 
        }
    }
    

    In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

    I have run through this. My case was more involved. The project was packaged fine from maven command line.

    Couple of things I made. 1. One class has many imports that confused eclipse. Cleaning them fixed part of the problem 2. One case was about a Setter, pressing F3 navigating to that Setter although eclipse complained it is not there. So I simply retyped it and it worked fine (even for all other Setters)

    I am still struggling with Implicit super constructor Item() is undefined for default constructor. Must define an explicit constructor"

    How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

    In general I would recommend against calling the event handlers 'manually'.

    • It's unclear what gets executed because of multiple registered listeners
    • Danger to get into a recursive and infinite event-loop (click A triggering Click B, triggering click A, etc.)
    • Redundant updates to the DOM
    • Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).

    Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.

    Use formula in custom calculated field in Pivot Table

    Some of it is possible, specifically accessing subtotals:

    "In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

    enter image description here

    • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

    Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

    ImportError: No module named 'MySQL'

    You need to use one of the following commands. Which one depends on different-2 OS and software you have and use.

    sudo easy_install mysql-python (mix os)
    sudo pip install mysql-python (mix os)
    sudo apt-get install python-mysqldb (Linux Ubuntu, ...)
    cd /usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
    yum install MySQL-python (Linux Fedora, CentOS ...)
    

    How to get javax.comm API?

    Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

    Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

    Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

    Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

    In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

    Check Whether a User Exists

    Script to Check whether Linux user exists or not

    Script To check whether the user exists or not

    #! /bin/bash
    USER_NAME=bakul
    cat /etc/passwd | grep ${USER_NAME} >/dev/null 2>&1
    if [ $? -eq 0 ] ; then
        echo "User Exists"
    else
        echo "User Not Found"
    fi
    

    what is the difference between ajax and jquery and which one is better?

    On StackOverflow, pressing the up-vote button is AJAX whereas typing in your question or answer and seeing it appear in the real-time preview window below it is JavaScript (JQuery).

    This means that the difference between AJAX and Javascript is that AJAX allows you to communicate with the server without doing a page refresh (i.e. going to a new page) whereas JavaScript (JQuery) allows you to embed logic and behaviour on your page. Of course, with this logic you create AJAX as well.

    How to properly compare two Integers in Java?

    tl;dr my opinion is to use a unary + to trigger the unboxing on one of the operands when checking for value equality, and simply use the maths operators otherwise. Rationale follows:

    It has been mentioned already that == comparison for Integer is identity comparison, which is usually not what a programmer want, and that the aim is to do value comparison; still, I've done a little science about how to do that comparison most efficiently, both in term of code compactness, correctness and speed.

    I used the usual bunch of methods:

    public boolean method1() {
        Integer i1 = 7, i2 = 5;
        return i1.equals( i2 );
    }
    
    public boolean method2() {
        Integer i1 = 7, i2 = 5;
        return i1.intValue() == i2.intValue();
    }
    
    public boolean method3() {
        Integer i1 = 7, i2 = 5;
        return i1.intValue() == i2;
    }
    
    public boolean method4() {
        Integer i1 = 7, i2 = 5;
        return i1 == +i2;
    }
    
    public boolean method5() { // obviously not what we want..
        Integer i1 = 7, i2 = 5;
        return i1 == i2;
    }
    

    and got this code after compilation and decompilation:

    public boolean method1() {
        Integer var1 = Integer.valueOf( 7 );
        Integer var2 = Integer.valueOf( 5 );
    
        return var1.equals( var2 );
    }
    
    public boolean method2() {
        Integer var1 = Integer.valueOf( 7 );
        Integer var2 = Integer.valueOf( 5 );
    
        if ( var2.intValue() == var1.intValue() ) {
            return true;
        } else {
            return false;
        }
    }
    
    public boolean method3() {
        Integer var1 = Integer.valueOf( 7 );
        Integer var2 = Integer.valueOf( 5 );
    
        if ( var2.intValue() == var1.intValue() ) {
            return true;
        } else {
            return false;
        }
    }
    
    public boolean method4() {
        Integer var1 = Integer.valueOf( 7 );
        Integer var2 = Integer.valueOf( 5 );
    
        if ( var2.intValue() == var1.intValue() ) {
            return true;
        } else {
            return false;
        }
    }
    
    public boolean method5() {
        Integer var1 = Integer.valueOf( 7 );
        Integer var2 = Integer.valueOf( 5 );
    
        if ( var2 == var1 ) {
            return true;
        } else {
            return false;
        }
    }
    

    As you can easily see, method 1 calls Integer.equals() (obviously), methods 2-4 result in exactly the same code, unwrapping the values by means of .intValue() and then comparing them directly, and method 5 just triggers an identity comparison, being the incorrect way to compare values.

    Since (as already mentioned by e.g. JS) equals() incurs an overhead (it has to do instanceof and an unchecked cast), methods 2-4 will work with exactly the same speed, noticingly better than method 1 when used in tight loops, since HotSpot is not likely to optimize out the casts & instanceof.

    It's quite similar with other comparison operators (e.g. </>) - they will trigger unboxing, while using compareTo() won't - but this time, the operation is highly optimizable by HS since intValue() is just a getter method (prime candidate to being optimized out).

    In my opinion, the seldom used version 4 is the most concise way - every seasoned C/Java developer knows that unary plus is in most cases equal to cast to int/.intValue() - while it may be a little WTF moment for some (mostly those who didn't use unary plus in their lifetime), it arguably shows the intent most clearly and most tersely - it shows that we want an int value of one of the operands, forcing the other value to unbox as well. It is also unarguably most similar to the regular i1 == i2 comparison used for primitive int values.

    My vote goes for i1 == +i2 & i1 > i2 style for Integer objects, both for performance & consistency reasons. It also makes the code portable to primitives without changing anything other than the type declaration. Using named methods seems like introducing semantic noise to me, similar to the much-criticized bigInt.add(10).multiply(-3) style.

    pip issue installing almost any library

    To install any other package I have to use the latest version of pip, since the 9.0.1 has this SSL problem. To upgrade the pip by pip itself, I have to solve this SSL problem first. To jump out of this endless loop, I find this only way that works for me.

    1. Find the latest version of pip in this page: https://pypi.org/simple/pip/
    2. Download the .whl file of the latest version.
    3. Use pip to install the latest pip. (Use your own latest version here)

    sudo pip install pip-10.0.1-py2.py3-none-any.whl

    Now the pip is the latest version and can install anything.

    How do you know if Tomcat Server is installed on your PC

    In case of Windows(in my case XP):-

    1. Check the directory where tomcat is installed.
    2. Open the directory called \conf in it.
    3. Then search file server.xml
    4. Open that file and check what is the connector port for HTTP,whre you will found something like 8009,8080 etc.
    5. Suppose it found 8009,use that port as "/localhost:8009/" in your web-browser with HTTP protocol. Hope this will work !

    How do you revert to a specific tag in Git?

    Use git reset:

    git reset --hard "Version 1.0 Revision 1.5"
    

    (assuming that the specified string is the tag).

    gson throws MalformedJsonException

    I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

    GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

    If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader(result1));
    reader.setLenient(true);
    Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
    

    How to use cURL to send Cookies?

    If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..

    Make A List Item Clickable (HTML/CSS)

    The li element supports an onclick event.

    <ul>
    <li onclick="location.href = 'http://stackoverflow.com/questions/3486110/make-a-list-item-clickable-html-css';">Make A List Item Clickable</li>
    </ul>
    

    TypeError: list indices must be integers or slices, not str

    First, array_length should be an integer and not a string:

    array_length = len(array_dates)
    

    Second, your for loop should be constructed using range:

    for i in range(array_length):  # Use `xrange` for python 2.
    

    Third, i will increment automatically, so delete the following line:

    i += 1
    

    Note, one could also just zip the two lists given that they have the same length:

    import csv
    
    dates = ['2020-01-01', '2020-01-02', '2020-01-03']
    urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']
    
    csv_file_patch = '/path/to/filename.csv'
    
    with open(csv_file_patch, 'w') as fout:
        csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
        result_array = zip(dates, urls)
        csv_file.writerows(result_array)
    

    Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

    Inspired by cyptus's answer I used

    _dbContext.Database.CreateIfNotExists();
    

    on EF6 before the first database contact (before DB seeding).

    How to get current route in react-router 2.0.0-rc5

    In App.js add the below code and try

    window.location.pathname
    

    How to store NULL values in datetime fields in MySQL?

    I just discovered that MySQL will take null provided the default for the field is null and I write specific if statements and leave off the quotes. This works for update as well.

    if(empty($odate) AND empty($ddate))
    {
      $query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
    };
    

    How do I pull my project from github?

    Run these commands:

    cd /pathToYourLocalProjectFolder
    
    git pull origin master
    

    When to use static methods

    A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.

    Consider the following example:

     class Languages 
     {
         public static void main(String[] args) 
         {
             display();
         }
    
         static void display() 
         {
             System.out.println("Java is my favorite programming language.");
         }
      }
    

    How do I find out what all symbols are exported from a shared object?

    If it is a Windows DLL file and your OS is Linux then use winedump:

    $ winedump -j export pcre.dll
    
    Contents of pcre.dll: 229888 bytes
    
    Exports table:
    
      Name:            pcre.dll
      Characteristics: 00000000
      TimeDateStamp:   53BBA519 Tue Jul  8 10:00:25 2014
      Version:         0.00
      Ordinal base:    1
      # of functions:  31
      # of Names:      31
    Addresses of functions: 000375C8
    Addresses of name ordinals: 000376C0
    Addresses of names: 00037644
    
      Entry Pt  Ordn  Name
      0001FDA0     1 pcre_assign_jit_stack
      000380B8     2 pcre_callout
      00009030     3 pcre_compile
    ...
    

    ng-repeat finish event

    i would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.

    but in my experience, as the OP states, its usually running some JQuery plugins or methods on the finnaly compiled DOM, which in that case i found that the most simple solution is to create a directive with a setTimeout, since the setTimeout function gets pushed to the end of the queue of the browser, its always right after everything is done in angular, usually ngReapet which continues after its parents postLinking function

    angular.module('myApp', [])
    .directive('pluginNameOrWhatever', function() {
      return function(scope, element, attrs) {        
        setTimeout(function doWork(){
          //jquery code and plugins
        }, 0);        
      };
    });
    

    for whoever wondering that in that case why not to use $timeout, its that it causes another digest cycle that is completely unnecessary

    NSDictionary - Need to check whether dictionary contains key-value pair or not

    Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

    if ([xyz objectForKey:@"b"]) {
        NSLog(@"There's an object set for key @\"b\"!");
    } else {
        NSLog(@"No object set for key @\"b\"");
    }
    

    Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

    How to use JavaScript to change the form action

    I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

    I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

    To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

    function setAction (element, page)
    {
      if(checkCondition(page))
      {
        /* Insert a hidden input into the form to set the page as a parameter.
         */
        var input = document.createElement("input");
        input.setAttribute("type","hidden");
        input.setAttribute("name","page");
        input.setAttribute("value",page);
        element.form.appendChild(input);
    
        /* Change the form's action. This doesn't chage which page is displayed,
         * it just make the URL look right.
         */
        element.form.action = '/' + page;
        element.form.submit();
      }
    }
    

    In the form:

    <input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
    

    Here are my Apache rewrite rules:

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
    RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
    

    I'd be interested in any explanation as to why just setting the action didn't work.

    Start an Activity with a parameter

    The existing answers (pass the data in the Intent passed to startActivity()) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent which launches the Activity.

    You can create a base-class Activity that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:

    class BaseActivity extends Activity
    {
        public BaseActivity(String param)
        {
            // Do something with param
        }
    }
    
    class DerivedActivity extends BaseActivity
    {
        public DerivedActivity()
        {
            super("parameter");
        }
    }
    

    If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.

    Comprehensive beginner's virtualenv tutorial?

    Here's another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

    This one shows how to use pip and a pip requirements file with virtualenv; Scobal's two suggested tutorials are both very helpful but are both easy_install-centric.

    Note that none of these tutorials explain how to run a different version of Python within a virtualenv - for this, see this SO question: Use different Python version with virtualenv

    How does BitLocker affect performance?

    I am talking here from a theoretical point of view; I have not tried BitLocker.

    BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.

    However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).

    (*) Here I assume that Microsoft's developers did their job properly.

    Detect if user is scrolling

    If you want detect when user scroll over certain div, you can do something like this:

    window.onscroll = function() {
        var distanceScrolled = document.documentElement.scrollTop;
        console.log('Scrolled: ' + distanceScrolled);
    }
    

    For example, if your div appear after scroll until the position 112:

    window.onscroll = function() {
        var distanceScrolled = document.documentElement.scrollTop;
        if (distanceScrolled > 112) {
          do something...
        }
    }
    

    But as you can see you don't need a div, just the offset distance you want something to happen.

    Facebook Graph API, how to get users email?

    Just add these code block on status return, and start passing a query string object {}. For JavaScript devs

    After initializing your sdk.

    step 1: // get login status

    $(document).ready(function($) {
        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
            console.log(response);
        });
      });
    

    This will check on document load and get your login status check if users has been logged in.

    Then the function checkLoginState is called, and response is pass to statusChangeCallback

    function checkLoginState() {
        FB.getLoginStatus(function(response) {
          statusChangeCallback(response);
        });
      }
    

    Step 2: Let you get the response data from the status

    function statusChangeCallback(response) {
        // body...
        if(response.status === 'connected'){
          // setElements(true);
          let userId = response.authResponse.userID;
          // console.log(userId);
          console.log('login');
          getUserInfo(userId);
    
        }else{
          // setElements(false);
          console.log('not logged in !');
        }
      }
    

    This also has the userid which is being set to variable, then a getUserInfo func is called to fetch user information using the Graph-api.

    function getUserInfo(userId) {
        // body...
        FB.api(
          '/'+userId+'/?fields=id,name,email',
          'GET',
          {},
          function(response) {
            // Insert your code here
            // console.log(response);
            let email = response.email;
            loginViaEmail(email);
          }
        );
      }
    

    After passing the userid as an argument, the function then fetch all information relating to that userid. Note: in my case i was looking for the email, as to allowed me run a function that can logged user via email only.

    // login via email

    function loginViaEmail(email) {
        // body...
        let token = '{{ csrf_token() }}';
    
        let data = {
          _token:token,
          email:email
        }
    
        $.ajax({
          url: '/login/via/email',    
          type: 'POST',
          dataType: 'json',
          data: data,
          success: function(data){
            console.log(data);
            if(data.status == 'success'){
              window.location.href = '/dashboard';
            }
    
            if(data.status == 'info'){
              window.location.href = '/create-account'; 
            }
          },
          error: function(data){
            console.log('Error logging in via email !');
            // alert('Fail to send login request !');
          }
        });
      }
    

    Change directory in PowerShell

    You can simply type Q: and that should solve your problem.

    String "true" and "false" to boolean

    I'm surprised no one posted this simple solution. That is if your strings are going to be "true" or "false".

    def to_boolean(str)
        eval(str)
    end
    

    How do I check if there are duplicates in a flat list?

    I found this to do the best performance because it short-circuit the operation when the first duplicated it found, then this algorithm has time and space complexity O(n) where n is the list's length:

    def has_duplicated_elements(iterable):
        """ Given an `iterable`, return True if there are duplicated entries. """
        clean_elements_set = set()
        clean_elements_set_add = clean_elements_set.add
    
        for possible_duplicate_element in iterable:
    
            if possible_duplicate_element in clean_elements_set:
                return True
    
            else:
                clean_elements_set_add( possible_duplicate_element )
    
        return False
    

    What is the string concatenation operator in Oracle?

    Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

    My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

    CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD
    

    How different is Scrum practice from Agile Practice?

    As mentioned Agile is a set of principles about how a methodology should be implemented to achieve the benefits of embracing change, close co-operation etc. These principles address some of the project management issues found in studies such as the Chaos Report by the Standish group.

    Agile methodologies are created by the development and supporting teams to meet the principles. The methodology is made to fit the business and changed as appropriate.

    SCRUM is a fixed set of processes to implement an incremental development methodology. Since the processes are fixed and not catered to the teams it cannot really be considered agile in the original sense of focus on individuals rather than processes.

    D3.js: How to get the computed width and height for an arbitrary element?

    Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:

    function computeDimensions(selection) {
      var dimensions = null;
      var node = selection.node();
    
      if (node instanceof SVGGraphicsElement) { // check if node is svg element
        dimensions = node.getBBox();
      } else { // else is html element
        dimensions = node.getBoundingClientRect();
      }
      console.log(dimensions);
      return dimensions;
    }
    

    Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.

    _x000D_
    _x000D_
    var svg = d3.select('svg')
      .attr('width', 50)
      .attr('height', 50);
    
    function computeDimensions(selection) {
        var dimensions = null;
      var node = selection.node();
    
      if (node instanceof SVGElement) {
        dimensions = node.getBBox();
      } else {
        dimensions = node.getBoundingClientRect();
      }
      console.clear();
      console.log(dimensions);
      return dimensions;
    }
    
    var circle = svg
        .append("circle")
        .attr("r", 20)
        .attr("cx", 30)
        .attr("cy", 30)
        .attr("fill", "red")
        .on("click", function() { computeDimensions(circle); });
        
    var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
    _x000D_
    * {
      margin: 0;
      padding: 0;
      border: 0;
    }
    
    body {
      background: #ffd;
    }
    
    .div {
      display: inline-block;
      background-color: blue;
      margin-right: 30px;
      width: 30px;
      height: 30px;
    }
    _x000D_
    <h3>
      Click on blue div block or svg circle
    </h3>
    <svg></svg>
    <div class="div"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

    Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip

    Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths

    1. Xcode.app/Contents/Info.plist
    2. Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist

    Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild from Xcode 10

    ****OR*****

    you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip

    And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

    Note: Restart the Xcode

    How to clear the cache of nginx?

    There is one right method to remove only cache-files, which matches any KEY. For example:

    grep -lr 'KEY: yahoo' /var/lib/nginx/cache | xargs rm -rf
    

    This removes all cache-files, which matches to KEY "yahoo/*", if in nginx.conf was set:

    proxy_cache_key $host$uri;
    

    github: server certificate verification failed

    Try to connect to repositroy with url: http://github.com/<user>/<project>.git (http except https)

    In your case you should clone like this:

    git clone http://github.com/<user>/<project>.git
    

    What is char ** in C?

    It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

    How do you use a variable in a regular expression?

    If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b):

    re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
    

    Example:

    let inputString = "I'm John, or johnny, but I prefer john.";
    let replaceThis = "John";
    let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
    console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
    

    How to get a user's time zone?

    Swift 4, 4.2 & 5

    var timeZone : String = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        timeZone = getCurrentTimeZone()
        print(timeZone)
    }
    
    func getCurrentTimeZone() -> String {
            let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
            let items = (localTimeZoneAbbreviation / 3600)
            return "\(items)"
    }
    

    When to use single quotes, double quotes, and backticks in MySQL

    It is sometimes useful to not use quotes... because this can highlight issues in the code generating the query... For example:

    Where x and y are should always be integers...

    SELECT * FROM table WHERE x= AND y=0

    Is a SQL syntax error... a little lazy but can be useful...

    Javascript ajax call on page onload

    This is really easy using a JavaScript library, e.g. using jQuery you could write:

    $(document).ready(function(){
    $.ajax({ url: "database/update.html",
            context: document.body,
            success: function(){
               alert("done");
            }});
    });
    

    Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

    <html>
      <body onload="updateDB();">
      </body>
      <script language="javascript">
        function updateDB() {
          var xhr = new XMLHttpRequest();
          xhr.open("POST", "database/update.html", true);
          xhr.send(null);
          /* ignore result */
        }
      </script>
    </html>
    

    See also:

    How to append one file to another in Linux from the shell?

    You can also do this without cat, though honestly cat is more readable:

    >> file1 < file2

    The >> appends STDIN to file1 and the < dumps file2 to STDIN.

    How to make a dropdown readonly using jquery?

    It´s work very well

    $('#cf_1268591 option:not(:selected)').prop('disabled', true);
    

    With this I can see the options but I can't select it

    Convert int (number) to string with leading zeros? (4 digits)

    Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

    string text = no.ToString("0000");
    

    Setting focus on an HTML input box on page load

    And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

    <input type="text" name="fname" autofocus>
    

    Convert date yyyyMMdd to system.datetime format

    string time = "19851231";
    DateTime theTime= DateTime.ParseExact(time,
                                            "yyyyMMdd",
                                            CultureInfo.InvariantCulture,
                                            DateTimeStyles.None);
    

    PHP float with 2 decimal places: .00

    You can show float numbers

    • with a certain number of decimals
    • with a certain format (localised)

    i.e.

    $myNonFormatedFloat = 5678.9
    
    $myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90
    
    $myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90 
    

    Note that, the

    1st argument is the float number you would like to format

    2nd argument is the number of decimals

    3rd argument is the character used to visually separate the decimals

    4th argument is the character used to visually separate thousands

    Difference between except: and except Exception as e: in Python

    Using the second form gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

    Merge development branch with master

    If you are on Mac or Ubuntu, go to the working folder of the branch. In the terminal

    suppose harisdev is the branchname.

    git checkout master
    

    if there are untracked or uncommitted files you will get an error and you have to commit or delete all the untracked or uncommitted files.

    git merge harisdev 
    
    git push origin master
    

    One last command to delete the branch.

    $ git branch -d harisdev
    

    MySQL FULL JOIN?

    SELECT  p.LastName, p.FirstName, o.OrderNo
    FROM    persons AS p
    LEFT JOIN
            orders AS o
    ON      o.orderNo = p.p_id
    UNION ALL
    SELECT  NULL, NULL, orderNo
    FROM    orders
    WHERE   orderNo NOT IN
            (
            SELECT  p_id
            FROM    persons
            )
    

    How to solve javax.net.ssl.SSLHandshakeException Error?

    I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

    ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

    Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

    In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

    I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

    P.S I cant get source code before the weekend since external SSH is disabled in my office :(

    django admin - add custom form fields that are not part of the model

    If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:

    I never done something like this so I'm not completely sure how it will work out.

    Creating a PDF from a RDLC Report in the Background

    You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

    var lr = new LocalReport
    {
        ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
        EnableExternalImages = true
    };
    
    lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
    
    string mimeType, encoding, extension;
    
    Warning[] warnings;
    string[] streams;
    var renderedBytes = lr.Render
        (
            "PDF",
            @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
            out mimeType,
            out encoding,
            out extension,
            out streams,
            out warnings
        );
    
    var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
    
    var idx = 0;
    while (File.Exists(saveAs))
    {
        idx++;
        saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
    }
    
    using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
    {
        stream.Write(renderedBytes, 0, renderedBytes.Length);
        stream.Close();
    }
    
    lr.Dispose();
    

    You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

    Can't append <script> element

    <script>
        ...
        ...jQuery("<script></script>")...
        ...
    </script>
    

    The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.

    Facebook page automatic "like" URL (for QR Code)

    I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.

    You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.

    CSS: background-color only inside the margin

    That is not possible du to the Box Model. However you could use a workaround with css3's border-image, or border-color in general css.

    However im unsure whether you may have a problem with resetting. Some browsers do set a margin to html as well. See Eric Meyers Reset CSS for more!

    html{margin:0;padding:0;}
    

    Inner Joining three tables

    select *
    from
        tableA a
            inner join
        tableB b
            on a.common = b.common
            inner join 
        TableC c
            on b.common = c.common
    

    Highcharts - how to have a chart with dynamic height?

    Remove the height will fix your problem because highchart is responsive by design if you adjust your screen it will also re-size.

    AngularJS Directive Restrict A vs E

    According to the documentation:

    When should I use an attribute versus an element? Use an element when you are creating a component that is in control of the template. The common case for this is when you are creating a Domain-Specific Language for parts of your template. Use an attribute when you are decorating an existing element with new functionality.

    Edit following comment on pitfalls for a complete answer:

    Assuming you're building an app that should run on Internet Explorer <= 8, whom support has been dropped by AngularJS team from AngularJS 1.3, you have to follow the following instructions in order to make it working: https://docs.angularjs.org/guide/ie

    How to stop an animation (cancel() does not work)

    Call clearAnimation() on whichever View you called startAnimation().

    How do I write a Windows batch script to copy the newest file from a directory?

    The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

    FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I
    

    Now you can reference %NewestFile% throughout the rest of your bat file.

    For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

    :Variables
    SET DatabaseBackupPath=\\virtualserver1\Database Backups
    
    echo.
    echo Restore WebServer Database
    FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
    copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"
    
    sqlcmd -U <username> -P <password> -d master -Q ^
    "RESTORE DATABASE [ExampleDatabaseName] ^
    FROM  DISK = N'D:\%NewestFile%' ^
    WITH  FILE = 1,  ^
    MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
    MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^
    NOUNLOAD,  STATS = 10"
    

    jquery datatables hide column

    Hide columns dynamically

    The previous answers are using legacy DataTables syntax. In v 1.10+, you can use column().visible():

    var dt = $('#example').DataTable();
    //hide the first column
    dt.column(0).visible(false);
    

    To hide multiple columns, columns().visible() can be used:

    var dt = $('#example').DataTable();
    //hide the second and third columns
    dt.columns([1,2]).visible(false);
    

    Here is a Fiddle Demo.

    Hide columns when the table is initialized

    To hide columns when the table is initialized, you can use the columns option:

    $('#example').DataTable( {
        'columns' : [
            null,
            //hide the second column
            {'visible' : false },
            null,
            //hide the fourth column
            {'visible' : false }
        ]
    });
    

    For the above method, you need to specify null for columns that should remain visible and have no other column options specified. Or, you can use columnDefs to target a specific column:

    $('#example').DataTable( {
        'columnDefs' : [
            //hide the second & fourth column
            { 'visible': false, 'targets': [1,3] }
        ]
    });
    

    Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

    This issue is also observed for inconsistent settings.py for incorrectly writing INSTALLED_APPS, verify if you correctly included apps and separated with "," .

    How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

    I'd create a cte and do an inner join. It's not efficient but it's convenient

    with table as (
    SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
    OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
     FROM TABLE)
    
    select *
    
    from table t
    join select(
    max(Row_Num) as Row_Num
    ,DATE
    ,STATUS
    ,TITLE
    from table 
    group by date, status, title) t2  
    on t2.Row_Num = t.Row_Num and t2
    and t2.date = t.date
    and t2.title = t.title
    

    What is the difference between YAML and JSON?

    If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

    How to add double quotes to a string that is inside a variable?

    "<i class=\"fa fa-check-circle\"></i>" is used with ternary operator with Eval() data binding:

    Text = '<%# Eval("bqtStatus").ToString()=="Verified" ? 
           Convert.ToString("<i class=\"fa fa-check-circle\"></i>") : 
           Convert.ToString("<i class=\"fa fa-info-circle\"></i>"
    

    gcc warning" 'will be initialized after'

    Make sure the members appear in the initializer list in the same order as they appear in the class

    Class C {
       int a;
       int b;
       C():b(1),a(2){} //warning, should be C():a(2),b(1)
    }
    

    or you can turn -Wno-reorder

    REST / SOAP endpoints for a WCF service

    This is what i did to make it work. Make sure you put
    webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

    [ServiceContract]
    public interface ITestService
    {
    
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
        string GetData();
    }
    
    public class TestService : ITestService
    {
        public string GetJsonData()
        {
            return "I am good...";
        }
    }
    

    Inside service model

       <service name="TechCity.Business.TestService">
    
        <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
          bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
        <endpoint address="mex"
                  contract="IMetadataExchange" binding="mexHttpBinding"/>
        <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
                  name="Http" contract="TechCity.Interfaces.ITestService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8739/test" />
          </baseAddresses>
        </host>
      </service>
    

    EndPoint Behaviour

      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <webHttp automaticFormatSelectionEnabled="true"  />
          <!-- use JSON serialization -->
        </behavior>
      </endpointBehaviors>
    

    get current date and time in groovy?

    Date has the time part, so we only need to extract it from Date

    I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

    Date date = new Date()
    String datePart = date.format("dd/MM/yyyy")
    String timePart = date.format("HH:mm:ss")
    
    println "datePart : " + datePart + "\ttimePart : " + timePart
    

    SQL ORDER BY date problem

    Try using this this work for me

    select *  from `table_name` ORDER BY STR_TO_DATE(start_date,"%d-%m-%Y") ASC
    

    where start_date is the field name

    CSS content property: is it possible to insert HTML instead of Text?

    In CSS3 paged media this is possible using position: running() and content: element().

    Example from the CSS Generated Content for Paged Media Module draft:

    @top-center {
      content: element(heading); 
    }
    
    .runner { 
      position: running(heading);
    }
    

    .runner can be any element and heading is an arbitrary name for the slot.

    EDIT: to clarify, there is basically no browser support so this was mostly meant to be for future reference/in addition to the 'practical answers' given already.

    What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

    Reload the current page:
    F5
    or
    CTRL + R


    Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
    SHIFT + F5
    or
    CTRL + F5
    or
    CTRL + SHIFT + R

    How can I manually generate a .pyc file from a .py file

    In Python2 you could use:

    python -m compileall <pythonic-project-name>
    

    which compiles all .py files to .pyc files in a project which contains packages as well as modules.


    In Python3 you could use:

    python3 -m compileall <pythonic-project-name>
    

    which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

    Or with browning from this post:

    You can enforce the same layout of .pyc files in the folders as in Python2 by using:

    python3 -m compileall -b <pythonic-project-name>

    The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).

    Android: checkbox listener

    h.chk.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            CheckBox chk=(CheckBox)view; // important line and code work
            if(chk.isChecked())
            {
                Message.message(a,"Clicked at"+position);
            }
            else
            {
                Message.message(a,"UnClick");
            }
        }
    });
    

    Creating a JSON Array in node js

    You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

    Use JSON.stringify(object) to turn it into (a string of) JSON text.

    Adding event listeners to dynamically added elements using jQuery

    You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

    $('#musics').on('change', '#want',function(e) {
        $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
        var ans=$(this).val();
        console.log(($('#want').is(':checked')));
    });
    

    http://jsfiddle.net/swoogie/1rkhn7ek/39/

    Detailed 500 error message, ASP + IIS 7.5

    I have come to the same problem and fixed the same way as Alex K.

    So if "Send Errors To Browser" is not working set also this:

    Error Pages -> 500 -> Edit Feature Settings -> "Detailed Errors"

    enter image description here

    Also note that if the content of the error page sent back is quite short and you're using IE, IE will happily ignore the useful content sent back by the server and show you its own generic error page instead. You can turn this off in IE's options, or use a different browser.

    Why es6 react component works only with "export default"?

    Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

    exportimport { ... } from './Template'

    export defaultimport ... from './Template'


    Here is a working example:

    // ExportExample.js
    import React from "react";
    
    function DefaultExport() {
      return "This is the default export";
    }
    
    function Export1() {
      return "Export without default 1";
    }
    
    function Export2() {
      return "Export without default 2";
    }
    
    export default DefaultExport;
    export { Export1, Export2 };
    

    // App.js
    import React from "react";
    import DefaultExport, { Export1, Export2 } from "./ExportExample";
    
    export default function App() {
      return (
        <>
          <strong>
            <DefaultExport />
          </strong>
          <br />
          <Export1 />
          <br />
          <Export2 />
        </>
      );
    }
    

    ??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

    node.js execute system command synchronously

    you can do synchronous shell operations in nodejs like so:

    var execSync = function(cmd) {
    
        var exec  = require('child_process').exec;
        var fs = require('fs');
    
        //for linux use ; instead of &&
        //execute your command followed by a simple echo 
        //to file to indicate process is finished
        exec(cmd + " > c:\\stdout.txt && echo done > c:\\sync.txt");
    
        while (true) {
            //consider a timeout option to prevent infinite loop
            //NOTE: this will max out your cpu too!
            try {
                var status = fs.readFileSync('c:\\sync.txt', 'utf8');
    
                if (status.trim() == "done") {
                    var res = fs.readFileSync("c:\\stdout.txt", 'utf8');
                    fs.unlinkSync("c:\\stdout.txt"); //cleanup temp files
                    fs.unlinkSync("c:\\sync.txt");
                    return res;
                }
            } catch(e) { } //readFileSync will fail until file exists
        }
    
    };
    
    //won't return anything, but will take 10 seconds to run
    console.log(execSync("sleep 10")); 
    
    //assuming there are a lot of files and subdirectories, 
    //this too may take a while, use your own applicable file path
    console.log(execSync("dir /s c:\\usr\\docs\\"));
    

    EDIT - this example is meant for windows environments, adjust for your own linux needs if necessary

    How to advance to the next form input when the current input has a value?

    This should work. Working with and without tabindex.

    _x000D_
    _x000D_
    var currentlyFocused = undefined;_x000D_
    var tabableElements = undefined;_x000D_
    _x000D_
    /**_x000D_
     * Compare function for element sort_x000D_
     * @param {string | null} a_x000D_
     * @param {string | null} b_x000D_
     * @param {boolean} asc_x000D_
     */_x000D_
    function sortCompare(a, b, asc = true) {_x000D_
      let result = null;_x000D_
      if (a == null) result = 1;_x000D_
      else if (b == null) result = -1;_x000D_
      else if (parseInt(a) > parseInt(b)) result = 1;_x000D_
      else if (parseInt(a) < parseInt(b)) result = -1;_x000D_
      else result = 0;_x000D_
      return result * (asc ? 1 : -1);_x000D_
    }_x000D_
    _x000D_
    /**_x000D_
     * When an element is focused assign it to the currentlyFocused variable_x000D_
     * @param {Element} element_x000D_
     */_x000D_
    function registerOnElementFocus(element) {_x000D_
      element.addEventListener("focus", function(el) {_x000D_
        currentlyFocused = el.srcElement;_x000D_
      });_x000D_
    }_x000D_
    _x000D_
    /**_x000D_
     * Tab Trigger_x000D_
     */_x000D_
    function onTabClick() {_x000D_
      //Select currently focused element_x000D_
      let currentIndex;_x000D_
      tabableElements.forEach((el, idx) => {_x000D_
        //return if no element is focused_x000D_
        if (!currentlyFocused) return;_x000D_
        if (currentlyFocused.isEqualNode(el)) {_x000D_
          //assign current index and return_x000D_
          currentIndex = idx;_x000D_
          return;_x000D_
        }_x000D_
      });_x000D_
      //if theres no focused element or the current focused element is last start over_x000D_
      let lastIndex = tabableElements.length - 1;_x000D_
      let nextElementidx = currentIndex === undefined || currentIndex == lastIndex ? 0 : currentIndex + 1;_x000D_
      //Focus_x000D_
      currentlyFocused = tabableElements[nextElementidx];_x000D_
      currentlyFocused.focus();_x000D_
    }_x000D_
    /**_x000D_
     * Init must be run after all elements are loadead in the dom_x000D_
     */_x000D_
    function init() {_x000D_
      //Get all tab-able elements_x000D_
      let nodeList = document.querySelectorAll("input, button, a, area, object, select, textarea, [tabindex]");_x000D_
      //To array for easier manipulation_x000D_
      tabableElements = Array.prototype.slice.call(nodeList, 0);_x000D_
      //Correcting tabindexes to ensure correct order_x000D_
      tabableElements.forEach((el, idx, list) => {_x000D_
        let tabindex = el.getAttribute("tabindex");_x000D_
        //-1 tabindex will not receive focus_x000D_
        if (tabindex == -1) list.splice(idx, 1);_x000D_
        //null or 0 tabindex in normal source order_x000D_
        else if (tabindex == null || tabindex == 0) {_x000D_
          list[idx].setAttribute("tabindex", 9999 + idx);_x000D_
        }_x000D_
      });_x000D_
      //sort elements by their tabindex in ascending order_x000D_
      tabableElements.sort((elementA, elementB) => sortCompare(elementA.getAttribute("tabindex"), elementB.getAttribute("tabindex")));_x000D_
      //register focus event to elements_x000D_
      tabableElements.forEach(el => registerOnElementFocus(el));_x000D_
    }
    _x000D_
    <!doctype html>_x000D_
    <html lang="en">_x000D_
    _x000D_
    <head>_x000D_
      <!-- Required meta tags -->_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">_x000D_
    _x000D_
      <!-- Bootstrap CSS -->_x000D_
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">_x000D_
    _x000D_
      <title>Virtual tab</title>_x000D_
    </head>_x000D_
    _x000D_
    <body onload="init()">_x000D_
      <div class="container">_x000D_
        <h3>Virtual Tab Demo</h3>_x000D_
        <form>_x000D_
          <div class="btn btn-primary" style="position: fixed;" onclick="onTabClick()">_x000D_
            Tab!_x000D_
          </div>_x000D_
          <br>_x000D_
          <br>_x000D_
          <button id="button1" type="button" onclick="alert('button 1')">Button1</button>_x000D_
          <button id="button2" type="button" onclick="alert('button 2')">Button2</button>_x000D_
          <br>_x000D_
          <br>_x000D_
          <input id="text" type='text'>text_x000D_
          <br>_x000D_
          <input id="password" type='password' tabindex="-1">password_x000D_
          <br>_x000D_
          <input id="number" type='number' tabindex="5">number_x000D_
          <br>_x000D_
          <input id="checkbox" type='checkbox'>checkbox_x000D_
          <br>_x000D_
          <input id="radio" type='radio'>radio_x000D_
          <br>_x000D_
          <br>_x000D_
          <button id="button3" type="button" onclick="alert('button 3')">Button3</button>_x000D_
          <button id="button4" type="button" onclick="alert('button 4')">Button4</button>_x000D_
          <br>_x000D_
          <br>_x000D_
          <select id="select">_x000D_
            <option value="volvo">Volvo</option>_x000D_
            <option value="saab">Saab</option>_x000D_
            <option value="mercedes">Mercedes</option>_x000D_
            <option value="audi">Audi</option>_x000D_
          </select>_x000D_
          <br>_x000D_
          <br> textarea_x000D_
          <br>_x000D_
          <textarea id="textarea"></textarea>_x000D_
            <br>_x000D_
            <br>_x000D_
            <span id="span" tabindex="1">Focus other elements.</span>_x000D_
        </form>_x000D_
      </div>_x000D_
      <!-- Optional JavaScript -->_x000D_
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->_x000D_
      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    What is the difference between __dirname and ./ in node.js?

    The gist

    In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

    By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

    The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

    For example...

    Let's say your directory structure is

    /dir1
      /dir2
        pathtest.js
    

    and pathtest.js contains

    var path = require("path");
    console.log(". = %s", path.resolve("."));
    console.log("__dirname = %s", path.resolve(__dirname));
    

    and you do

    cd /dir1/dir2
    node pathtest.js
    

    you get

    . = /dir1/dir2
    __dirname = /dir1/dir2
    

    Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

    However, if you run the script from /dir1

    cd /dir1
    node dir2/pathtest.js
    

    you get

    . = /dir1
    __dirname = /dir1/dir2
    

    In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

    Using . inside require...

    If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

    require('../thefile')
    

    because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

    AngularJS HTTP post to PHP and undefined

    Because PHP does not natively accept JSON 'application/json' One approach is to update your headers and parameters from angular so that your api can use the data directly.

    First, Parameterize your data:

    data: $.param({ "foo": $scope.fooValue })
    

    Then, add the following to your $http

     headers: {
         'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
     }, 
    

    If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

    myApp.config(function($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    });
    

    Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

    My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...

    =CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")

    Advisably sheets to be adjacent to avoid unanticipated results.

    Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)
    
         Dim sStarSheet As String, sEndSheet As String, sAddress As String
         Dim lColonPos As Long, lExclaPos As Long, cnt As Long
    
        lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
        lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets
    
        sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
        sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name
    
        sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address
    
            cnt = 0
       For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
            cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
       Next
    
       CountIf3D = cnt
    
    End Function
    

    Initial size for the ArrayList

    Although your arraylist has a capacity of 10, the real list has no elements here. The add method is used to insert a element to the real list. Since it has no elements, you can't insert an element to the index of 5.

    How to read line by line or a whole text file at once?

    Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

    #include<cstdio>
    #include<iostream>
    
    using namespace std;
    
    int main(){
       freopen("path to file", "rb", stdin);
       string line;
       while(getline(cin, line))
           cout << line << endl;
       return 0;
    }
    

    Converting byte array to string in javascript

    Try the new Text Encoding API:

    _x000D_
    _x000D_
    // create an array view of some valid bytes_x000D_
    let bytesView = new Uint8Array([104, 101, 108, 108, 111]);_x000D_
    _x000D_
    console.log(bytesView);_x000D_
    _x000D_
    // convert bytes to string_x000D_
    // encoding can be specfied, defaults to utf-8 which is ascii._x000D_
    let str = new TextDecoder().decode(bytesView); _x000D_
    _x000D_
    console.log(str);_x000D_
    _x000D_
    // convert string to bytes_x000D_
    // encoding can be specfied, defaults to utf-8 which is ascii._x000D_
    let bytes2 = new TextEncoder().encode(str);_x000D_
    _x000D_
    // look, they're the same!_x000D_
    console.log(bytes2);_x000D_
    console.log(bytesView);
    _x000D_
    _x000D_
    _x000D_

    How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

    If I Understood correctly you need to view the .db file that you extracted from internal storage of Emulator. If that's the case use this

    http://sourceforge.net/projects/sqlitebrowser/

    to view the db.

    You can also use a firefox extension

    https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/

    EDIT: For online tool use : https://sqliteonline.com/

    bash "if [ false ];" returns true instead of false -- why?

    I found that I can do some basic logic by running something like:

    A=true
    B=true
    if ($A && $B); then
        C=true
    else
        C=false
    fi
    echo $C
    

    Array of an unknown length in C#

    Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.

    Search for them in System.Collections and System.Collections.Generics.

    Setting different color for each series in scatter plot on matplotlib

    A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import time
    
    
    # a generic set of data with associated colors
    nsamples=1000
    x=np.random.uniform(0,10,nsamples)
    y=np.random.uniform(0,10,nsamples)
    colors={0:'r',1:'g',2:'b',3:'k'}
    c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]
    
    plt.close('all')
    
    # "Fast" Scatter plotting
    starttime=time.time()
    # 1) make a dataframe
    df=pd.DataFrame()
    df['x']=x
    df['y']=y
    df['c']=c
    plt.figure()
    # 2) group the dataframe by color and loop
    for g,b in df.groupby(by='c'):
        plt.scatter(b['x'],b['y'],color=g)
    print('Fast execution time:', time.time()-starttime)
    
    # "Slow" Scatter plotting
    starttime=time.time()
    plt.figure()
    # 2) group the dataframe by color and loop
    for i in range(len(x)):
        plt.scatter(x[i],y[i],color=c[i])
    print('Slow execution time:', time.time()-starttime)
    
    plt.show()
    

    How do I see the current encoding of a file in Sublime Text?

    Another option in case you don't wanna use a plugin:

    Ctrl+` or

    View -> Show Console

    type on the console the following command:

    view.encoding()
    

    In case you want to something more intrusive, there's a option to create an shortcut that executes the following command:

    sublime.message_dialog(view.encoding())
    

    AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

    remove {{}} braces around foo.bar because angular expressions cannot be used in angular directives.

    For More: https://docs.angularjs.org/api/ng/directive/ngShow

    example

      <body ng-app="changeExample">
        <div ng-controller="ExampleController">
        <p ng-show="foo.bar">I could be shown, or I could be hidden</p>
        <p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
        </div>
        </body>
    
    <script>
         angular.module('changeExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.foo ={};
              $scope.foo.bar = true;
            }]);
    </script>
    

    Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

    you have missed the Fingerprint Certificate Authorization dialog in your phone when you connected it, try to change the USB mode to Media, or another different than the one you have in and then reconnect your device, or go to Developer Options -> Revoke USB Debugging and reconnect, watch for the dialog and click on accept, that should solve your problems.

    If that doesn't work, set your ANDROID_SDK_HOME again, and then:

    1. Unplug device
    2. Run:

      adb kill-server 
      adb start-server
      
    3. Plug in device

    How to use GROUP BY to concatenate strings in SQL Server?

    Just to add to what Cade said, this is usually a front-end display thing and should therefore be handled there. I know that sometimes it's easier to write something 100% in SQL for things like file export or other "SQL only" solutions, but most of the times this concatenation should be handled in your display layer.

    How to append a date in batch files

    I've found two ways that work regardless of the date settings.

    On my pc, date/t returns 2009-05-27

    You can either access the registry and read the regional settings (HKEY_CURRENT_USER\Control Panel\International)

    Or use a vbscript. This is the ugly batch file/vbscript hybrid I created some time ago....

    @Echo Off
    set rnd=%Random%
    set randfilename=x%rnd%.vbs
    
    ::create temp vbscript file
    Echo Dim DayofWeek(7) >  %temp%\%randfilename%
    Echo DayofWeek(1)="Sun" >> %temp%\%randfilename%
    Echo DayofWeek(2)="Mon" >> %temp%\%randfilename%
    Echo DayofWeek(3)="Tue" >> %temp%\%randfilename%
    Echo DayofWeek(4)="Wed" >> %temp%\%randfilename%
    Echo DayofWeek(5)="Thu" >> %temp%\%randfilename%
    Echo DayofWeek(6)="Fri" >> %temp%\%randfilename%
    Echo DayofWeek(7)="Sat" >> %temp%\%randfilename%
    Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename%
    Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename%
    Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename%
    Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " "  _ >> %temp%\%randfilename%
    Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename%
    Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename%
    Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2)  >> %temp%\%randfilename%
    
    ::set the output into vars
    if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F
    set year=%y2kyear:~2,2%
    
    ::cleanup
    del %temp%\%randfilename%
    

    It's not pretty, but it works.

    Make first letter of a string upper case (with maximum performance)

    I found something here http://www.dotnetperls.com/uppercase-first-letter :

    static string UppercaseFirst(string s)
    {
    // Check for empty string.
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }
    // Return char and concat substring.
    return char.ToUpper(s[0]) + s.Substring(1);
    }
    

    maybe this helps!!

    AES Encrypt and Decrypt

    This is a pretty old post but XCode 10 added the CommonCrypto module so you don't need a module map. Also with Swift 5, no need for the annoying casts.

    You could do something like:

    func decrypt(_ data: Data, iv: Data, key: Data) throws -> String {
    
        var buffer = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
        var bufferLen: Int = 0
    
        let status = CCCrypt(
            CCOperation(kCCDecrypt),
            CCAlgorithm(kCCAlgorithmAES128),
            CCOptions(kCCOptionPKCS7Padding),
            [UInt8](key),
            kCCBlockSizeAES128,
            [UInt8](iv),
            [UInt8](data),
            data.count,
            &buffer,
            buffer.count,
            &bufferLen
        )
    
        guard status == kCCSuccess,
            let str = String(data: Data(bytes: buffer, count: bufferLen),
                             encoding: .utf8) else {
                                throw NSError(domain: "AES", code: -1, userInfo: nil)
        }
    
        return str
    }
    

    Open application after clicking on Notification

    Thanks to above posts, here's the main lines - distilled from the longer code answers - that are necessary to connect a notification with click listener set to open some app Activity.

    private Notification getNotification(String messageText) {
    
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentText(messageText);
        // ...
    
        Intent appActivityIntent = new Intent(this, SomeAppActivity.class);
    
        PendingIntent contentAppActivityIntent =
                PendingIntent.getActivity(
                                this,  // calling from Activity
                                0,
                                appActivityIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT);
    
        builder.setContentIntent(contentAppActivityIntent);
    
        return builder.build();
    }
    

    How to initialize a List<T> to a given size (as opposed to capacity)?

    Use the constructor which takes an int ("capacity") as an argument:

    List<string> = new List<string>(10);
    

    EDIT: I should add that I agree with Frederik. You are using the List in a way that goes against the entire reasoning behind using it in the first place.

    EDIT2:

    EDIT 2: What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.

    Why would anyone need to know the size of a List with all null values? If there are no real values in the list, I would expect the length to be 0. Anyhow, the fact that this is cludgy demonstrates that it is going against the intended use of the class.

    how to call an ASP.NET c# method using javascript

    PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

    PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

    In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

    <body>
        <form id="form1" runat="server">
        <div>
            <fieldset style="width: 200px;">
                <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
                <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
            </fieldset>
            <div>
            </div>
            <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
        </div>
        </form>
    </body>
    </html>
    

    To setup page method, first you have to drag a script manager on your page.

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    

    Also notice that I have changed EnablePageMethods="true".
    This will tell ScriptManager that I am going to call PageMethods from client side.

    Now next step is to create a Server Side function.
    Here is the function which I created, this function validates user's input:

    [WebMethod]
    public static string RegisterUser(string email, string password)
    {
        string result = "Congratulations!!! your account has been created.";
        if (email.Length == 0)//Zero length check
        {
            result = "Email Address cannot be blank";
        }
        else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
        {
            result = "Not a valid email address";
        }
        else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
        {
            result = "Not a valid email address";
        }
    
        else if (password.Length == 0)
        {
            result = "Password cannot be blank";
        }
        else if (password.Length < 5)
        {
            result = "Password cannot be less than 5 chars";
        }
    
        return result;
    }
    

    To tell script manager that this method is accessible through javascript we need to ensure two things:
    First: This method should be 'public static'.
    Second: There should be a [WebMethod] tag above method as written in above code.

    Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

    <script type="text/javascript">
        function Signup() {
            var email = document.getElementById('<%=txtEmail.ClientID %>').value;
            var password = document.getElementById('<%=txtPassword.ClientID %>').value;
    
            PageMethods.RegisterUser(email, password, onSucess, onError);
    
            function onSucess(result) {
                alert(result);
            }
    
            function onError(result) {
                alert('Cannot process your request at the moment, please try later.');
            }
        }
    </script>
    

    To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
    My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

    Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
            </asp:ScriptManager>
            <fieldset style="width: 200px;">
                <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
                <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
            </fieldset>
            <div>
            </div>
            <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
        </div>
        </form>
    </body>
    </html>
    
    <script type="text/javascript">
        function Signup() {
            var email = document.getElementById('<%=txtEmail.ClientID %>').value;
            var password = document.getElementById('<%=txtPassword.ClientID %>').value;
    
            PageMethods.RegisterUser(email, password, onSucess, onError);
    
            function onSucess(result) {
                alert(result);
            }
    
            function onError(result) {
                alert('Cannot process your request at the moment, please try later.');
            }
        }
    </script>
    

    What does -> mean in C++?

    a->b means (*a).b.

    If a is a pointer, a->b is the member b of which a points to.

    a can also be a pointer like object (like a vector<bool>'s stub) override the operators.

    (if you don't know what a pointer is, you have another question)

    Non-recursive depth first search algorithm

    If you have pointers to parent nodes, you can do it without additional memory.

    def dfs(root):
        node = root
        while True:
            visit(node)
            if node.first_child:
                node = node.first_child      # walk down
            else:
                while not node.next_sibling:
                    if node is root:
                        return
                    node = node.parent       # walk up ...
                node = node.next_sibling     # ... and right
    

    Note that if the child nodes are stored as an array rather than through sibling pointers, the next sibling can be found as:

    def next_sibling(node):
        try:
            i =    node.parent.child_nodes.index(node)
            return node.parent.child_nodes[i+1]
        except (IndexError, AttributeError):
            return None
    

    DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

    You can use String.Format:

    DateTime d = DateTime.Now;
    string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
    // I got this result: "02/23/2015 16:42:38.234"
    

    Correct format specifier for double in printf

    It can be %f, %g or %e depending on how you want the number to be formatted. See here for more details. The l modifier is required in scanf with double, but not in printf.

    How to place a JButton at a desired location in a JFrame using Java

    Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

    //JPanel
    JPanel pnlButton = new JPanel();
    //Buttons
    JButton btnAddFlight = new JButton("Add Flight");
    
    public Control() {
    
        //JFrame layout
        this.setLayout(null);
    
        //JPanel layout
        pnlButton.setLayout(null);
    
        //Adding to JFrame
        pnlButton.add(btnAddFlight);
        add(pnlButton);
    
        // postioning
        pnlButton.setLocation(0,0);
    

    C# DataTable.Select() - How do I format the filter criteria to include null?

    The way to check for null is to check for it:

    DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");
    

    You can use and and or in the Select statement.

    What is the best way to create a string array in python?

    def _remove_regex(input_text, regex_pattern):
        findregs = re.finditer(regex_pattern, input_text) 
        for i in findregs: 
            input_text = re.sub(i.group().strip(), '', input_text)
        return input_text
    
    regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
    _remove_regex("row and row and row your boat until you can row no more", regex_pattern)
    

    \w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

    When do you use Java's @Override annotation and why?

    Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

    Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

    How to set shadows in React Native for android?

    In short, you can't do that in android, because if you see the docs about shadow only Support IOS see doc

    The best option you can install 3rd party react-native-shadow

    How to specify HTTP error code?

    The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.

    Stuck at ".android/repositories.cfg could not be loaded."

    Creating a dummy blank repositories.cfg works on Windows 7 as well. After waiting for a couple of minutes the installation finishes and you get the message on your cmd window -- done

    How to enable C++11/C++0x support in Eclipse CDT?

    When using a cross compiler, I often get advanced custom build systems meticulously crafted by colleagues. I use "Makefile Project with Existing code" so most of the other answers are not applicable.

    At the start of the project, I have to specify that I'm using a cross compiler in the wizard for "Makefile Project with Existing Code". The annoying thing is that in the last 10 or so years, the cross compiler button on that wizard doesn't prompt for where the cross compiler is. So in a step that fixes the C++ problem and the cross compiler problem, I have to go to the providers tab as mentioned by answers like @ravwojdyla above, but the provider I have to select is the cross-compiler provider. Then in the command box I put the full path to the compiler and I add -std=gnu++11 for the C++ standard I want to have support for. This works out as well as can be expected.

    You can do this to an existing project. The only thing you might need to do is rerun the indexer.

    I have never had to add the experimental flag or override __cplusplus's definition. The only thing is, if I have a substantial amount of modern C code, I have nowhere to put the C-specific standard option.

    And for when things are going really poorly, getting a parser log, using that command in the Indexer submenu, can be very informative.

    format a Date column in a Data Frame

    The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

    dt = data.table(
      Name = c('Joe', 'Amy', 'John'),
      JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
      AmtPaid = c(1000, 100, 200)
    )
    
    require(data.table)
    dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]
    

    How to set the first option on a select box using jQuery?

    Here is the best solution im using. This will apply for over 1 slectbox

    _x000D_
    _x000D_
    $("select").change(function(){_x000D_
        var thisval = $(this).val();_x000D_
        $("select").prop('selectedIndex',0);_x000D_
        $(this).val(thisval);_x000D_
    })
    _x000D_
    _x000D_
    _x000D_

    How to style readonly attribute with CSS?

    Loads of answers here, but haven't seen the one I use:

    input[type="text"]:read-only { color: blue; }
    

    Note the dash in the pseudo selector. If the input is readonly="false" it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:

    input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
    

    textarea works the same way:

    textarea:read-only:not([read-only="false"]) { color: blue; }
    

    Keep in mind that html now supports not only type="text", but a slew of other textual types such a number, tel, email, date, time, url, etc. Each would need to be added to the selector.

    Using if-else in JSP

    Instead of if-else condition use if in both conditions. it will work that way but not sure why.

    How can I find all *.js file in directory recursively in Linux?

    If you just want the list, then you should ask here: http://unix.stackexchange.com

    The answer is: cd / && find -name *.js

    If you want to implement this, you have to specify the language.

    I want to calculate the distance between two points in Java

    Math.sqrt returns a double so you'll have to cast it to int as well

    distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

    Converting Decimal to Binary Java

    Well, you can use while loop, like this,

    import java.util.Scanner;
    
    public class DecimalToBinaryExample
    {
        public static void main(String[] args)
        {
            int num;
            int a = 0;
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter a decimal number : ");
            num = sc.nextInt();
            int binary[] = new int[100];
    
            while(num != 0)
            {
                binary[a] = num % 2;
                num = num / 2;
                a++;
            }
    
            System.out.println("The binary value is : ");
            for(int b = a - 1; b >= 0; b--)
            {
                System.out.println("" + binary[b]);
            }
            sc.close();
        }
    }
    

    You can refer example below for some good explanation,

    convert decimal to binary example.

    Saving response from Requests to file

    As Peter already pointed out:

    In [1]: import requests
    
    In [2]: r = requests.get('https://api.github.com/events')
    
    In [3]: type(r)
    Out[3]: requests.models.Response
    
    In [4]: type(r.content)
    Out[4]: str
    

    You may also want to check r.text.

    Also: https://2.python-requests.org/en/latest/user/quickstart/

    TypeError: unhashable type: 'list' when using built-in set function

        python 3.2
    
    
        >>>> from itertools import chain
        >>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
            [7, 6, 5, 4, 3, 2, 1]
    
    
       ##### eg contain 2 list within a list. so if you want to use set() function
       you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]
    
       >>> res= list(chain(*eg))       # [1, 2, 3, 4, 4, 5, 6, 7]                   
       >>> res1= set(res)                    #   [1, 2, 3, 4, 5, 6, 7]
       >>> res1= sorted(res1,reverse=True)
    

    Cannot find control with name: formControlName in angular reactive form

    you're missing group nested controls with formGroupName directive

    <div class="panel-body" formGroupName="address">
      <div class="form-group">
        <label for="address" class="col-sm-3 control-label">Business Address</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
        </div>
      </div>
      <div class="form-group">
        <label for="website" class="col-sm-3 control-label">Website</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="website" placeholder="website">
        </div>
      </div>
      <div class="form-group">
        <label for="telephone" class="col-sm-3 control-label">Telephone</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-sm-3 control-label">Email</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="email" placeholder="email">
        </div>
      </div>
      <div class="form-group">
        <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
        </div>
      </div>
      <div class="form-group">
        <label for="about" class="col-sm-3  control-label"></label>
        <div class="col-sm-3">
          <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
        </div>
        <label for="about" class="col-sm-2  control-label"></label>
        <div class="col-sm-3">
          <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
        </div>
      </div>
    </div>
    

    How to create Custom Ratings bar in Android

    You can use @erdomester 's given solution for this. But if you are facing issues with rating bar height then you can use ratingbar's icons height programmatically.

    In Kotlin,

    val drawable = ContextCompat.getDrawable(context, R.drawable.rating_filled)
    val drawableHeight = drawable.intrinsicHeight
    
    rating_bar.layoutParams.height = drawableHeight
    

    How to check if a Ruby object is a Boolean

    An object that is a boolean will either have a class of TrueClass or FalseClass so the following one-liner should do the trick

    mybool = true
    mybool.class == TrueClass || mybool.class == FalseClass
    => true
    

    The following would also give you true/false boolean type check result

    mybool = true    
    [TrueClass, FalseClass].include?(mybool.class)
    => true
    

    "Active Directory Users and Computers" MMC snap-in for Windows 7?

    I'm not allowed to use Turn Windows features on or off, but running all of these commands in an elevated command prompt (Run as Administrator) finally got Active Directory Users and Computers to show up under Administrative Tools on the start menu:

    dism /online /enable-feature /featurename:RemoteServerAdministrationTools
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-AdministrativeCenter
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-NIS
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-LDS
    dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-Powershell
    

    I had downloaded and installed the RSAT (Windows 7 Link, Windows Vista Link) before running these commands.

    It's quite likely that this is more than you features than you actually need, but at least it's not too few.

    Disable validation of HTML5 form elements

    I had a read of the spec and did some testing in Chrome, and if you catch the "invalid" event and return false that seems to allow form submission.

    I am using jquery, with this HTML.

    _x000D_
    _x000D_
    // suppress "invalid" events on URL inputs_x000D_
    $('input[type="url"]').bind('invalid', function() {_x000D_
      alert('invalid');_x000D_
      return false;_x000D_
    });_x000D_
    _x000D_
    document.forms[0].onsubmit = function () {_x000D_
      alert('form submitted');_x000D_
    };
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <form>_x000D_
      <input type="url" value="http://" />_x000D_
      <button type="submit">Submit</button>_x000D_
    </form>
    _x000D_
    _x000D_
    _x000D_

    I haven't tested this in any other browsers.

    How to replace local branch with remote branch entirely in Git?

    That's as easy as three steps:

    1. Delete your local branch: git branch -d local_branch
    2. Fetch the latest remote branch: git fetch origin remote_branch
    3. Rebuild the local branch based on the remote one: git checkout -b local_branch origin/remote_branch

    How to change the color of header bar and address bar in newest Chrome version on Lollipop?

    For example, to set the background to your favorite/Branding color

    Add Below Meta property to your HTML code in HEAD Section

    <head>
      ...
      <meta name="theme-color" content="Your Hexadecimal Code">
      ...
    </head>
    

    Example

    <head>
      ...
      <meta name="theme-color" content="#444444">
      ...
    </head>
    

    In Below Image, I just mentioned How Chrome taken your theme-color Property

    enter image description here

    Firefox OS, Safari, Internet Explorer and Opera Coast allow you to define colors for elements of the browser, and even the platform using meta tags.

    <!-- Windows Phone -->
    <meta name="msapplication-navbutton-color" content="#4285f4">
    <!-- iOS Safari -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    

    Safari specific styling

    From the guidelinesDocuments Here

    Hiding Safari User Interface Components

    Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.

    <meta name="apple-mobile-web-app-capable" content="yes">
    

    Changing the Status Bar Appearance

    You can change the appearance of the default status bar to either black or black-translucent. With black-translucent, the status bar floats on top of the full screen content, rather than pushing it down. This gives the layout more height, but obstructs the top. Here’s the code required:

    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    

    For more on status bar appearance, see apple-mobile-web-app-status-bar-style.

    For Example:

    Screenshot using black-translucent

    Screenshot using black-translucent

    Screenshot using black

    Screenshot using black

    UEFA/FIFA scores API

    You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

    We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

    Count(*) vs Count(1) - SQL Server

    As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.

    SELECT COUNT(*) FROM something counts records which is an easy task.

    SELECT COUNT(1) FROM something retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.

    Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.

    However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.