Programs & Examples On #Mpeg

MPEG - Class of Compression standards and related algorithms, tools and systems

Converting video to HTML5 ogg / ogv and mpg4

The Miro video converter does a beautiful job and is drag-n-drop. http://www.mirovideoconverter.com/

BTW it's FREE and also very good for mobile device encoding.

Returning a C string from a function

If you really can't use pointers, do something like this:

char get_string_char(int index)
{
    static char array[] = "my string";
    return array[index];
}

int main()
{
    for (int i = 0; i < 9; ++i)
        printf("%c", get_string_char(i));
    printf("\n");
    return 0;
}

The magic number 9 is awful, and this is not an example of good programming. But you get the point. Note that pointers and arrays are the same thing (kind of), so this is a bit cheating.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

  1. This error would spring up arbitrarily and caused quite a bit of trouble though the code on my end was solid.

I did the following :

  • I closed it on netbeans.
  • Then open the project by clicking "Open Project", selecting my project and
  • Simply hit the run button in netbeans.

I would not build or clean build it. Hope that helps you out.

  1. I noticed another reason why this happens. If you moved your main class to another package, the same error springs up. In that case you :
    • Right Click Project > Properties > Run
    • Set the "Main Class" correctly by clicking "Browse" and selecting.

Reading a text file with SQL Server

What does your text file look like?? Each line a record?

You'll have to check out the BULK INSERT statement - that should look something like:

BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
  CODEPAGE = '1252',
  FIELDTERMINATOR = ';',
  CHECK_CONSTRAINTS
) 

Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.

From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:

BULK INSERT dbo.temp 
   FROM 'c:\temp\file.txt'
   WITH 
      (
         ROWTERMINATOR ='\n'
      )

Seems to work just fine in my test environment :-)

git undo all uncommitted or unsaved changes

If you wish to "undo" all uncommitted changes simply run:

git stash
git stash drop

If you have any untracked files (check by running git status), these may be removed by running:

git clean -fdx

git stash creates a new stash which will become stash@{0}. If you wish to check first you can run git stash list to see a list of your stashes. It will look something like:

stash@{0}: WIP on rails-4: 66c8407 remove forem residuals
stash@{1}: WIP on master: 2b8f269 Map qualifications
stash@{2}: WIP on master: 27a7e54 Use non-dynamic finders
stash@{3}: WIP on blogit: c9bd270 some changes

Each stash is named after the previous commit messsage.

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How to set viewport meta for iPhone that handles rotation properly?

Why not just reload the page when the user rotates the screen with javascript

function doOnOrientationChange()
{
location.reload();
}

window.addEventListener('orientationchange', doOnOrientationChange);

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

vi/vim editor, copy a block (not usual action)

Keyboard shortcuts to that are:

  1. For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p

  2. For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

Do HTTP POST methods send data as a QueryString?

If your post try to reach the following URL

mypage.php?id=1

you will have the POST data but also GET data.

How to pass values between Fragments

This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.

In receiver fragment add a listener:

setFragmentResultListener(
    "data_request_key",
    lifecycleOwner,
    FragmentResultListener { requestKey: String, bundle: Bundle ->
        // unpack the bundle and use data
        val frag1Str = bundle.getString("frag1_data_key")

    })

In sender fragment(frag1):

setFragmentResult(
    "data_request_key",
    bundleOf("frag1_data_key" to value)
)

Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.

Credits and further reading:

A New Way to Pass Data Between Fragments

Android Fragments: Fragment Result

What is a smart pointer and when should I use one?

A smart pointer is a pointer-like type with some additional functionality, e.g. automatic memory deallocation, reference counting etc.

A small intro is available on the page Smart Pointers - What, Why, Which?.

One of the simple smart-pointer types is std::auto_ptr (chapter 20.4.5 of C++ standard), which allows one to deallocate memory automatically when it out of scope and which is more robust than simple pointer usage when exceptions are thrown, although less flexible.

Another convenient type is boost::shared_ptr which implements reference counting and automatically deallocates memory when no references to the object remains. This helps avoiding memory leaks and is easy to use to implement RAII.

The subject is covered in depth in book "C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis, chapter Chapter 20. Smart Pointers. Some topics covered:

Count characters in textarea

Here my example. Supper simple

_x000D_
_x000D_
$(document).ready(function() {_x000D_
      _x000D_
        var textarea    = $("#my_textarea");_x000D_
  _x000D_
        textarea.keydown(function(event) {_x000D_
          _x000D_
            var numbOfchars = textarea.val();_x000D_
            var len = numbOfchars.length;_x000D_
            $(".chars-counter").text(len);_x000D_
_x000D_
        });_x000D_
  _x000D_
  _x000D_
 }); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="my_textarea" class="uk-textarea" rows="5" name="text"></textarea>_x000D_
<h1 class="chars-counter">0</h1>
_x000D_
_x000D_
_x000D_

C - gettimeofday for computing time?

No. gettimeofday should NEVER be used to measure time.

This is causing bugs all over the place. Please don't add more bugs.

Regular expression for not allowing spaces in the input field

This will help to find the spaces in the beginning, middle and ending:

var regexp = /\s/g

Newtonsoft JSON Deserialize

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
    // Do something with typeStr
} 

string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

What does this thread join code mean?

For me, Join() behavior was always confusing because I was trying to remember who will wait for whom. Don't try to remember it that way.

Underneath, it is pure wait() and notify() mechanism.

We all know that, when we call wait() on any object(t1), calling object(main) is sent to waiting room(Blocked state).

Here, main thread is calling join() which is wait() under the covers. So main thread will wait until it is notified. Notification is given by t1 when it finishes it's run(thread completion).

After receiving the notification, main comes out of waiting room and proceeds it's execution.

CSS-Only Scrollable Table with fixed headers

Surprised a solution using flexbox hasn't been posted yet.

Here's my solution using display: flex and a basic use of :after (thanks to Luggage) to maintain the alignment even with the scrollbar padding the tbody a bit. This has been verified in Chrome 45, Firefox 39, and MS Edge. It can be modified with prefixed properties to work in IE11, and further in IE10 with a CSS hack and the 2012 flexbox syntax.

Note the table width can be modified; this even works at 100% width.

The only caveat is that all table cells must have the same width. Below is a clearly contrived example, but this works fine when cell contents vary (table cells all have the same width and word wrapping on, forcing flexbox to keep them the same width regardless of content). Here is an example where cell contents are different.

Just apply the .scroll class to a table you want scrollable, and make sure it has a thead:

_x000D_
_x000D_
.scroll {_x000D_
  border: 0;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll tr {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.scroll td {_x000D_
  padding: 3px;_x000D_
  flex: 1 auto;_x000D_
  border: 1px solid #aaa;_x000D_
  width: 1px;_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.scroll thead tr:after {_x000D_
  content: '';_x000D_
  overflow-y: scroll;_x000D_
  visibility: hidden;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
.scroll thead th {_x000D_
  flex: 1 auto;_x000D_
  display: block;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.scroll tbody {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
  height: 200px;_x000D_
}
_x000D_
<table class="scroll" width="400px">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Angular 2 Show and Hide an element

You should use the *ngIf Directive

<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

Update: you are missing the reference to the outer scope when you are inside the Timeout callback.

so add the .bind(this) like I added Above

Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn

A : I would add edit as a property to the object I am iterating over.

<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


export class AppComponent implements OnInit{
   
  public listOfObjects = [
    {
       name : 'obj - 1',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    },
    {
       name : 'obj - 2',
       edit : false
    } 
  ];
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
  }
}

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

your .key file contains illegal characters. you can check .key file like this:

# file server.key

output "server.key: UTF-8 Unicode (with BOM) text" means it is a plain text, not a key file. The correct output should be "server.key: PEM RSA private key".

use below command to remove illegal characters:

# tail -c +4 server.key > new_server.key

The new_server.key should be correct.

For more detail, you can click here, thanks for the post.

How do I instantiate a JAXBElement<String> object?

ObjectFactory fact = new ObjectFactory();   
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");    
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());

List files recursively in Linux CLI with path relative to the current directory

Try find. You can look it up exactly in the man page, but it's sorta like this:

find [start directory] -name [what to find]

so for your example

find . -name "*.txt"

should give you what you want.

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Support for schemas:

This is an updated version that amends the great answer from David, et al. Added is support for named schemas. It should be noted this may break if there's actually tables of the same name present within various schemas. Another improvement is the use of the official QuoteName() function.

SELECT 
    t.TABLE_CATALOG,
    t.TABLE_SCHEMA,
    t.TABLE_NAME,
    'create table '+QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) + ' (' + LEFT(o.List, Len(o.List)-1) + ');  ' 
        + CASE WHEN tc.Constraint_Name IS NULL THEN '' 
          ELSE 
            'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) 
            + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ');  ' 
          END as 'SQL_CREATE_TABLE'
FROM sysobjects so

CROSS APPLY (
    SELECT 
          '  ['+column_name+'] ' 
          +  data_type 
          + case data_type
                when 'sql_variant' then ''
                when 'text' then ''
                when 'ntext' then ''
                when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
              else 
              coalesce(
                '('+ case when character_maximum_length = -1 
                    then 'MAX' 
                    else cast(character_maximum_length as varchar) end 
                + ')','') 
            end 
        + ' ' 
        + case when exists ( 
            SELECT id 
            FROM syscolumns
            WHERE 
                object_name(id) = so.name
                and name = column_name
                and columnproperty(id,name,'IsIdentity') = 1 
          ) then
            'IDENTITY(' + 
            cast(ident_seed(so.name) as varchar) + ',' + 
            cast(ident_incr(so.name) as varchar) + ')'
          else ''
          end 
        + ' ' 
        + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) 
        + 'NULL ' 
        + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT 
          ELSE '' 
          END 
        + ','  -- can't have a field name or we'll end up with XML

    FROM information_schema.columns 
    WHERE table_name = so.name
    ORDER BY ordinal_position
    FOR XML PATH('')
) o (list)

LEFT JOIN information_schema.table_constraints tc on  
    tc.Table_name = so.Name
    AND tc.Constraint_Type  = 'PRIMARY KEY'

LEFT JOIN information_schema.tables t on  
    t.Table_name = so.Name

CROSS APPLY (
    SELECT QuoteName(Column_Name) + ', '
    FROM information_schema.key_column_usage kcu
    WHERE kcu.Constraint_Name = tc.Constraint_Name
    ORDER BY ORDINAL_POSITION
    FOR XML PATH('')
) j (list)

WHERE
    xtype = 'U'
    AND name NOT IN ('dtproperties')
    -- AND so.name = 'ASPStateTempSessions'
;

..

For use in Management Studio:

One detractor to the sql code above is if you test it using SSMS, long statements aren't easy to read. So, as per this helpful post, here's another version that's somewhat modified to be easier on the eyes after clicking the link of a cell in the grid. The results are more readily identifiable as nicely formatted CREATE TABLE statements for each table in the db.

-- settings
DECLARE @CRLF NCHAR(2)
SET @CRLF = Nchar(13) + NChar(10)
DECLARE @PLACEHOLDER NCHAR(3)
SET @PLACEHOLDER = '{:}'

-- the main query
SELECT 
    t.TABLE_CATALOG,
    t.TABLE_SCHEMA,
    t.TABLE_NAME,
    CAST(
        REPLACE(
            'create table ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.name) + ' (' + @CRLF 
            + LEFT(o.List, Len(o.List) - (LEN(@PLACEHOLDER)+2)) + @CRLF + ');' + @CRLF
            + CASE WHEN tc.Constraint_Name IS NULL THEN '' 
              ELSE
                'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.Name) 
                + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY (' + LEFT(j.List, Len(j.List) - 1) + ');' + @CRLF
              END,
            @PLACEHOLDER,
            @CRLF
        )
    AS XML) as 'SQL_CREATE_TABLE'
FROM sysobjects so

CROSS APPLY (
    SELECT 
          '   '
          + '['+column_name+'] ' 
          +  data_type 
          + case data_type
                when 'sql_variant' then ''
                when 'text' then ''
                when 'ntext' then ''
                when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
              else 
              coalesce(
                '('+ case when character_maximum_length = -1 
                    then 'MAX' 
                    else cast(character_maximum_length as varchar) end 
                + ')','') 
            end 
        + ' ' 
        + case when exists ( 
            SELECT id 
            FROM syscolumns
            WHERE 
                object_name(id) = so.name
                and name = column_name
                and columnproperty(id,name,'IsIdentity') = 1 
          ) then
            'IDENTITY(' + 
            cast(ident_seed(so.name) as varchar) + ',' + 
            cast(ident_incr(so.name) as varchar) + ')'
          else ''
          end 
        + ' ' 
        + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) 
        + 'NULL ' 
        + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT 
          ELSE '' 
          END 
        + ', ' 
        + @PLACEHOLDER  -- note, can't have a field name or we'll end up with XML

    FROM information_schema.columns where table_name = so.name
    ORDER BY ordinal_position
    FOR XML PATH('')
) o (list)

LEFT JOIN information_schema.table_constraints tc on  
    tc.Table_name = so.Name
    AND tc.Constraint_Type  = 'PRIMARY KEY'

LEFT JOIN information_schema.tables t on  
    t.Table_name = so.Name

CROSS APPLY (
    SELECT QUOTENAME(Column_Name) + ', '
    FROM information_schema.key_column_usage kcu
    WHERE kcu.Constraint_Name = tc.Constraint_Name
    ORDER BY ORDINAL_POSITION
    FOR XML PATH('')
) j (list)

WHERE
    xtype = 'U'
    AND name NOT IN ('dtproperties')
    -- AND so.name = 'ASPStateTempSessions'
;

Not to belabor the point, but here's the functionally equivalent example outputs for comparison:

-- 1 (scripting version)
create table [dbo].[ASPStateTempApplications] (  [AppId] int  NOT NULL ,  [AppName] char(280)  NOT NULL );  ALTER TABLE [dbo].[ASPStateTempApplications] ADD CONSTRAINT PK__ASPState__8E2CF7F908EA5793 PRIMARY KEY  ([AppId]);  

-- 2 (SSMS version)
create table [dbo].[ASPStateTempSessions] (
   [SessionId] nvarchar(88)  NOT NULL , 
   [Created] datetime  NOT NULL DEFAULT (getutcdate()), 
   [Expires] datetime  NOT NULL , 
   [LockDate] datetime  NOT NULL , 
   [LockDateLocal] datetime  NOT NULL , 
   [LockCookie] int  NOT NULL , 
   [Timeout] int  NOT NULL , 
   [Locked] bit  NOT NULL , 
   [SessionItemShort] varbinary(7000)  NULL , 
   [SessionItemLong] image(2147483647)  NULL , 
   [Flags] int  NOT NULL DEFAULT ((0))
);
ALTER TABLE [dbo].[ASPStateTempSessions] ADD CONSTRAINT PK__ASPState__C9F4929003317E3D PRIMARY KEY ([SessionId]);

..

Detracting factors:

It should be noted that I remain relatively unhappy with this due to the lack of support for indeces other than a primary key. It remains suitable for use as a mechanism for simple data export or replication.

How to get the current time as datetime

One line Swift 5.2

let date = String(DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short))

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

I had a similar issue. I've been bouncing between XCode 7 and 8 for a variety of reasons. Once you use 8 to build, you will need to use 8. I simply used Xcode 8 and applied some of the changes suggested above and it worked.

MVC 4 Razor File Upload

View Page

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

script file

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

Illegal string offset Warning PHP

A little bit late to the question, but for others who are searching: I got this error by initializing with a wrong value (type):

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

The right way is:

 $varName = array();
 $varName["x"] = "test"; // works

Is Spring annotation @Controller same as @Service?

You can declare a @service as @Controller.

You can NOT declare an @Controller as @Service

@Service

It is regular. You are just declaring class as a Component.

@Controller

It is a little more special than Component. The dispatcher will search for @RequestMapping here. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

Reversing a string in C

That's a good question ant2009. You can use a standalone function to reverse the string. The code is...

#include <stdio.h>
#define MAX_CHARACTERS 99

int main( void );
int strlen( char __str );

int main() {
    char *str[ MAX_CHARACTERS ];
    char *new_string[ MAX_CHARACTERS ];
    int i, j;

    printf( "enter string: " );
    gets( *str );

    for( i = 0; j = ( strlen( *str ) - 1 ); i < strlen( *str ), j > -1; i++, j-- ) {
        *str[ i ] = *new_string[ j ];
    }
    printf( "Reverse string is: %s", *new_string" );
    return ( 0 );
}

int strlen( char __str[] ) {
    int count;
    for( int i = 0; __str[ i ] != '\0'; i++ ) {
         ++count;
    }
    return ( count );
}

Difference between h:button and h:commandButton

h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:

<h:form>
    <h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>

this code generates the follwing html:

<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">

whereas the h:button is simpler and just used for static or rule based navigation as follows

<h:button outcome="page.xhtml" value="button"/>

the generated html is

 <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

Script to Change Row Color when a cell changes text

Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.

Assuming the "Status" was Column D:

Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as

=RegExMatch($D2,"Complete")

or

=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))

Edit (thanks to Frederik Schøning)

=RegExMatch($D2,"(?i)Complete") then set the range to cover all the rows e.g. A2:Z10. This is case insensitive, so will match complete, Complete or CoMpLeTe.

You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The best solution would be to go to http://projects.eclipse.org/projects/tools.pdt/downloads where you will find the URL to the most updated PDT, as most of the URLS listed above are hitting a 404. Then pasting the URL to eclipse.

Get visible items in RecyclerView

You can find the first and last visible children of the recycle view and check if the view you're looking for is in the range:

var visibleChild: View = rv.getChildAt(0)
val firstChild: Int = rv.getChildAdapterPosition(visibleChild)
visibleChild = rv.getChildAt(rv.childCount - 1)
val lastChild: Int = rv.getChildAdapterPosition(visibleChild)
println("first visible child is: $firstChild")
println("last visible child is: $lastChild")

npm install doesn't create node_modules directory

See @Cesco's answer: npm init is really all you need


I was having the same issue - running npm install somePackage was not generating a node_modules dir.

I created a package.json file at the root, which contained a simple JSON obj:

{
    "name": "please-work"
}

On the next npm install the node_modules directory appeared.

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

How to convert from []byte to int in Go Programming

Starting from a byte array you can use the binary package to do the conversions.

For example if you want to read ints :

buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)

The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.

When to use StringBuilder in Java

As a general rule, always use the more readable code and only refactor if performance is an issue. In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case.

You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize.

What is the difference between UTF-8 and ISO-8859-1?

UTF

UTF is a family of multi-byte encoding schemes that can represent Unicode code points which can be representative of up to 2^31 [roughly 2 billion] characters. UTF-8 is a flexible encoding system that uses between 1 and 4 bytes to represent the first 2^21 [roughly 2 million] code points.

Long story short: any character with a code point/ordinal representation below 127, aka 7-bit-safe ASCII is represented by the same 1-byte sequence as most other single-byte encodings. Any character with a code point above 127 is represented by a sequence of two or more bytes, with the particulars of the encoding best explained here.

ISO-8859

ISO-8859 is a family of single-byte encoding schemes used to represent alphabets that can be represented within the range of 127 to 255. These various alphabets are defined as "parts" in the format ISO-8859-n, the most familiar of these likely being ISO-8859-1 aka 'Latin-1'. As with UTF-8, 7-bit-safe ASCII remains unaffected regardless of the encoding family used.

The drawback to this encoding scheme is its inability to accommodate languages comprised of more than 128 symbols, or to safely display more than one family of symbols at one time. As well, ISO-8859 encodings have fallen out of favor with the rise of UTF. The ISO "Working Group" in charge of it having disbanded in 2004, leaving maintenance up to its parent subcommittee.

UL or DIV vertical scrollbar

You need to define height of ul or your div and set overflow equals to auto as below:

<ul style="width: 300px; height: 200px; overflow: auto">
  <li>text</li>
  <li>text</li>

UIView Infinite 360 degree rotation animation?

This was working for me:

[UIView animateWithDuration:1.0
                animations:^
{
    self.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    self.imageView.transform = CGAffineTransformMakeRotation(0);
}];

Query to list all stored procedures

The following will Return All Procedures in selected database

SELECT * FROM sys.procedures

"psql: could not connect to server: Connection refused" Error when connecting to remote database

cd /etc/postgresql/9.x/main/

open file named postgresql.conf

sudo vi postgresql.conf

add this line to that file

listen_addresses = '*'

then open file named pg_hba.conf

sudo vi pg_hba.conf

and add this line to that file

host  all  all 0.0.0.0/0 md5

It allows access to all databases for all users with an encrypted password

restart your server

sudo /etc/init.d/postgresql restart

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

How to read from stdin with fgets()?

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}

XMLHttpRequest (Ajax) Error

I see 2 possible problems:

Problem 1

  • the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it

Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function

xmlhttp.onreadystatechange = callbackFunctionName;

Once the state has reached DONE (4), the response content is ready to be read.

Problem 2

  • the XMLHTTPRequest object does not exist in all browsers (by that name)

Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method

Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()

How to change the default background color white to something else in twitter bootstrap

You have to override the bootstrap default by being a bit more specific. Try this for a black background:

html body {
    background-color: rgba(0,0,0,1.00);

}

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

Understanding string reversal via slicing

Using extended slice syntax

word = input ("Type a word which you want to reverse: ")
def reverse(word):
  word = word[::-1]
  return word
print (reverse(word))

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

javac error: Class names are only accepted if annotation processing is explicitly requested

I created a jar file from a Maven project (by write mvn package or mvn install )

after that i open the cmd , move to the jar direction and then

to run this code the

java -cp FILENAME.jar package.Java-Main-File-Name-Class

Edited : after puting in Pom file declar the main to run the code :

java -jar FILENAME.JAR

What's the difference between ng-model and ng-bind

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

Swift Error: Editor placeholder in source file

Error is straight forward and its because of wrong placeholders you have used in function call. Inside init you are not passing any parameters to your function. It should be this way

destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values

Or you can just initialise with default method

destination = Node()

UPDATE

Add empty initialiser in your Node class

init() {

}

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

Check if image exists on server using JavaScript?

If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn't exist on the server.

How do I specify different layouts for portrait and landscape orientations?

Create a new directory layout-land, then create xml file with same name in layout-land as it was layout directory and align there your content for Landscape mode.

Note that id of content in both xml is same.

Ternary operator ?: vs if...else

I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.

for each loop in groovy

as simple as:

tmpHM.each{ key, value -> 
  doSomethingWithKeyAndValue key, value
}

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you're using Webpack:

  1. Set up bootstrap-loader as described in docs;
  2. Install tether.js via npm;
  3. Add tether.js to the webpack ProvidePlugin plugin.

webpack.config.js:

plugins: [
        <... your plugins here>,
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.Tether": 'tether'
        })
    ]

Source

batch file Copy files with certain extensions from multiple directories into one directory

Just use the XCOPY command with recursive option

xcopy c:\*.doc k:\mybackup /sy

/s will make it "recursive"

Excel how to fill all selected blank cells with text

I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).

In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.

Sub FillWithNull()

Dim cell As range
Dim myRange As range

Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False

For Each cell In myRange
    If Len(cell) = 0 Then
        cell.Value = "Null"
    End If
Next

Application.ScreenUpdating = True

End Sub

How to create unique keys for React elements?

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
    });

Wherever you're lopping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Generate random array of floats between a range

Alternatively you could use SciPy

from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)

and for the record to sample integers it's

stats.randint(10, 20).rvs(50)

Is string in array?

Just use the already built-in Contains() method:

using System.Linq;

//...

string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
    //...
}

How to post a file from a form with Axios

Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).

As others have said though, ATP should definitely not be turned off for production apps.

1) Use a different plist for Debug

Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.

XCode Debug

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2) Exclude local servers

Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>server.local</key>
        <dict/>
        <key>NSExceptionAllowsInsecureHTTPLoads</key>
        <true/>
    </dict>
</dict>

String.replaceAll single backslashes with double backslashes

You'll need to escape the (escaped) backslash in the first argument as it is a regular expression. Replacement (2nd argument - see Matcher#replaceAll(String)) also has it's special meaning of backslashes, so you'll have to replace those to:

theString.replaceAll("\\\\", "\\\\\\\\");

Good way of getting the user's location in Android

Skyhook (http://www.skyhookwireless.com/) has a location provider that is much faster than the standard one Google provides. It might be what you're looking for. I'm not affiliated with them.

Measuring text height to be drawn on Canvas ( Android )

You could use the android.text.StaticLayout class to specify the bounds required and then call getHeight(). You can draw the text (contained in the layout) by calling its draw(Canvas) method.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text
alt text
alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

    enableInputMethods(true);   
    addMouseListener(this);
    
  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
    
  6. Override this method:

    public void paintComponent(Graphics g)
    

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

ImportError: No module named 'bottle' - PyCharm

pycharm 2019.3 ,my solution is below: enter image description here

open link in iframe

<a href="YOUR_URL" target="_YOUR_IFRAME_NAME">LINK NAME</a>

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Show Image View from file path?

All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.

Did I mention it is super easy to use:

Picasso.with(context).load(new File(...)).into(imageView);

How to use Spring Boot with MySQL database and JPA?

You can move Application.java to a folder under the java.

Typescript sleep

import { timer } from 'rxjs';

await timer(1000).pipe(take(1)).toPromise();

this works better for me

How to calculate DATE Difference in PostgreSQL?

CAST both fields to datatype DATE and you can use a minus:

(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference

Test case:

SELECT  (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM 
    generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);

Result: 31

Or create a function datediff():

CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp) 
RETURNS int 
LANGUAGE sql 
AS
$$
    SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;

Matrix Multiplication in pure Python?

One liner:

def dot(m1, m2):
    return [
        [sum(x * y for x, y in zip(m1_r, m2_c)) for m2_c in zip(*m2)] for m1_r in m1
    ]

Explanation:

zip(*m2) - gets a column from the second matrix

zip(m1_r, m2_c) - creates tuple from m1 row and m2 column

sum(...) - sums multiplication row * col

Test:

m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[7, 8], [9, 10], [11, 12]]
result = dot(m1, m2)
assert result == [[58, 64], [139, 154]]

Is there any kind of hash code function in JavaScript?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

you can use Es6 symbol to create unique key and access object. Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

var obj = {};

obj[Symbol('a')] = 'a';
obj[Symbol.for('b')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

How to resolve 'unrecognized selector sent to instance'?

For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.

How can I label points in this scatterplot?

I have tried directlabels package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.

Cannot invoke an expression whose type lacks a call signature

TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple and Pear don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean member. Because of structural typing, you don' need to inherit Apple and Pear from such an interface.

There are different ways to assign such a compatible type:

Assign type during variable declaration

This statement is implicitly typed to Apple[] | Pear[]:

const fruits = fruitBasket[key];

You can simply use a compatible type explicitly in in your variable declaration:

const fruits: { isDecayed: boolean }[] = fruitBasket[key];

For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple and Pear interfaces don't need to be changed):

type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];

Cast to compatible type for the operation

The problem with the given solution is that it changes the type of the fruits variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits:

const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

Or with the reusable Fruit type:

type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

The advantage of this solution is that both, fruits and freshFruits will be of type Apple[] | Pear[].

How to use sys.exit() in Python

In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:

so:

import sys

and when finished:

sys.exit()

Get current category ID of the active page

I found this question whilst looking for exactly what you asked. Unfortunately you have accepted an incorrect answer. For the sake of other people who are trying to achieve what we were trying to achieve, I thought I'd post the correct answer.

$cur_cat = get_cat_ID( single_cat_title("",false) );

As you said single_term_title("", false); was correctly returning the category title, I'm not sure why you would have had troubles with your code; but the above code works flawlessly for me.

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

How to open html file?

You can read HTML page using 'urllib'.

 #python 2.x

  import urllib

  page = urllib.urlopen("your path ").read()
  print page

Filling a List with all enum values in Java

You can use also:

Collections.singletonList(Something.values())

How to make a vertical SeekBar in Android?

I used Selva's solution but had two kinds of issues:

  • OnSeekbarChangeListener did not work properly
  • Setting progress programmatically did not work properly.

I fixed these two issues. You can find the solution (within my own project package) at

https://github.com/jeisfeld/Augendiagnose/blob/master/AugendiagnoseIdea/augendiagnoseLib/src/main/java/de/jeisfeld/augendiagnoselib/components/VerticalSeekBar.java

Android: how to make keyboard enter button say "Search" and handle its click?

In Kotlin

evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doTheLoginWork()
    }
    true
}

Partial Xml Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginUserEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:imeOptions="actionDone"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>
</LinearLayout>

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

PHP FPM - check if running

For php7.0-fpm I call:

service php7.0-fpm status

php7.0-fpm start/running, process 25993

Now watch for the good part. The process name is actually php-fpm7.0

echo `/bin/pidof php-fpm7.0`

26334 26297 26286 26285 26282

iOS 7.0 No code signing identities found

With fastlane installed, you can create and install an Development Certificate by

cert --development
sigh --development

What's the @ in front of a string in C#?

Putting a @ in front of a string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters.

So you can write:

string path = @"C:\My path\";

instead of:

string path = "C:\\My path\\";

Android simple alert dialog

You can easily make your own 'AlertView' and use it everywhere.

alertView("You really want this?");

Implement it once:

private void alertView( String message ) {
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setTitle( "Hello" )
       .setIcon(R.drawable.ic_launcher)
       .setMessage(message)
//     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//      public void onClick(DialogInterface dialoginterface, int i) {
//          dialoginterface.cancel();   
//          }})
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {   
        }               
        }).show();
 }

How can I use a DLL file from Python?

ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.

I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.

static linking only some libraries

to link dynamic and static library within one line, you must put static libs after dynamic libs and object files, like this:

gcc -lssl main.o -lFooLib -o main

otherwise, it will not work. it does take me sometime to figure it out.

REST API Authentication

You can use HTTP Basic or Digest Authentication. You can securely authenticate users using SSL on the top of it, however, it slows down the API a little bit.

  • Basic authentication - uses Base64 encoding on username and password
  • Digest authentication - hashes the username and password before sending them over the network.

OAuth is the best it can get. The advantages oAuth gives is a revokable or expirable token. Refer following on how to implement: Working Link from comments: https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf

How to invoke a Linux shell command from Java

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

configure: error: C compiler cannot create executables

I just had this issue building apache. The solution I used was the same as Mostafa, I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

This was one Mac OSX Mavericks

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How to store(bitmap image) and retrieve image from sqlite database in android?

If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.

on button click write this

 Intent in = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            in.putExtra("crop", "true");
            in.putExtra("outputX", 100);
            in.putExtra("outputY", 100);
            in.putExtra("scale", true);
            in.putExtra("return-data", true);

            startActivityForResult(in, 1);

then do this in your activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");

            img.setImageBitmap(bmp);
            btnadd.requestFocus();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

            byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
            Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                    bytarray.length);

        }

    }

Configuration with name 'default' not found. Android Studio

Case matters I manually added a submodule :k3b-geohelper to the settings.gradle file

 include ':app', ':k3b-geohelper'

and everthing works fine on my mswindows build system

When i pushed the update to github the fdroid build system failed with

  Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found

The final solution was that the submodule folder was named k3b-geoHelper not k3b-geohelper.

Under MSWindows case doesn-t matter but on linux system it does

S3 - Access-Control-Allow-Origin Header

@jordanstephens said this in a comment, but it kind of gets lost and was a really easy fix for me.

I simply added HEAD method and clicked saved and it started working.

_x000D_
_x000D_
<CORSConfiguration>_x000D_
 <CORSRule>_x000D_
  <AllowedOrigin>*</AllowedOrigin>_x000D_
  <AllowedMethod>GET</AllowedMethod>_x000D_
  <AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->_x000D_
  <MaxAgeSeconds>3000</MaxAgeSeconds>_x000D_
  <AllowedHeader>Authorization</AllowedHeader>_x000D_
 </CORSRule>_x000D_
</CORSConfiguration>
_x000D_
_x000D_
_x000D_

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

Drop all tables whose names begin with a certain string

SELECT 'DROP TABLE "' + TABLE_NAME + '"' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '[prefix]%'

This will generate a script.

Adding clause to check existence of table before deleting:

SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '[prefix]%'

Compare one String with multiple values in one expression

Since this question has been reopened anyway, I might just as well propose an enum solution.

enum ValidValues {
   VAL1, VAL2, VAL3;

   public static boolean isValid(String input) {
       return Stream.of(ValidValues.values())
                    .map(ValidValues::name)
                    .anyMatch(s -> s.equalsIgnoreCase(input));
   }
}

Or you can just use the stream statement with

Stream.of("val1", "val2", "val3")
      .anyMatch(s -> s.equalsIgnoreCase(str))

if you only use it in one place.

How to upgrade Git on Windows to the latest version?

Using the command "where git" find out how command prompt picks up the version. Once you have the path, you can go ahead and uninstall / delete previous version completely. Then if you install and make sure the new installed location is in the path, it should just work fine.

Using git-friendly tools like cmder will make your life much easier. You don't really have to use dual boot or cygwin anymore since the support for git in windows is already top-notch now. (Git for windows installs msysgit which includes all necessary unix tools from MinGW. MinGW has been there for a while and is pretty stable. If you want you can install the full version of msysgit rather than Git for Windows. msysgit is available on Git for windows page at the bottom.)

How do I subtract minutes from a date in javascript?

moment.js has some really nice convenience methods to manipulate date objects

The .subtract method, allows you to subtract a certain amount of time units from a date, by providing the amount and a timeunit string.

var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...

Multiple commands in an alias for bash

On windows, in Git\etc\bash.bashrc I use (at the end of the file)

a(){
    git add $1  
    git status
}

and then in git bash simply write

$ a Config/

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

You can do the folllwoing: import the jar file inside you class:

import javax.servlet.http.HttpServletResponse

add the Apache Tomcat library as follow:

Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok

Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.

I think this will solve your error

Left function in c#

use substring function:

yourString.Substring(0, length);

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

.trim() in JavaScript not working in IE

We can get official code From the internet! Refer this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim

Running the following code before any other code will create trim() if it's not natively available.

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about trim.

defineProperties(StringPrototype, {
 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 // http://perfectionkills.com/whitespace-deviations/
  trim: function trim() {
    if (typeof this === 'undefined' || this === null) {
      throw new TypeError("can't convert " + this + ' to object');
    }
    return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
  }
}, hasTrimWhitespaceBug);

NLS_NUMERIC_CHARACTERS setting for decimal

You can see your current session settings by querying nls_session_parameters:

select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';

VALUE                                  
----------------------------------------
.,                                       

That may differ from the database defaults, which you can see in nls_database_parameters.

In this session your query errors:

select to_number('100,12') from dual;

Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"

I could alter my session, either directly with alter session or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):

alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;

TO_NUMBER('100,12')
-------------------
             100,12 

In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.

But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number(); though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:

alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;

TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
                                                        100.12 

By default the result is still displayed with my session settings, so the decimal separator is still a period.

Command line tool to dump Windows DLL version?

C:\>wmic datafile where name="C:\\Windows\\System32\\kernel32.dll" get version
Version
6.1.7601.18229

ContractFilter mismatch at the EndpointDispatcher exception

I had a similar error. This could be because you would have changed some contract setting on your config file after it was refrenced into you project. solution - Update the webservice reference on you VSstudio project or create a new proxy using svcutil.exe

What Ruby IDE do you prefer?

Ruby in Steel: http://www.sapphiresteel.com/Products/Ruby-In-Steel/Ruby-In-Steel-Developer-Overview

A Visual Studio based Ruby IDE. Fast Debugger. Intellisense.

How to use placeholder as default value in select2 framework

I did the following:

var defaultOption = new Option();
defaultOption.selected = true;    
$(".js-select2").append(defaultOption);

For other options I use then:

var realOption = new Option("Option Value", "id");
realOption.selected = false;    
$(".js-select2").append(realOption);

How to grep, excluding some patterns?

A bit old, but oh well...

The most up-voted solution from @houbysoft will not work as that will exclude any line with "gloom" in it, even if it has "loom". According to OP's expectations, we need to include lines with "loom", even if they also have "gloom" in them. This line needs to be in the output "Arty is slooming in a gloomy day.", but this will be excluded by a chained grep like

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

Instead, the egrep regex example of Bentoy13 works better

egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

as it will include any line with "loom" in it, regardless of whether or not it has "gloom". On the other hand, if it only has gloom, it will not include it, which is precisely the behaviour OP wants.

git pull error "The requested URL returned error: 503 while accessing"

I received the same error when trying to clone a heroku git repository.

Upon accessing heroku dashboard I saw a warning that the tool was under maintenance, and should come back in a few hours.

Cloning into 'foo-repository'...
remote: !        Heroku has temporarily disabled this feature, please try again shortly. See https://status.heroku.com for current Heroku platform status.
fatal: unable to access 'https://git.heroku.com/foo-repository.git/': The requested URL returned error: 503

If you receive the same error, check the service status

Error message: "'chromedriver' executable needs to be available in the path"

We have to add path string, begin with the letter r before the string, for raw string. I tested this way, and it works.

driver = webdriver.Chrome(r"C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

How to add column if not exists on PostgreSQL?

Following select query will return true/false, using EXISTS() function.

EXISTS():
The argument of EXISTS is an arbitrary SELECT statement, or subquery. The subquery is evaluated to determine whether it returns any rows. If it returns at least one row, the result of EXISTS is "true"; if the subquery returns no rows, the result of EXISTS is "false"

SELECT EXISTS(SELECT  column_name 
                FROM  information_schema.columns 
               WHERE  table_schema = 'public' 
                 AND  table_name = 'x' 
                 AND  column_name = 'y'); 

and use the following dynamic SQL statement to alter your table

DO
$$
BEGIN
IF NOT EXISTS (SELECT column_name 
                 FROM  information_schema.columns 
                WHERE  table_schema = 'public' 
                  AND  table_name = 'x' 
                  AND  column_name = 'y') THEN
ALTER TABLE x ADD COLUMN y int DEFAULT NULL;
ELSE
RAISE NOTICE 'Already exists';
END IF;
END
$$

How to get the current TimeStamp?

In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch() static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.

How to create a Java cron job

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }

Detect IF hovering over element with jQuery

Set a flag on hover:

var over = false;
$('#elem').hover(function() {
  over = true;
},
function () {
  over = false;
});

Then just check your flag.

Java Process with Input/Output Stream

Firstly, I would recommend replacing the line

Process process = Runtime.getRuntime ().exec ("/bin/bash");

with the lines

ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectErrorStream(true);
Process process = builder.start();

ProcessBuilder is new in Java 5 and makes running external processes easier. In my opinion, its most significant improvement over Runtime.getRuntime().exec() is that it allows you to redirect the standard error of the child process into its standard output. This means you only have one InputStream to read from. Before this, you needed to have two separate Threads, one reading from stdout and one reading from stderr, to avoid the standard error buffer filling while the standard output buffer was empty (causing the child process to hang), or vice versa.

Next, the loops (of which you have two)

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

only exit when the reader, which reads from the process's standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has this next line.

Since you're sending two lines of input to the process before reaching this loop, the first of these two loops will hang if the process hasn't exited after these two lines of input. It will sit there waiting for another line to be read, but there will never be another line for it to read.

I compiled your source code (I'm on Windows at the moment, so I replaced /bin/bash with cmd.exe, but the principles should be the same), and I found that:

  • after typing in two lines, the output from the first two commands appears, but then the program hangs,
  • if I type in, say, echo test, and then exit, the program makes it out of the first loop since the cmd.exe process has exited. The program then asks for another line of input (which gets ignored), skips straight over the second loop since the child process has already exited, and then exits itself.
  • if I type in exit and then echo test, I get an IOException complaining about a pipe being closed. This is to be expected - the first line of input caused the process to exit, and there's nowhere to send the second line.

I have seen a trick that does something similar to what you seem to want, in a program I used to work on. This program kept around a number of shells, ran commands in them and read the output from these commands. The trick used was to always write out a 'magic' line that marks the end of the shell command's output, and use that to determine when the output from the command sent to the shell had finished.

I took your code and I replaced everything after the line that assigns to writer with the following loop:

while (scan.hasNext()) {
    String input = scan.nextLine();
    if (input.trim().equals("exit")) {
        // Putting 'exit' amongst the echo --EOF--s below doesn't work.
        writer.write("exit\n");
    } else {
        writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");
    }
    writer.flush();

    line = reader.readLine();
    while (line != null && ! line.trim().equals("--EOF--")) {
        System.out.println ("Stdout: " + line);
        line = reader.readLine();
    }
    if (line == null) {
        break;
    }
}

After doing this, I could reliably run a few commands and have the output from each come back to me individually.

The two echo --EOF-- commands in the line sent to the shell are there to ensure that output from the command is terminated with --EOF-- even in the result of an error from the command.

Of course, this approach has its limitations. These limitations include:

  • if I enter a command that waits for user input (e.g. another shell), the program appears to hang,
  • it assumes that each process run by the shell ends its output with a newline,
  • it gets a bit confused if the command being run by the shell happens to write out a line --EOF--.
  • bash reports a syntax error and exits if you enter some text with an unmatched ).

These points might not matter to you if whatever it is you're thinking of running as a scheduled task is going to be restricted to a command or a small set of commands which will never behave in such pathological ways.

EDIT: improve exit handling and other minor changes following running this on Linux.

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

How to stop console from closing on exit?

What about Console.Readline();?

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

Programmatically go back to previous ViewController in Swift

I did it like this

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        self.dismissView()
    }))

    self.present(alert, animated: true)
}

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}

Cell spacing in UICollectionView

I know that the topic is old, but in case anyone still needs correct answer here what you need:

  1. Override standard flow layout.
  2. Add implementation like that:

    - (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray *answer = [super layoutAttributesForElementsInRect:rect];
    
        for(int i = 1; i < [answer count]; ++i) {
            UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
            UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
            NSInteger maximumSpacing = 4;
            NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
    
            if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
                CGRect frame = currentLayoutAttributes.frame;
                frame.origin.x = origin + maximumSpacing;
                currentLayoutAttributes.frame = frame;
            }
        }
        return answer;
    }
    

where maximumSpacing could be set to any value you prefer. This trick guarantees that the space between cells would be EXACTLY equal to maximumSpacing!!

Warning: comparison with string literals results in unspecified behaviour

There is a distinction between 'a' and "a":

  • 'a' means the value of the character a.
  • "a" means the address of the memory location where the string "a" is stored (which will generally be in the data section of your program's memory space). At that memory location, you will have two bytes -- the character 'a' and the null terminator for the string.

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

How do I install ASP.NET MVC 5 in Visual Studio 2012?

If you want to install ASP.NET MVC 5 and ASP.NET Web API 2 into VS 2012 Ultimage so, you can download MSI installer from
http://www.microsoft.com/en-us/download/details.aspx?id=41532.

I have downloaded and intalled just know. I got MVC 5 and Web API 2
:)

JAVA_HOME should point to a JDK not a JRE

In IntelliJ IDEA go to File>Project Structure>SDK>JDK home path. Copy it and then go to My Computer>Advanced Settings>Environment Variables Change the JAVA_HOME path to what you have copied. Then open new cmd, and try mvn -v

It worked for me !!!

Select N random elements from a List<T> in C#

I combined several of the above answers to create a Lazily-evaluated extension method. My testing showed that Kyle's approach (Order(N)) is many times slower than drzaus' use of a set to propose the random indices to choose (Order(K)). The former performs many more calls to the random number generator, plus iterates more times over the items.

The goals of my implementation were:

1) Do not realize the full list if given an IEnumerable that is not an IList. If I am given a sequence of a zillion items, I do not want to run out of memory. Use Kyle's approach for an on-line solution.

2) If I can tell that it is an IList, use drzaus' approach, with a twist. If K is more than half of N, I risk thrashing as I choose many random indices again and again and have to skip them. Thus I compose a list of the indices to NOT keep.

3) I guarantee that the items will be returned in the same order that they were encountered. Kyle's algorithm required no alteration. drzaus' algorithm required that I not emit items in the order that the random indices are chosen. I gather all the indices into a SortedSet, then emit items in sorted index order.

4) If K is large compared to N and I invert the sense of the set, then I enumerate all items and test if the index is not in the set. This means that I lose the Order(K) run time, but since K is close to N in these cases, I do not lose much.

Here is the code:

    /// <summary>
    /// Takes k elements from the next n elements at random, preserving their order.
    /// 
    /// If there are fewer than n elements in items, this may return fewer than k elements.
    /// </summary>
    /// <typeparam name="TElem">Type of element in the items collection.</typeparam>
    /// <param name="items">Items to be randomly selected.</param>
    /// <param name="k">Number of items to pick.</param>
    /// <param name="n">Total number of items to choose from.
    /// If the items collection contains more than this number, the extra members will be skipped.
    /// If the items collection contains fewer than this number, it is possible that fewer than k items will be returned.</param>
    /// <returns>Enumerable over the retained items.
    /// 
    /// See http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp for the commentary.
    /// </returns>
    public static IEnumerable<TElem> TakeRandom<TElem>(this IEnumerable<TElem> items, int k, int n)
    {
        var r = new FastRandom();
        var itemsList = items as IList<TElem>;

        if (k >= n || (itemsList != null && k >= itemsList.Count))
            foreach (var item in items) yield return item;
        else
        {  
            // If we have a list, we can infer more information and choose a better algorithm.
            // When using an IList, this is about 7 times faster (on one benchmark)!
            if (itemsList != null && k < n/2)
            {
                // Since we have a List, we can use an algorithm suitable for Lists.
                // If there are fewer than n elements, reduce n.
                n = Math.Min(n, itemsList.Count);

                // This algorithm picks K index-values randomly and directly chooses those items to be selected.
                // If k is more than half of n, then we will spend a fair amount of time thrashing, picking
                // indices that we have already picked and having to try again.   
                var invertSet = k >= n/2;  
                var positions = invertSet ? (ISet<int>) new HashSet<int>() : (ISet<int>) new SortedSet<int>();

                var numbersNeeded = invertSet ? n - k : k;
                while (numbersNeeded > 0)
                    if (positions.Add(r.Next(0, n))) numbersNeeded--;

                if (invertSet)
                {
                    // positions contains all the indices of elements to Skip.
                    for (var itemIndex = 0; itemIndex < n; itemIndex++)
                    {
                        if (!positions.Contains(itemIndex))
                            yield return itemsList[itemIndex];
                    }
                }
                else
                {
                    // positions contains all the indices of elements to Take.
                    foreach (var itemIndex in positions)
                        yield return itemsList[itemIndex];              
                }
            }
            else
            {
                // Since we do not have a list, we will use an online algorithm.
                // This permits is to skip the rest as soon as we have enough items.
                var found = 0;
                var scanned = 0;
                foreach (var item in items)
                {
                    var rand = r.Next(0,n-scanned);
                    if (rand < k - found)
                    {
                        yield return item;
                        found++;
                    }
                    scanned++;
                    if (found >= k || scanned >= n)
                        break;
                }
            }
        }  
    } 

I use a specialized random number generator, but you can just use C#'s Random if you want. (FastRandom was written by Colin Green and is part of SharpNEAT. It has a period of 2^128-1 which is better than many RNGs.)

Here are the unit tests:

[TestClass]
public class TakeRandomTests
{
    /// <summary>
    /// Ensure that when randomly choosing items from an array, all items are chosen with roughly equal probability.
    /// </summary>
    [TestMethod]
    public void TakeRandom_Array_Uniformity()
    {
        const int numTrials = 2000000;
        const int expectedCount = numTrials/20;
        var timesChosen = new int[100];
        var century = new int[100];
        for (var i = 0; i < century.Length; i++)
            century[i] = i;

        for (var trial = 0; trial < numTrials; trial++)
        {
            foreach (var i in century.TakeRandom(5, 100))
                timesChosen[i]++;
        }
        var avg = timesChosen.Average();
        var max = timesChosen.Max();
        var min = timesChosen.Min();
        var allowedDifference = expectedCount/100;
        AssertBetween(avg, expectedCount - 2, expectedCount + 2, "Average");
        //AssertBetween(min, expectedCount - allowedDifference, expectedCount, "Min");
        //AssertBetween(max, expectedCount, expectedCount + allowedDifference, "Max");

        var countInRange = timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);
        Assert.IsTrue(countInRange >= 90, String.Format("Not enough were in range: {0}", countInRange));
    }

    /// <summary>
    /// Ensure that when randomly choosing items from an IEnumerable that is not an IList, 
    /// all items are chosen with roughly equal probability.
    /// </summary>
    [TestMethod]
    public void TakeRandom_IEnumerable_Uniformity()
    {
        const int numTrials = 2000000;
        const int expectedCount = numTrials / 20;
        var timesChosen = new int[100];

        for (var trial = 0; trial < numTrials; trial++)
        {
            foreach (var i in Range(0,100).TakeRandom(5, 100))
                timesChosen[i]++;
        }
        var avg = timesChosen.Average();
        var max = timesChosen.Max();
        var min = timesChosen.Min();
        var allowedDifference = expectedCount / 100;
        var countInRange =
            timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);
        Assert.IsTrue(countInRange >= 90, String.Format("Not enough were in range: {0}", countInRange));
    }

    private IEnumerable<int> Range(int low, int count)
    {
        for (var i = low; i < low + count; i++)
            yield return i;
    }

    private static void AssertBetween(int x, int low, int high, String message)
    {
        Assert.IsTrue(x > low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));
        Assert.IsTrue(x < high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));
    }

    private static void AssertBetween(double x, double low, double high, String message)
    {
        Assert.IsTrue(x > low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));
        Assert.IsTrue(x < high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));
    }
}

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

invalid types 'int[int]' for array subscript

int myArray[10][10][10];

should be

int myArray[10][10][10][10];

boundingRectWithSize for NSAttributedString returning wrong size

Looks like you weren't providing the correct options. For wrapping labels, provide at least:

CGRect paragraphRect =
  [attributedText boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
  options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
  context:nil];

Note: if the original text width is under 300.f there won't be line wrapping, so make sure the bound size is correct, otherwise you will still get wrong results.

Creating a select box with a search option

Selectize Js has all options we require .Please Try It

_x000D_
_x000D_
  $(document).ready(function () {_x000D_
      $('select').selectize({_x000D_
          sortField: 'text'_x000D_
      });_x000D_
  });
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />_x000D_
</head>_x000D_
<body>_x000D_
  <select id="select-state" placeholder="Pick a state...">_x000D_
    <option value="">Select a state...</option>_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="CA">California</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="DC">District of Columbia</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
  </select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Color Tint UIButton Image

Swift 3:

This solution could be comfortable if you have already setted your image through xCode interface builder. Basically you have one extension to colorize an image:

extension UIImage {
    public func image(withTintColor color: UIColor) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(CGBlendMode.normal)
        let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.clip(to: rect, mask: self.cgImage!)
        color.setFill()
        context.fill(rect)
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
}

Then , you can prepare this UIButton extension to colorize the image for a particular state:

extension UIButton {
    func imageWith(color:UIColor, for: UIControlState) {
        if let imageForState = self.image(for: state) {
            self.image(for: .normal)?.withRenderingMode(.alwaysTemplate)
            let colorizedImage = imageForState.image(withTintColor: color)
            self.setImage(colorizedImage, for: state)
        }
    }
}

Usage:

myButton.imageWith(.red, for: .normal)

P.S. (working good also in table cells, you don't need to call setNeedDisplay() method, the change of the color is immediate due to the UIImage extension..

How can I see what has changed in a file before committing to git?

Go to your respective git repo, then run the below command:

git diff filename

It will open the file with the changes marked, press return/enter key to scroll down the file.

P.S. filename should include the full path of the file or else you can run without the full file path by going in the respective directory/folder of the file

Detecting arrow key presses in JavaScript

That is the working code for chrome and firefox

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script type="text/javascript">

    function leftArrowPressed() {
      alert("leftArrowPressed" );
      window.location = prevUrl  
    }

    function rightArrowPressed() {
      alert("rightArrowPressed" );
      window.location = nextUrl  
    }
    function topArrowPressed() {
      alert("topArrowPressed" );
      window.location = prevUrl  
    }

    function downArrowPressed() {
      alert("downArrowPressed" );
      window.location = nextUrl  
    }

        document.onkeydown = function(evt) {
                        var nextPage = $("#next_page_link")
                        var prevPage = $("#previous_page_link")
                        nextUrl = nextPage.attr("href")
                        prevUrl = prevPage.attr("href")
        evt = evt || window.event;
        switch (evt.keyCode) {
                case 37:
                leftArrowPressed(nextUrl);
                break;

                case 38:
                topArrowPressed(nextUrl);
                break;

                 case 39:
                rightArrowPressed(prevUrl);
                break;

                case 40:
                downArrowPressed(prevUrl);
                break;

        }
    };


</script>
</head>
<body>
<p>
<a id="previous_page_link" href="http://www.latest-tutorial.com">Latest Tutorials</a> 
<a id="next_page_link" href="http://www.zeeshanakhter.com">Zeeshan Akhter</a>
 </p>
</body>
</html>

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

There's no need to downgrade Android Tools. On Windows, Gradle moved from:

C:\Users\you_username\AppData\Local\Android\sdk\tools

to:

C:\Program Files\Android\Android Studio\plugins\android\lib\templates\gradle\wrapper

So you just need to adjust your path so that it points to the right folder.

Response Content type as CSV

MIME type of the CSV is text/csv according to RFC 4180.

htaccess redirect if URL contains a certain string

RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]

(No space inside your website)

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

Static Classes In Java

What's happening when a members inside a class is declared as static..? That members can be accessed without instantiating the class. Therefore making outer class(top level class) static has no meaning. Therefore it is not allowed.

But you can set inner classes as static (As it is a member of the top level class). Then that class can be accessed without instantiating the top level class. Consider the following example.

public class A {
    public static class B {

    }
}

Now, inside a different class C, class B can be accessed without making an instance of class A.

public class C {
    A.B ab = new A.B();
}

static classes can have non-static members too. Only the class gets static.

But if the static keyword is removed from class B, it cannot be accessed directly without making an instance of A.

public class C {
    A a = new A();
    A.B ab = a. new B();
}

But we cannot have static members inside a non-static inner class.

Regular expression to extract URL from an HTML link

this regex can help you, you should get the first group by \1 or whatever method you have in your language.

href="([^"]*)

example:

<a href="http://www.amghezi.com">amgheziName</a>

result:

http://www.amghezi.com

Looping through all the properties of object php

For testing purposes I use the following:

//return assoc array when called from outside the class it will only contain public properties and values 
var_dump(get_object_vars($obj)); 

Reverse order of foreach list items

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

fatal error: iostream.h no such file or directory

That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.

Use #include <iostream> instead. And all the library classes are in the std:: namespace, for ex­am­ple std::cout.

Also, throw away any book or notes that mention the thing you said.

How to enable DataGridView sorting when user clicks on the column header?

You can use DataGridViewColoumnHeaderMouseClick event like this :

Private string order = String.Empty;
private void dgvDepartment_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (order == "d")
{
        order = "a";                
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })   .OrderBy(s => s.Apellidos).ToList();
    }
    else
    {
        order = "d";
        dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth }.OrderByDescending(s => s.Apellidos)  .ToList()
    }
}

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Here is another, very manual solution. You can define the size of the axis and paddings are considered accordingly (including legend and tickmarks). Hope it is of use to somebody.

Example (axes size are the same!):

enter image description here

Code:

#==================================================
# Plot table

colmap = [(0,0,1) #blue
         ,(1,0,0) #red
         ,(0,1,0) #green
         ,(1,1,0) #yellow
         ,(1,0,1) #magenta
         ,(1,0.5,0.5) #pink
         ,(0.5,0.5,0.5) #gray
         ,(0.5,0,0) #brown
         ,(1,0.5,0) #orange
         ]


import matplotlib.pyplot as plt
import numpy as np

import collections
df = collections.OrderedDict()
df['labels']        = ['GWP100a\n[kgCO2eq]\n\nasedf\nasdf\nadfs','human\n[pts]','ressource\n[pts]'] 
df['all-petroleum long name'] = [3,5,2]
df['all-electric']  = [5.5, 1, 3]
df['HEV']           = [3.5, 2, 1]
df['PHEV']          = [3.5, 2, 1]

numLabels = len(df.values()[0])
numItems = len(df)-1
posX = np.arange(numLabels)+1
width = 1.0/(numItems+1)

fig = plt.figure(figsize=(2,2))
ax = fig.add_subplot(111)
for iiItem in range(1,numItems+1):
  ax.bar(posX+(iiItem-1)*width, df.values()[iiItem], width, color=colmap[iiItem-1], label=df.keys()[iiItem])
ax.set(xticks=posX+width*(0.5*numItems), xticklabels=df['labels'])

#--------------------------------------------------
# Change padding and margins, insert legend

fig.tight_layout() #tight margins
leg = ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
plt.draw() #to know size of legend

padLeft   = ax.get_position().x0 * fig.get_size_inches()[0]
padBottom = ax.get_position().y0 * fig.get_size_inches()[1]
padTop    = ( 1 - ax.get_position().y0 - ax.get_position().height ) * fig.get_size_inches()[1]
padRight  = ( 1 - ax.get_position().x0 - ax.get_position().width ) * fig.get_size_inches()[0]
dpi       = fig.get_dpi()
padLegend = ax.get_legend().get_frame().get_width() / dpi 

widthAx = 3 #inches
heightAx = 3 #inches
widthTot = widthAx+padLeft+padRight+padLegend
heightTot = heightAx+padTop+padBottom

# resize ipython window (optional)
posScreenX = 1366/2-10 #pixel
posScreenY = 0 #pixel
canvasPadding = 6 #pixel
canvasBottom = 40 #pixel
ipythonWindowSize = '{0}x{1}+{2}+{3}'.format(int(round(widthTot*dpi))+2*canvasPadding
                                            ,int(round(heightTot*dpi))+2*canvasPadding+canvasBottom
                                            ,posScreenX,posScreenY)
fig.canvas._tkcanvas.master.geometry(ipythonWindowSize) 
plt.draw() #to resize ipython window. Has to be done BEFORE figure resizing!

# set figure size and ax position
fig.set_size_inches(widthTot,heightTot)
ax.set_position([padLeft/widthTot, padBottom/heightTot, widthAx/widthTot, heightAx/heightTot])
plt.draw()
plt.show()
#--------------------------------------------------
#==================================================

Position Relative vs Absolute?

Both “relative” and “absolute” positioning are really relative, just with different framework. “Absolute” positioning is relative to the position of another, enclosing element. “Relative” positioning is relative to the position that the element itself would have without positioning.

It depends on your needs and goals which one you use. “Relative” position is suitable when you wish to displace an element from the position it would otherwise have in the flow of elements, e.g. to make some characters appear in a superscript position. “Absolute” positioning is suitable for placing an element in some system of coordinates set by another element, e.g. to “overprint” an image with some text.

As a special, use “relative” positioning with no displacement (just setting position: relative) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).

How do I measure separate CPU core usage for a process?

dstat -C 0,1,2,3 

Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.

For example, if you only interested in core 3 and 7 then you could do

dstat -C 3,7

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

How to downgrade tensorflow, multiple versions possible?

You can try to use the options of --no-cache-dir together with -I to overwrite the cache of the previous version and install the new version. For example:

pip3 install --no-cache-dir -I tensorflow==1.1

Then use the following command to check the version of tensorflow:

python3 -c ‘import tensorflow as tf; print(tf.__version__)’

It should show the right version got installed.

Using bootstrap with bower

There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.

bower install bootstrap-css

Thanks Nico.

W3WP.EXE using 100% CPU - where to start?

It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

There is a typo error in define arguments, change DB_HOST into DB_SERVER and DB_USER into DB_USERNAME:

<?php

    define("DB_SERVER", "localhost");
    define("DB_USERNAME", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "databasename");
    $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

?>

Git command to display HEAD commit id?

You can specify git log options to show only the last commit, -1, and a format that includes only the commit ID, like this:

git log -1 --format=%H

If you prefer the shortened commit ID:

git log -1 --format=%h

'heroku' does not appear to be a git repository

Following official Heroku article:

Initialize GIT

$ cd myapp
$ git init

$ git add .
$ git commit -m "my first commit"

Then create (initialize) heroku app with:

$ heroku create YourAppName

Lastly add git remote:

$ heroku git:remote -a YourAppName

Now you can safely deploy your app with:

$ git push heroku master

You should wait for some time and see if you don't get any error/interrupt on console while deploying. For details look at heroku article.

C# 4.0 optional out/ref arguments

ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

Selecting the first "n" items with jQuery

I found this note in the end of the lt() docs:

Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

So use $("selector").slice(from, to) for better performances.

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

how to delete all cookies of my website in php

All previous answers have overlooked that the setcookie could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com domain, there might be a cookie set on tar.com. Therefore, you want to unset cookies for all domains that might have dropped the cookie:

$host = explode('.', $_SERVER['HTTP_HOST']);

while ($host) {
    $domain = '.' . implode('.', $host);

    foreach ($_COOKIE as $name => $value) {
        setcookie($name, '', 1, '/', $domain);
    }

    array_shift($host);
}

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

File to byte[] in Java

// Returns the contents of the file in a byte array.
    public static byte[] getBytesFromFile(File file) throws IOException {        
        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
            throw new IOException("File is too large!");
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;

        InputStream is = new FileInputStream(file);
        try {
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }
        } finally {
            is.close();
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        return bytes;
    }

Trigger to fire only if a condition is met in SQL Server

Given that a WHERE clause did not work, maybe this will:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON

      If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
      Begin
          Return
      End

      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      Attribute,
      ParameterValue,
      ParameterDescription,
      ChangeDate
    FROM Inserted AS I
END

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.