Programs & Examples On #Doctrine orm

Doctrine 2.0 is a PHP (5.3.2+) ORM. While Doctrine 1.2 uses the Active Record pattern, Doctrine 2 uses the Data Mapper pattern. The Doctrine project is a collection of open source libraries and tools for dealing with database abstraction and Object-Relational Mapping written in PHP.

Default value in Doctrine

You can do it using xml as well:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

Doctrine findBy 'does not equal'

There is now a an approach to do this, using Doctrine's Criteria.

A full example can be seen in How to use a findBy method with comparative criteria, but a brief answer follows.

use \Doctrine\Common\Collections\Criteria;

// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));

// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);

How to select distinct query using symfony2 doctrine query builder?

This works:

$category = $catrep->createQueryBuilder('cc')
        ->select('cc.categoryid')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->distinct()
        ->getQuery();

$categories = $category->getResult();

Edit for Symfony 3 & 4.

You should use ->groupBy('cc.categoryid') instead of ->distinct()

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

With php5.4 now you can do :

use JsonSerializable;

/**
* @Entity(repositoryClass="App\Entity\User")
* @Table(name="user")
*/
class MyUserEntity implements JsonSerializable
{
    /** @Column(length=50) */
    private $name;

    /** @Column(length=50) */
    private $login;

    public function jsonSerialize()
    {
        return array(
            'name' => $this->name,
            'login'=> $this->login,
        );
    }
}

And then call

json_encode(MyUserEntity);

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

The EntityManager is closed

Same problem, solved with a simple code refactoring. The problem is sometime present when a required field is null, before do anithing, try to refactor your code. A better workflow can solve the problem.

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

How to order results with findBy() in Doctrine

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I was getting from a conflict with join table defined in an association class ( with additional custom fields ) annotation and a join table defined in a many-to-many annotation.

The mapping definitions in two entities with a direct many-to-many relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.

The explanation and solution is that identified by FMaz008 above. In my situation, it was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the associative entity class. There is an example provided in this forum post Association models with extra fields:

public class Person {

  /** @OneToMany(targetEntity="AssignedItems", mappedBy="person") */
  private $assignedItems;

}

public class Items {

    /** @OneToMany(targetEntity="AssignedItems", mappedBy="item") */
    private $assignedPeople;
}

public class AssignedItems {

    /** @ManyToOne(targetEntity="Person")
    * @JoinColumn(name="person_id", referencedColumnName="id")
    */
private $person;

    /** @ManyToOne(targetEntity="Item")
    * @JoinColumn(name="item_id", referencedColumnName="id")
    */
private $item;

}

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

How to sort findAll Doctrine's method?

I use an alternative to the solution that wrote nifr.

$resultRows = $repository->fetchAll();
uasort($resultRows, function($a, $b){
    if ($a->getProperty() == $b->getProperty()) {
        return 0;
    }
    return ($a->getProperty()< $b->getProperty()) ? -1 : 1;
});

It's quicker than the ORDER BY clause, and without the overhead of the Iterator.

Count Rows in Doctrine QueryBuilder

For people who are using only Doctrine DBAL and not the Doctrine ORM, they will not be able to access the getQuery() method because it doesn't exists. They need to do something like the following.

$qb = new QueryBuilder($conn);
$count = $qb->select("count(id)")->from($tableName)->execute()->fetchColumn(0);

Set LIMIT with doctrine 2?

I use Doctrine\ORM\Tools\Pagination\Paginator for this, and it works perfectly (doctrine 2.2).

$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
                       ->setFirstResult(0)
                       ->setMaxResults(10);

$paginator = new Paginator($query, $fetchJoinCollection = true);

How to use a findBy method with comparative criteria

You have to use either DQL or the QueryBuilder. E.g. in your Purchase-EntityRepository you could do something like this:

$q = $this->createQueryBuilder('p')
          ->where('p.prize > :purchasePrize')
          ->setParameter('purchasePrize', 200)
          ->getQuery();

$q->getResult();

For even more complex scenarios take a look at the Expr() class.

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

How to use WHERE IN with Doctrine 2

The best way doing this - especially if you're adding more than one condition - is:

$values = array(...); // array of your values
$qb->andWhere('where', $qb->expr()->in('r.winner', $values));

If your array of values contains strings, you can't use the setParameter method with an imploded string, because your quotes will be escaped!

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Get single row result with Doctrine NativeQuery

I just want one result

implies that you expect only one row to be returned. So either adapt your query, e.g.

SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
LIMIT 0, 1

(and then use getSingleResult() as recommended by AdrienBrault) or fetch rows as an array and access the first item:

// ...
$players = $query->getArrayResult();
$myPlayer = $players[0];

Background thread with QThread in PyQt

Based on the Worker objects methods mentioned in other answers, I decided to see if I could expand on the solution to invoke more threads - in this case the optimal number the machine can run and spin up multiple workers with indeterminate completion times. To do this I still need to subclass QThread - but only to assign a thread number and to 'reimplement' the signals 'finished' and 'started' to include their thread number.

I've focused quite a bit on the signals between the main gui, the threads, and the workers.

Similarly, others answers have been a pains to point out not parenting the QThread but I don't think this is a real concern. However, my code also is careful to destroy the QThread objects.

However, I wasn't able to parent the worker objects so it seems desirable to send them the deleteLater() signal, either when the thread function is finished or the GUI is destroyed. I've had my own code hang for not doing this.

Another enhancement I felt was necessary was was reimplement the closeEvent of the GUI (QWidget) such that the threads would be instructed to quit and then the GUI would wait until all the threads were finished. When I played with some of the other answers to this question, I got QThread destroyed errors.

Perhaps it will be useful to others. I certainly found it a useful exercise. Perhaps others will know a better way for a thread to announce it identity.

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  To demonstrate creation of multiple threads and identify the receipt of thread results
# Created: 19/12/15

import sys


from PyQt4.QtCore import QThread, pyqtSlot, pyqtSignal
from PyQt4.QtGui import QApplication, QLabel, QWidget, QGridLayout

import sys
import worker

class Thread(QThread):
    #make new signals to be able to return an id for the thread
    startedx = pyqtSignal(int)
    finishedx = pyqtSignal(int)

    def __init__(self,i,parent=None):
        super().__init__(parent)
        self.idd = i

        self.started.connect(self.starttt)
        self.finished.connect(self.finisheddd)

    @pyqtSlot()
    def starttt(self):
        print('started signal from thread emitted')
        self.startedx.emit(self.idd) 

    @pyqtSlot()
    def finisheddd(self):
        print('finished signal from thread emitted')
        self.finishedx.emit(self.idd)

class Form(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

        self.worker={}
        self.threadx={}
        self.i=0
        i=0

        #Establish the maximum number of threads the machine can optimally handle
        #Generally relates to the number of processors

        self.threadtest = QThread(self)
        self.idealthreadcount = self.threadtest.idealThreadCount()

        print("This machine can handle {} threads optimally".format(self.idealthreadcount))

        while i <self.idealthreadcount:
            self.setupThread(i)
            i+=1

        i=0
        while i<self.idealthreadcount:
            self.startThread(i)
            i+=1

        print("Main Gui running in thread {}.".format(self.thread()))


    def setupThread(self,i):

        self.worker[i]= worker.Worker(i)  # no parent!
        #print("Worker object runningt in thread {} prior to movetothread".format(self.worker[i].thread()) )
        self.threadx[i] = Thread(i,parent=self)  #  if parent isn't specified then need to be careful to destroy thread 
        self.threadx[i].setObjectName("python thread{}"+str(i))
        #print("Thread object runningt in thread {} prior to movetothread".format(self.threadx[i].thread()) )
        self.threadx[i].startedx.connect(self.threadStarted)
        self.threadx[i].finishedx.connect(self.threadFinished)

        self.worker[i].finished.connect(self.workerFinished)
        self.worker[i].intReady.connect(self.workerResultReady)

        #The next line is optional, you may want to start the threads again without having to create all the code again.
        self.worker[i].finished.connect(self.threadx[i].quit)

        self.threadx[i].started.connect(self.worker[i].procCounter)

        self.destroyed.connect(self.threadx[i].deleteLater)
        self.destroyed.connect(self.worker[i].deleteLater)

        #This is the key code that actually get the worker code onto another processor or thread.
        self.worker[i].moveToThread(self.threadx[i])

    def startThread(self,i):
        self.threadx[i].start()

    @pyqtSlot(int)
    def threadStarted(self,i):
        print('Thread {}  started'.format(i))
        print("Thread priority is {}".format(self.threadx[i].priority()))        


    @pyqtSlot(int)
    def threadFinished(self,i):
        print('Thread {} finished'.format(i))




    @pyqtSlot(int)
    def threadTerminated(self,i):
        print("Thread {} terminated".format(i))

    @pyqtSlot(int,int)
    def workerResultReady(self,j,i):
        print('Worker {} result returned'.format(i))
        if i ==0:
            self.label1.setText("{}".format(j))
        if i ==1:
            self.label2.setText("{}".format(j))
        if i ==2:
            self.label3.setText("{}".format(j))
        if i ==3:
            self.label4.setText("{}".format(j)) 

        #print('Thread {} has started'.format(self.threadx[i].currentThreadId()))    

    @pyqtSlot(int)
    def workerFinished(self,i):
        print('Worker {} finished'.format(i))

    def initUI(self):
        self.label1 = QLabel("0")
        self.label2= QLabel("0")
        self.label3= QLabel("0")
        self.label4 = QLabel("0")
        grid = QGridLayout(self)
        self.setLayout(grid)
        grid.addWidget(self.label1,0,0)
        grid.addWidget(self.label2,0,1) 
        grid.addWidget(self.label3,0,2) 
        grid.addWidget(self.label4,0,3) #Layout parents the self.labels

        self.move(300, 150)
        self.setGeometry(0,0,300,300)
        #self.size(300,300)
        self.setWindowTitle('thread test')
        self.show()

    def closeEvent(self, event):
        print('Closing')

        #this tells the threads to stop running
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].quit()
            i+=1

         #this ensures window cannot be closed until the threads have finished.
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].wait() 
            i+=1        


        event.accept()


if __name__=='__main__':
    app = QApplication(sys.argv)
    form = Form()
    sys.exit(app.exec_())

And the worker code below

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  Stack Overflow
# Created: 19/12/15

import sys
import unittest


from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
import random


class Worker(QObject):
    finished = pyqtSignal(int)
    intReady = pyqtSignal(int,int)

    def __init__(self, i=0):
        '''__init__ is called while the worker is still in the Gui thread. Do not put slow or CPU intensive code in the __init__ method'''

        super().__init__()
        self.idd = i



    @pyqtSlot()
    def procCounter(self): # This slot takes no params
        for j in range(1, 10):
            random_time = random.weibullvariate(1,2)
            time.sleep(random_time)
            self.intReady.emit(j,self.idd)
            print('Worker {0} in thread {1}'.format(self.idd, self.thread().idd))

        self.finished.emit(self.idd)


if __name__=='__main__':
    unittest.main()

Attach a body onload event with JS

Cross browser window.load event

function load(){}

window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )

Maintaining the final state at end of a CSS3 animation

IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards is AFTER the animation declaration or it will not work...

animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;

vs

animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;

Disable ScrollView Programmatically?

Does this help?

((ScrollView)findViewById(R.id.QuranGalleryScrollView)).setOnTouchListener(null);

How can I hide an HTML table row <tr> so that it takes up no space?

You can set

<table>
  <tr style="visibility: hidden"></tr>
</table> 

What is a mixin, and why are they useful?

OP mentioned that he/she never heard of mixin in C++, perhaps that is because they are called Curiously Recurring Template Pattern (CRTP) in C++. Also, @Ciro Santilli mentioned that mixin is implemented via abstract base class in C++. While abstract base class can be used to implement mixin, it is an overkill as the functionality of virtual function at run-time can be achieved using template at compile time without the overhead of virtual table lookup at run-time.

The CRTP pattern is described in detail here

I have converted the python example in @Ciro Santilli's answer into C++ using template class below:

    #include <iostream>
    #include <assert.h>

    template <class T>
    class ComparableMixin {
    public:
        bool operator !=(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) == static_cast<T&>(other));
        }
        bool operator <(ComparableMixin &other) {
            return ((*(this) != other) && (*static_cast<T*>(this) <= static_cast<T&>(other)));
        }
        bool operator >(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) <= static_cast<T&>(other));
        }
        bool operator >=(ComparableMixin &other) {
            return ((*static_cast<T*>(this) == static_cast<T&>(other)) || (*(this) > other));
        }
        protected:
            ComparableMixin() {}
    };

    class Integer: public ComparableMixin<Integer> {
    public:
     Integer(int i) {
         this->i = i;
     }
     int i;
     bool operator <=(Integer &other) {
         return (this->i <= other.i);
     }
     bool operator ==(Integer &other) {
         return (this->i == other.i);
     }
    };

int main() {

    Integer i(0) ;
    Integer j(1) ;
    //ComparableMixin<Integer> c; // this will cause compilation error because constructor is protected.
    assert (i < j );
    assert (i != j);
    assert (j >  i);
    assert (j >= i);

    return 0;
}

EDIT: Added protected constructor in ComparableMixin so that it can only be inherited and not instantiated. Updated the example to show how protected constructor will cause compilation error when an object of ComparableMixin is created.

mysqli::query(): Couldn't fetch mysqli

Check if db name do not have "_" or "-" that helps in my case

Android dex gives a BufferOverflowException when building

Try what van said:

Right click your projectandroid toolsandroid support library.

Hope this helps :)

Byte Array to Hex String

Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit
import binascii

number = 10000

def using_str_format() -> str:
    return "".join("{:02x}".format(x) for x in test_obj)

def using_format() -> str:
    return "".join(format(x, "02x") for x in test_obj)

def using_hexlify() -> str:
    return binascii.hexlify(bytearray(test_obj)).decode('ascii')

def do_test():
    print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
    if using_str_format() != using_format() != using_hexlify():
        raise RuntimeError("Results are not the same")

    print("Using str.format       -> " + str(timeit(using_str_format, number=number)))
    print("Using format           -> " + str(timeit(using_format, number=number)))
    print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))

test_obj = bytes([i for i in range(255)])
do_test()

test_obj = bytearray([i for i in range(255)])
do_test()

Result:

Testing with 255-byte bytes:
Using str.format       -> 1.459474583090427
Using format           -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format       -> 1.443447684109402
Using format           -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684

Methods using format do provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How to sanity check a date in Java

As shown by @Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.

However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:

Invalid characters in the date string Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.

Years: 2, 3 or 4 digits? You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")

A Strict Solution with the Standard Library

So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.

  Date parseDate(String maybeDate, String format, boolean lenient) {
    Date date = null;

    // test date string matches format structure using regex
    // - weed out illegal characters and enforce 4-digit year
    // - create the regex based on the local format string
    String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
    reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
    if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {

      // date string matches format structure, 
      // - now test it can be converted to a valid date
      SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
      sdf.applyPattern(format);
      sdf.setLenient(lenient);
      try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
    } 
    return date;
  } 

  // used like this:
  Date date = parseDate( "21/5/2009", "d/M/yyyy", false);

Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:

Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();

Joda Time - Better Alternative?

I've been hearing about joda time recently and thought I'd compare. Two points:

  1. Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat
  2. Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own DateTimeFormatter for this purpose)

It's quite simple to use:

import org.joda.time.format.*;
import org.joda.time.DateTime;

org.joda.time.DateTime parseDate(String maybeDate, String format) {
  org.joda.time.DateTime date = null;
  try {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
    date =  fmt.parseDateTime(maybeDate);
  } catch (Exception e) { }
  return date;
}

Pass value to iframe from a window

What you have to do is to append the values as parameters in the iframe src (URL).

E.g. <iframe src="some_page.php?somedata=5&more=bacon"></iframe>

And then in some_page.php file you use php $_GET['somedata'] to retrieve it from the iframe URL. NB: Iframes run as a separate browser window in your file.

How to split a long array into smaller arrays, with JavaScript

function chunkArrayInGroups(arr, size) {
    var newArr=[];

    for (var i=0; i < arr.length; i+= size){
    newArr.push(arr.slice(i,i+size));
    }
    return newArr;

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

TypeError: 'list' object is not callable while trying to access a list

For accessing the elements of a list you need to use the square brackets ([]) and not the parenthesis (()).

Instead of:

print  wordlists(len(words))

you need to use:

print worldlists[len(words)]

And instead of:

(wordlists(len(words))).append(words)

you need to use:

worldlists[len(words)].append(words)

Outline effect to text

This mixin for SASS will give smooth results, using 8-axis:

@mixin stroke($size: 1px, $color: #000) {
  text-shadow:
    -#{$size} -#{$size} 0 $color,
     0        -#{$size} 0 $color,
     #{$size} -#{$size} 0 $color,
     #{$size}  0        0 $color,
     #{$size}  #{$size} 0 $color,
     0         #{$size} 0 $color,
    -#{$size}  #{$size} 0 $color,
    -#{$size}  0        0 $color;
}

And normal CSS:

text-shadow:
  -1px -1px 0 #000,
   0   -1px 0 #000,
   1px -1px 0 #000,
   1px  0   0 #000,
   1px  1px 0 #000,
   0    1px 0 #000,
  -1px  1px 0 #000,
  -1px  0   0 #000;

ExecuteNonQuery: Connection property has not been initialized.

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

How to get current timestamp in milliseconds since 1970 just the way Java gets

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}

How can I prevent the backspace key from navigating back?

Simplest way to prevent navigation on pressing backspace

$(document).keydown(function () {
    if (event.keyCode == 8) {
        if (event.target.nodeName == 'BODY') {
            event.preventDefault();
        }
    }
});

Insert php variable in a href

echo '<a href="' . $folder_path . '">Link text</a>';

Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.

EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

The PYTHONPATH environment variable is used by Python to specify a list of directories that modules can be imported from on Windows. When running, you can inspect the sys.path variable to see which directories will be searched when you import something.

To set this variable from the Command Prompt, use: set PYTHONPATH=list;of;paths.

To set this variable from PowerShell, use: $env:PYTHONPATH=’list;of;paths’ just before you launch Python.

Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use. Read more in the Python on Windows FAQ docs.

Scroll Automatically to the Bottom of the Page

A simple way if you want to scroll down specific element

Call this function whenever you want to scroll down.

_x000D_
_x000D_
function scrollDown() {_x000D_
 document.getElementById('scroll').scrollTop =  document.getElementById('scroll').scrollHeight_x000D_
}
_x000D_
ul{_x000D_
 height: 100px;_x000D_
 width: 200px;_x000D_
 overflow-y: scroll;_x000D_
 border: 1px solid #000;_x000D_
}
_x000D_
<ul id='scroll'>_x000D_
<li>Top Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Bottom Here</li>_x000D_
<li style="color: red">Bottom Here</li>_x000D_
</ul>_x000D_
_x000D_
<br />_x000D_
_x000D_
<button onclick='scrollDown()'>Scroll Down</button>
_x000D_
_x000D_
_x000D_

How do I install TensorFlow's tensorboard?

Adding this just for the sake of completeness of this question (some questions may get closed as duplicate of this one).

I usually use user mode for pip ie. pip install --user even if instructions assume root mode. That way, my tensorboard installation was in ~/.local/bin/tensorboard, and it was not in my path (which shouldn't be ideal either). So I was not able to access it.

In this case, running

sudo ln -s ~/.local/bin/tensorboard /usr/bin

should fix it.

Importing json file in TypeScript

In your TS Definition file, e.g. typings.d.ts`, you can add this line:

declare module "*.json" {
const value: any;
export default value;
}

Then add this in your typescript(.ts) file:-

import * as data from './colors.json';
const word = (<any>data).name;

Return outside function error in Python

It basically occours when you return from a loop you can only return from function

Key Presses in Python

Install the pywin32 extensions. Then you can do the following:

import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want

Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.

EDIT: Sending F11

import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")

# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")

How to effectively work with multiple files in Vim

You may want to use Vim global marks.

This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short: 'C takes me to the code I'm working with, 'T takes me to the unit test I'm working with.

When you change places, resetting the marks is quick too: mC marks the new code spot, mT marks the new test spot.

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

Centos 7 php install comes with the ModSecurity package installed and enabled which prevents web access to phpMyAdmin. At the end of phpMyAdmin.conf, you should find

# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc.  This may break your mod_security implementation.
#
#<IfModule mod_security.c>
#    <Directory /usr/share/phpMyAdmin/>
#        SecRuleInheritance Off
#    </Directory>
#</IfModule>

which gives you the answer to the problem. By adding

    SecRuleEngine Off

in the block "Directory /usr/share/phpMyAdmin/", you can solve the 'denied access' to phpmyadmin, but you may create security issues.

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

jQuery location href

Ideally, you want to be using window.location.replace(...).

See this answer here for a full explanation: How do I redirect to another webpage?

How to make a smaller RatingBar?

After a lot of research I found the best solution to reduce the size of custom rating bars is to get the size of progress drawable in certain sizes as mentioned below :

xxhdpi - 48*48 px

xhdpi - 36*36 px

hdpi - 24*24 px

And in style put the minheight and maxheight as 16 dp for all Resolution.

Let me know if this doesn't help you to get a best small size rating bars as these sizes I found very compatible and equivalent to ratingbar.small style attribute.

Call break in nested if statements

In the most languages, break does only cancel loops like for, while etc.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Escaping ampersand character in SQL string

Escape is set to \ by default, so you don't need to set it; but if you do, don't wrap it in quotes.

Ampersand is the SQL*Plus substitution variable marker; but you can change it, or more usefully in your case turn it off completely, with:

set define off

Then you don't need to bother escaping the value at all.

Accept server's self-signed ssl certificate in Java client

If 'they' are using a self-signed certificate it is up to them to take the steps required to make their server usable. Specifically that means providing their certificate to you offline in a trustworthy way. So get them to do that. You then import that into your truststore using the keytool as described in the JSSE Reference Guide. Don't even think about the insecure TrustManager posted here.

EDIT For the benefit of the seventeen (!) downvoters, and numerous commenters below, who clearly have not actually read what I have written here, this is not a jeremiad against self-signed certificates. There is nothing wrong with self-signed certificates when implemented correctly. But, the correct way to implement them is to have the certificate delivered securely via an offline process, rather than via the unauthenticated channel they are going to be used to authenticate. Surely this is obvious? It is certainly obvious to every security-aware organization I have ever worked for, from banks with thousands of branches to my own companies. The client-side code-base 'solution' of trusting all certificates, including self-signed certificates signed by absolutely anybody, or any arbitary body setting itself up as a CA, is ipso facto not secure. It is just playing at security. It is pointless. You are having a private, tamperproof, reply-proof, injection-proof conversation with ... somebody. Anybody. A man in the middle. An impersonator. Anybody. You may as well just use plaintext.

Can't install nuget package because of "Failed to initialize the PowerShell host"

I updated the Nuget package manager and that fixed it for me.

How do I run Redis on Windows?

I've provided installation instructions and downloads for the 2 most popular ways of running Redis on windows at: https://github.com/mythz/redis-windows that shows how to:

  1. Use Vagrant to run the latest stable version of Redis inside a VirtualBox VM.
  2. Download and run Microsoft's Native Windows port of Redis

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

How to create a sub array from another array in Java?

Arrays.copyOfRange(..) was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)

How can I check if some text exist or not in the page using Selenium?

With XPath, it's not that hard. Simply search for all elements containing the given text:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.

The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.

To learn XPath, just follow the internet. The spec is also a surprisingly good read.


EDIT:

Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

rdtsc solution did not work for me.

Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.

Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.

I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk

This fixed the issue for me.

Truncate a string straight JavaScript

_x000D_
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to embed a Facebook page's feed into my website

In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.

  1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

_x000D_
_x000D_
<div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
  var js, fjs = d.getElementsByTagName(s)[0];_x000D_
  if (d.getElementById(id)) return;_x000D_
  js = d.createElement(s); js.id = id;_x000D_
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
  fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
_x000D_
_x000D_

  1. Place the code for your plugin wherever you want the plugin to appear on your page.

_x000D_
_x000D_
<div class="fb-page" _x000D_
     data-href="https://www.facebook.com/YourPageName" _x000D_
     data-tabs="timeline" _x000D_
     data-small-header="false" _x000D_
     data-adapt-container-width="true" _x000D_
     data-hide-cover="false" _x000D_
     data-show-facepile="true">_x000D_
  <div class="fb-xfbml-parse-ignore">_x000D_
    <blockquote cite="https://www.facebook.com/facebook">_x000D_
      <a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also change the following settings:

enter image description here

Also You can now have timeline, events and messages tabs with the new page plugin:

  • Timeline Tab: Will show the most recent posts of your Facebook Page timeline.
  • Events Tab: People can follow your page events and subscribe to events from the plugin.
  • Messages Tab: People can message your page directly from your website. People need to be logged in to use this feature.

_x000D_
_x000D_
<div class="fb-page" _x000D_
  data-tabs="timeline,events,messages"_x000D_
  data-href="https://www.facebook.com/YourPageName"_x000D_
  data-width="380" _x000D_
  data-hide-cover="false">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Defining custom attrs

Currently the best documentation is the source. You can take a look at it here (attrs.xml).

You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.

An <attr> element has two xml attributes name and format. name lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute. The format attribute can have different values depending on the 'type' of attribute you want.

  • reference - if it references another resource id (e.g, "@color/my_color", "@layout/my_layout")
  • color
  • boolean
  • dimension
  • float
  • integer
  • string
  • fraction
  • enum - normally implicitly defined
  • flag - normally implicitly defined

You can set the format to multiple types by using |, e.g., format="reference|color".

enum attributes can be defined as follows:

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag attributes are similar except the values need to be defined so they can be bit ored together:

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

In addition to attributes there is the <declare-styleable> element. This allows you to define attributes a custom view can use. You do this by specifying an <attr> element, if it was previously defined you do not specify the format. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name, as follows.

An example of a custom view <declare-styleable>:

<declare-styleable name="MyCustomView">
  <attr name="my_custom_attribute" />
  <attr name="android:gravity" />
</declare-styleable>

When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android". You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto".

Example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:whatever="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <org.example.mypackage.MyCustomView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>

Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);

  String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);

  //do something with str

  a.recycle();
}

The end. :)

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    public static void ExportToExcel(DataGridView dgView)
    {
        Microsoft.Office.Interop.Excel.Application excelApp = null;
        try
        {
            // instantiating the excel application class
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
            currentWorksheet.Columns.ColumnWidth = 18;


            if (dgView.Rows.Count > 0)
            {
                currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
                int i = 1;
                foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
                {
                    // Excel work sheet indexing starts with 1
                    currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                    ++i;
                }
                Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
                headerColumnRange.Font.Bold = true;
                headerColumnRange.Font.Color = 0xFF0000;
                //headerColumnRange.EntireColumn.AutoFit();
                int rowIndex = 0;
                for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
                {
                    DataGridViewRow dgRow = dgView.Rows[rowIndex];
                    for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                    {
                        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                    }
                }
                Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
                fullTextRange.WrapText = true;
                fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("s");
                timeStamp = timeStamp.Replace(':', '-');
                timeStamp = timeStamp.Replace("T", "__");
                currentWorksheet.Cells[1, 1] = timeStamp;
                currentWorksheet.Cells[1, 2] = "No error occured";
            }
            using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
            {
                exportSaveFileDialog.Title = "Select Excel File";
                exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

                if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
                {
                    string fullFileName = exportSaveFileDialog.FileName;
                   // currentWorkbook.SaveCopyAs(fullFileName);
                    // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                    // the save file dialogue box

                    currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    currentWorkbook.Saved = true;
                    MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.Quit();
            }
        }



    }

Tomcat request timeout

For anyone who doesn't like none of the solutions posted above like me then you can simply implement a timer yourself and stop the request execution by throwing a runtime exception. Something like below:

                  try 
                 {
                     timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                         timer.cancel();
                       }
                     }, /* specify time of the requst */ 1000);
                 }
                 catch(Exception e)
                 {
                   throw new RuntimeException("the request is taking longer than usual");
                 }

   

or preferably use the java guava timeLimiter here

How to replace space with comma using sed?

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

Android turn On/Off WiFi HotSpot programmatically

APManager - Access Point Manager

Step 1 : Add the jcenter repository to your build file
allprojects {
    repositories {
        ...
        jcenter()
    }
}
Step 2 : Add the dependency
dependencies {
    implementation 'com.vkpapps.wifimanager:APManager:1.0.0'
}
Step 3 use in your app
APManager apManager = APManager.getApManager(this);
apManager.turnOnHotspot(this, new APManager.OnSuccessListener() {

    @Override
    public void onSuccess(String ssid, String password) {
        //write your logic
    }

}, new APManager.OnFailureListener() {

    @Override
    public void onFailure(int failureCode, @Nullable Exception e) {
        //handle error like give access to location permission,write system setting permission,
        //disconnect wifi,turn off already created hotspot,enable GPS provider
        
        //or use DefaultFailureListener class to handle automatically
    }

});

check out source code https://github.com/vijaypatidar/AndroidWifiManager

What's the simplest way to print a Java array?

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

What does href expression <a href="javascript:;"></a> do?

There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.

A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.

You can use a more semantic name such as #disable, or #action to increase readability.

Benefits of the approach:

  • Avoids the "moving to the top" effect of the empty href="#"
  • Avoids the use of javascript

Drawbacks:

  • You must be sure the anchor name is not used in the document.
  • The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.

Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.

How can I display a tooltip message on hover using jQuery?

You can use bootstrap tooltip. Do not forget to initialize it.

<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>

Will be shown text Explanation on the left side.

and run it with js:

$('.tooltip-r').tooltip();

Presto SQL - Converting a date string to date format

Converted DateID having date in Int format to date format: Presto Query

Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
from
     Table_Name
limit 10;

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

Python-Requests close http connection

On Requests 1.X, the connection is available on the response object:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json",
                  data={'track': toTrack}, auth=('username', 'passwd'))

r.connection.close()

Copy an entire worksheet to a new worksheet in Excel 2010

I really liked @brettdj's code, but then I found that when I added additional code to edit the copy, it overwrote my original sheet instead. I've tweaked his answer so that further code pointed at ws1 will affect the new sheet rather than the original.

Sub Test()
    Dim ws1 as Worksheet
    ThisWorkbook.Worksheets("Master").Copy
    Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub

How to get css background color on <tr> tag to span entire row

Try this:

    .rowhighlight > td { background: green;}

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Jquery .on('scroll') not firing the event while scrolling

Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?

Then you can use:

$('#ulId').on('scroll',function(){ console.log('Event Fired'); })

obviously replacing ulId with whatever the actual id of the scrollable div is.

Then set css display: block; on the #ulId (or containing div) upon load?

How to use FormData for AJAX file upload?

View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
                $(document).on('change', ':file', function () {
                    var fileUpload = $(this).get(0);
                    var files = fileUpload.files;
                    var bid = 0;
                    if (files.length != 0) {
                        var data = new FormData();
                        for (var i = 0; i < files.length ; i++) {
                            data.append(files[i].name, files[i]);
                        }
                        $.ajax({
                            xhr: function () {
                                var xhr = $.ajaxSettings.xhr();
                                xhr.upload.onprogress = function (e) {
                                    console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                };
                                return xhr;
                            },
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            data: data,
                            url: '/ControllerX/' + bid,
                            success: function (response) {
                                location.href = 'xxx/Index/';
                            }
                        });
                    }
                });
            });
</Script>
Controller:
[HttpPost]
        public ActionResult ControllerX(string id)
        {
            var files = Request.Form.Files;
...

smtp configuration for php mail

Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)

In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm

Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at https://my.justhost.com/cgi/help/26 (under Outgoing Mail Server)

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

How can I get all a form's values that would be submitted without submitting

The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.

var queryString = $('#myFormId').formSerialize();

From http://malsup.com/jquery/form

Or using straight jquery:

var queryString = $('#myFormId').serialize();

IndexOf function in T-SQL

You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Maximum value of maxRequestLength?

As per MSDN the default value is 4096 KB (4 MB).

UPDATE

As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295

Removing all unused references from a project in Visual Studio projects

For Visual Studio 2013/2015/2017 there is an extension that does exactly what you want: ResolveUR. What this basically does is:

  • reference is removed in the project
  • project is compiled with msbuild
  • check for build errors
  • restore removed references if there were build errors.

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

'namespace' but is used like a 'type'

I had this problem as I created a class "Response.cs" inside a folder named "Response". So VS was catching the new Response () as Folder/namespace.

So I changed the class name to StatusResponse.cs and called new StatusResponse().This solved the issue.

JavaScript Promises - reject vs. throw

There's one difference — which shouldn't matter — that the other answers haven't touched on, so:

There's no difference that's likely to matter, no. Yes, there is a very small difference.

If the fulfillment handler passed to then throws, the promise returned by that call to then is rejected with what was thrown.

If it returns a rejected promise, the promise returned by the call to then is resolved to that promise (and will ultimately be rejected, since the promise it's resolved to is rejected), which may introduce one extra async "tick" (one more loop in the microtask queue, to put it in browser terms).

Any code that relies on that difference is fundamentally broken, though. :-) It shouldn't be that sensitive to the timing of the promise settlement.

Here's an example:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}
function usingReject(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                return Promise.reject(new Error(`${v} is not 42!`));
            }
            return v;
        });
}

// The rejection handler on this chain may be called **after** the
// rejection handler on the following chain
usingReject(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingReject:", e.message));

// The rejection handler on this chain may be called **before** the
// rejection handler on the preceding chain
usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

If you run that, as of this writing you get:

Error from usingThrow: 2 is not 42!
Error from usingReject: 1 is not 42!

Note the order.

Compare that to the same chains but both using usingThrow:

_x000D_
_x000D_
function usingThrow(val) {
    return Promise.resolve(val)
        .then(v => {
            if (v !== 42) {
                throw new Error(`${v} is not 42!`);
            }
            return v;
        });
}

usingThrow(1)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));

usingThrow(2)
.then(v => console.log(v))
.catch(e => console.error("Error from usingThrow:", e.message));
_x000D_
_x000D_
_x000D_

which shows that the rejection handlers ran in the other order:

Error from usingThrow: 1 is not 42!
Error from usingThrow: 2 is not 42!

I said "may" above because there's been some work in other areas that removed this unnecessary extra tick in other similar situations if all of the promises involved are native promises (not just thenables). (Specifically: In an async function, return await x originally introduced an extra async tick vs. return x while being otherwise identical; ES2020 changed it so that if x is a native promise, the extra tick is removed.)

Again, any code that's that sensitive to the timing of the settlement of a promise is already broken. So really it doesn't/shouldn't matter.

In practical terms, as other answers have mentioned:

  • As Kevin B pointed out, throw won't work if you're in a callback to some other function you've used within your fulfillment handler — this is the biggie
  • As lukyer pointed out, throw abruptly terminates the function, which can be useful (but you're using return in your example, which does the same thing)
  • As Vencator pointed out, you can't use throw in a conditional expression (? :), at least not for now

Other than that, it's mostly a matter of style/preference, so as with most of those, agree with your team what you'll do (or that you don't care either way), and be consistent.

Check a collection size with JSTL

<c:if test="${companies.size() > 0}">

</c:if>

This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt instead of >.

<c:if test="${companies.size() gt 0}">

</c:if>

If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length() function then. From the documentation:

length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.

Put this at the top of JSP page to allow the fn namespace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Or if you're using JSPX or Facelets:

<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">

And use like this in your page:

<p>The length of the companies collection is: ${fn:length(companies)}</p>

So to test with length of a collection:

<c:if test="${fn:length(companies) gt 0}">

</c:if>

Alternatively, for this specific case you can also simply use the EL empty operator:

<c:if test="${not empty companies}">

</c:if>

Can Linux apps be run in Android?

yes i have done that on several rooted machines i set a debian linux on a sdcard by dd. i copy this script http://jeanmichel.gens.free.fr/etc/install on /system/bin

i have not yet succeed to run a Xserver but i can use xwindows binaries through the android Xserver application

i can run update my debian with apt-get upgrade , run an apache server with PHP , run a ssh server and all binaries on a terminal including user management i have also a problem with semaphores handling please contact me if you have any trouble

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

How to assign a NULL value to a pointer in python?

left = None

left is None #evaluates to True

Typescript sleep

This works: (thanks to the comments)

setTimeout(() => 
{
    this.router.navigate(['/']);
},
5000);

Eclipse error: R cannot be resolved to a variable

I assume you have updated ADT with version 22 and R.java file is not getting generated.

If this is the case, then here is the solution:

Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.

enter image description here

Setting Windows PATH for Postgres tools

I am using Windows 8 and the above solutions did not work out for me. I downgraded Postgres from 9.4 to 9.3. Man,it worked :)

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

It might be worth verifying that the gmail account hasn't been locked out due to several unsuccessful login attempts, you may need to reset your password. I had the same problem as you, and this turned out to be the solution.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Can you force Vue.js to reload/re-render?

In order to reload/re-render/refresh component, stop the long codings. There is a Vue.JS way of doing that.

Just use :key attribute.

For example:

<my-component :key="unique" />

I am using that one in BS Vue Table Slot. Telling that I will do something for this component so make it unique.

How to spawn a process and capture its STDOUT in .NET?

I just tried this very thing and the following worked for me:

StringBuilder outputBuilder;
ProcessStartInfo processStartInfo;
Process process;

outputBuilder = new StringBuilder();

processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "<insert command line arguments here>";
processStartInfo.FileName = "<insert tool path here>";

process = new Process();
process.StartInfo = processStartInfo;
// enable raising events because Process does not raise events by default
process.EnableRaisingEvents = true;
// attach the event handler for OutputDataReceived before starting the process
process.OutputDataReceived += new DataReceivedEventHandler
(
    delegate(object sender, DataReceivedEventArgs e)
    {
        // append the new data to the data already read-in
        outputBuilder.Append(e.Data);
    }
);
// start the process
// then begin asynchronously reading the output
// then wait for the process to exit
// then cancel asynchronously reading the output
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();

// use the output
string output = outputBuilder.ToString();

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

Node/Express file upload

I needed to be walked through with a bit more detail than the other answers provided (e.g. how do I write the file to a location I decide at runtime?). Hopefully this is of help to others:  

get connect-busboy:

npm install connect-busboy --save

In your server.js, add these lines

let busboy = require('connect-busboy')

// ... 

app.use(busboy());

// ... 

app.post('/upload', function(req, res) {
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename) {
        var fstream = fs.createWriteStream('./images/' + filename); 
        file.pipe(fstream);
        fstream.on('close', function () {
            res.send('upload succeeded!');
        });
    });
});

This would seem to omit error handling though... will edit it in if I find it.

error opening trace file: No such file or directory (2)

You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.

How to draw text using only OpenGL methods?

I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on http://content.gpwiki.org/index.php/OpenGL:Tutorials:Font_System though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.

With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.

Checkbox value true/false

Use Checked = true

$("#checkbox1").prop('checked', true);

Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){}) is a wrong in the question.

How to convert C++ Code to C

While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).

I would suggest at least looking at a re-design to compare how this would work out.

Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?

T-SQL XOR Operator

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

Enabling HTTPS on express.js

I ran into a similar issue with getting SSL to work on a port other than port 443. In my case I had a bundle certificate as well as a certificate and a key. The bundle certificate is a file that holds multiple certificates, node requires that you break those certificates into separate elements of an array.

    var express = require('express');
    var https = require('https');
    var fs = require('fs');

    var options = {
      ca: [fs.readFileSync(PATH_TO_BUNDLE_CERT_1), fs.readFileSync(PATH_TO_BUNDLE_CERT_2)],
      cert: fs.readFileSync(PATH_TO_CERT),
      key: fs.readFileSync(PATH_TO_KEY)
    };

    app = express()

    app.get('/', function(req,res) {
        res.send('hello');
    });

    var server = https.createServer(options, app);

    server.listen(8001, function(){
        console.log("server running at https://IP_ADDRESS:8001/")
    });

In app.js you need to specify https and create the server accordingly. Also, make sure that the port you're trying to use is actually allowing inbound traffic.

Python MYSQL update statement

Neither of them worked for me for some reason.

I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.

And finally this worked for me.

   cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
   connect.commit()

Change navbar text color Bootstrap

For changing the text color in navbar you can use inline css as;

<a style="color: #3c6afc" href="#">

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

delete all from table

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

TRUNCATE TABLE table_name

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Comparing two input values in a form validation with AngularJS

I recently wrote a custom directive which can be generic enough to do any validation. It take a validation function from the current scope

module.directive('customValidator', [function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: { validateFunction: '&' },
            link: function (scope, elm, attr, ngModelCtrl) {
                ngModelCtrl.$parsers.push(function (value) {
                    var result = scope.validateFunction({ 'value': value });
                    if (result || result === false) {
                        if (result.then) {
                            result.then(function (data) {           //For promise type result object
                                ngModelCtrl.$setValidity(attr.customValidator, data);
                            }, function (error) {
                                ngModelCtrl.$setValidity(attr.customValidator, false);
                            });
                        }
                        else {
                            ngModelCtrl.$setValidity(attr.customValidator, result);
                            return result ? value : undefined;      //For boolean result return based on boolean value
                        }
                    }
                    return value;
                });
            }
        };
    }]);

To use it you do

<input type="email" name="email2" ng-model="emailReg2" custom-validator='emailMatch' data-validate-function='checkEmailMatch(value)'>
<span ng-show="registerForm.email2.$error.emailMatch">Emails have to match!</span>

In you controller then you can implement the method, that should return true or false

$scope.checkEmailMatch=function(value) {
    return value===$scope.emailReg;
}

The advantage is that you do not have to write custom directive for each custom validation.

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming you've got access to a standard Unix shell and/or cygwin environment:

tr -s ' ' '\n' < yourfile | sort | uniq -d -c
       ^--space char

Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.

PHP Converting Integer to Date, reverse of strtotime

Can you try this,

echo date("Y-m-d H:i:s", 1388516401);

As noted by theGame,

This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.

echo strtotime("2014-01-01 00:00:01");

This will return into the value 1388516401, which is the UNIX timestamp for the date 2014-01-01. This can be confirmed using the date() function as like below:

echo date('Y-m-d', 1198148400); // echos 2014-01-01

docker error - 'name is already in use by container'

TL:DR;

List all containers:
docker ps -a
Remove the concerned container by id:
docker container rm <container_id>

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

Get local IP address in Node.js

If you're into the whole brevity thing, here it is using Lodash:

_x000D_
_x000D_
var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();

console.log('First local IPv4 address is ' + firstLocalIp);
_x000D_
_x000D_
_x000D_

What's the difference between identifying and non-identifying relationships?

Non-identifying relationship

A non-identifying relationship means that a child is related to parent but it can be identified by its own.

PERSON    ACCOUNT
======    =======
pk(id)    pk(id)
name      fk(person_id)
          balance

The relationship between ACCOUNT and PERSON is non-identifying.

Identifying relationship

An identifying relationship means that the parent is needed to give identity to child. The child solely exists because of parent.

This means that foreign key is a primary key too.

ITEM      LANGUAGE    ITEM_LANG
====      ========    =========
pk(id)    pk(id)      pk(fk(item_id))
name      name        pk(fk(lang_id))
                      name

The relationship between ITEM_LANG and ITEM is identifying. And between ITEM_LANG and LANGUAGE too.

How to import Maven dependency in Android Studio/IntelliJ?

I am using the springframework android artifact as an example

open build.gradle

Then add the following at the same level as apply plugin: 'android'

apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
   compile group: 'org.springframework.android', name: 'spring-android-rest-template', version: '1.0.1.RELEASE'
}

you can also use this notation for maven artifacts

compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

Your IDE should show the jar and its dependencies under 'External Libraries' if it doesn't show up try to restart the IDE (this happened to me quite a bit)

here is the example that you provided that works

buildscript { 
    repositories { 
        maven { 
            url 'repo1.maven.org/maven2'; 
        } 
    } 
    dependencies { 
        classpath 'com.android.tools.build:gradle:0.4' 
    } 
} 
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies { 
    compile files('libs/android-support-v4.jar') 
    compile group:'com.squareup.picasso', name:'picasso', version:'1.0.1' 
} 
android { 
    compileSdkVersion 17 
    buildToolsVersion "17.0.0" 
    defaultConfig { 
        minSdkVersion 14 
        targetSdkVersion 17 
    } 
} 

How to install mongoDB on windows?

Mongo Installation Process in Windows

Are you ready for the installation … and use … Technically, it’s not an installation it’s just Downloading…

I. Download the zip file http://www.mongodb.org/downloads

II. Extract it and copy the files into your desired location.

III. Start the DB engine.

IV. Test the installation and use it.

That's it! So simple, right? Ok let’s start


1. Download the zip file

  1. Go to http://www.mongodb.org/downloads

  2. You will see a screen like this: The mongo download page I am using a windows 7 32 bit machine - that’s why I downloaded the package marked in red.

  3. Click download (It only takes a few seconds).
    Wow... I got that downloaded. It was a zipped file called mongodb-win32-i386-2.4.4.zip (The name of the folder will change according to the version you download, here I got version 2.4.4).

OK all set.


2. Extract

  1. Extract the zip
  2. Copy the files into a desired location in your machine.
    • I am going to copy the extracted files to my D drive, since I don’t have many files there.
    • Alright then where are you planning to paste the mongo files? In C: or in your Desktop itself?
    • Ok, no matter where you paste... In the snap shot below, you can see that I have navigated to the bin folder inside the Mongo folder. I count fifteen files inside bin. What about you?

The path to the bin folder

Finished! That’s all

What we have to do next?


3. Start the DB engine

Let’s go and start using our mongo db...

  1. Open up a command prompt, then navigate to bin in the mongo folder Navigating to mongo's bin folder

  2. Type mongo.exe (which is the command used to start mongo Db Power shell). Then see the below response.. Executing mongo.exe That was an awesome exception J LOL … What is that?

    Couldn’t connect to server.

    Why did the exception happen? I have no idea... Did I create a server in between?

    No.

    Right, then how come it connected to a server in between? Silly Machine …Jz.

    I got it! Like all other DBs - we have to start the DB engine before we use it.

    So, how can we start it?

  3. We have to start the mongo db by using the command mongod. Execute this from the bin folder of mongo.

    Let’s see what had happened.

    error message

    Again a wonderfully formatted exception J we got right? Did you notice what I have highlighted on top? Yeah it is the mongod command. The second one is the exception asking us to create a folder called data. And, inside the data folder, a folder called db.

    So we have to create these data\db folders.

    The next question is where to create these folders?

  4. We have to create the data\db folders in the C drive of our BOX in which we are installing mongo. Let’s go and create the folder structure in C drive.

    A question arises here: "Is it mandatory to create the data\db directories inside C?" Nooo, not really. Mongo looks in C by default for this folder, but you can create them wherever you want. However, if it's not in C, you have to tell mongo where it is.

    In other words, if you don't want the mongo databases to be on C:\, you have to set the db path for mongo.exe.

    Optional

    • Ok, I will create those folders in some other location besides C for better understanding of this option. I will create then in the D drive root, with the help of cmd.

      Why? Because it’s an opportunity for us to remember the old dos commands...

      md data

    • The next step is to set the Db path to mongo.exe.

      Navigate back to bin, and enter the command, mongod.exe --dbpath d:\data.

      I got the response below:

      --dbpath

      I Hope everything went well... Because I didn’t see any ERROR *** in the console J.

    Next, we can go and start the db using the command start mongo.exe

    start mongo.exe

    I didn't see any error or warning messages. But, we have to supply a command to make sure mongo is up and running, i.e. mongod will get a response:

    mongodb response

Hope everything went well.


4. Test the Mongo DB installation

Now we have to see our DB right? Yea very much, Otherwise how will we know it’s running?

For testing purpose MONGO has got a DB called test by default. Lets go query that.

But how without any management studios? Unlike SQL, we have to depend on the command prompt. Yes exactly the same command prompt… our good old command prompt… Heiiiii.. Don’t get afraid yes it’s our old command prompt only. Ok let’s go and see how we are going to use it…

Ohhh Nooo… don’t close the above Command prompt, leave it as it is…

  1. Open a new cmd window.

  2. Navigate to Bin as usual we do…

    I am sure you people may be remembering the old C programming which we have done on our college day’s right?

  3. In the command prompt, execute the command mongo or mongo.exe again and see what happens.

    You will get a screen as shown below:

    startup warning

  4. I mentioned before that Mongo has got a test db by default called test, try inserting a record into it.

    The next question here is "How will we insert?" Does mongo have SQL commands? No, mongo has got only commands to help with.

    The basic command to insert is
    db.test.save( { KodothTestField: ‘My name is Kodoth’ } )

    Where test is the DB and .save is the insert command. KodothTestField is the column or field name, and My name is Kodoth is the value.

  5. Before talking more let’s check whether it’s stored or not by performing another command: db.test.find()

    Mongo command to search for a document, similar to SELECT in SQL.

    Our Data got successfully inserted … Hurrayyyyyy..

    I know that you are thinking about the number which is displayed with every record right called ObjectId. It’s like a unique id field in SQL that auto-increments and all. Have a closer look you can see that the Object Id ends with 92, so it’s different for each and every record.

    At last we are successful in installing and verifying the MONGO right. Let’s have a party... So do you agree now MONGO is as Sweet as MANGO?

Also we have 3rd party tools to explore the MONGO. One is called MONGO VUE. Using this tool we can perform operations against the mongo DB like we use Management studio for SQL Server.

Can you just imagine an SQL server or Oracle Db with entirely different rows in same table? Is it possible in our relational DB table? This is how mongo works. I will show you how we can do that…


First I will show you how the data will look in a relational DB.

For example consider an Employee table and a Student table in relational way. The schemas would be entirely different right? Yes exactly…

results view

Let us now see how it will look in Mongo DB. The above two tables are combined into single Collection in Mongo…

MongoVUE

This is how Collections are stored in Mongo. I think now you can feel the difference really right? Every thing came under a single umbrella. This is not the right way but I just wanted to show you all how this happens that’s why I combined 2 entirely different tables in to one single Collection.

If you want to try out you can use below test scripts

*********************** 
TEST INSERT SCRIPT

*********EMPLOYEE****** 
db.test.save( { EmployeId: "1", EmployeFirstName: "Kodoth", EmployeLastName:"KodothLast", EmployeAge:"14" } )  
db.test.save( { EmployeId: "2", EmployeFirstName: "Kodoth 2", EmployeLastName:"Kodoth Last2", EmployeAge:"14" } )  
db.test.save( { EmployeId: "3", EmployeFirstName: "Kodoth 3", EmployeLastName:"Kodoth Last3", EmployeAge:"14" } ) 

******STUDENT****** 
db.test.save( { StudentId: "1", StudentName: "StudentName", StudentMark:"25" } )  
db.test.save( { StudentId: "2", StudentName: "StudentName 2", StudentMark:"26" } )  
db.test.save( {StudentId: "3", StudentName: "StudentName 3", StudentMark:"27"} )
************************

Thanks

How to use table variable in a dynamic sql statement?

On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.

So from the code you posted you could use this approach for @TSku but not for @RelPro

Example syntax below.

CREATE TYPE MyTable AS TABLE 
( 
Foo int,
Bar int
);
GO


DECLARE @T AS MyTable;

INSERT INTO @T VALUES (1,2), (2,3)

SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T

EXEC sp_executesql
  N'SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
    FROM @T',
  N'@T MyTable READONLY',
  @T=@T 

The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.

How do you create a toggle button?

I don't think using JS for creating a button is good practice. What if the user's browser deactivates JavaScript ?

Plus, you can just use a checkbox and a bit of CSS to do it. And it easy to retrieve the state of your checkbox.

This is just one example, but you can style it how want.

http://jsfiddle.net/4gjZX/

HTML

<fieldset class="toggle">
  <input id="data-policy" type="checkbox" checked="checked" />
  <label for="data-policy">
  <div class="toggle-button">
    <div class="toggle-tab"></div>
  </div>
  Toggle
  </label>
</fieldset>?

CSS

.toggle label {
  color: #444;
  float: left;
  line-height: 26px;
}
.toggle .toggle-button {
  margin: 0px 10px 0px 0px;
  float: left;
  width: 70px;
  height: 26px;
  background-color: #eeeeee;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));
  background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -o-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);
  background-image: linear-gradient(top, #eeeeee, #fafafa);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border: 1px solid #D1D1D1;
}
.toggle .toggle-button .toggle-tab {
  width: 30px;
  height: 26px;
  background-color: #fafafa;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));
  background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -o-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);
  background-image: linear-gradient(top, #fafafa, #eeeeee);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');
  border: 1px solid #CCC;
  margin-left: -1px;
  margin-top: -1px;
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}
.toggle input[type=checkbox] {
  display: none;
}
.toggle input[type=checkbox]:checked ~ label .toggle-button {
  background-color: #2d71c2;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));
  background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: linear-gradient(top, #2d71c2, #4ea1db);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');
}
.toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {
  margin-left: 39px;
  -webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}?

Hope this helps

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

Bootstrap 3 Navbar Collapse

Thanks to Seb33300 I got this working. However, an important part seems to be missing. At least in Bootstrap version 3.1.1.

My problem was that the navbar collapsed accordingly at the correct width, but the menu button didn't work. I couldn't expand and collapse the menu.

This is because the collapse.in class is overrided by the !important in .navbar-collapse.collapse, and can be solved by also adding the "collapse.in". Seb33300's example completed below:

@media (max-width: 991px) {
    .navbar-header {
        float: none;
    }
    .navbar-toggle {
        display: block;
    }
    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }
    .navbar-collapse.collapse {
        display: none!important;
    }
    .navbar-collapse.collapse.in {
        display: block!important;
    }
    .navbar-nav {
        float: none!important;
        margin: 7.5px -15px;
    }
    .navbar-nav>li {
        float: none;
    }
    .navbar-nav>li>a {
        padding-top: 10px;
        padding-bottom: 10px;
    }
}

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Can HTML be embedded inside PHP "if" statement?

Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).

Better is to use heredoc syntax. It is the same concept as in other languages (like bash).

 <?php
 if ($condition) {
   echo <<< END_OF_TEXT
     <b>lots of html</b> <i>$variable</i>
     lots of text...
 many lines possible, with any indentation, until the closing delimiter...
 END_OF_TEXT;
 }
 ?>

END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.

Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).

Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Initializing data.frames()

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Adding options to select with javascript

Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');

X close button only using css

_x000D_
_x000D_
<div style="width: 10px; height: 10px; position: relative; display: flex; justify-content: center;">
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(45deg); border-radius: 2px;"></div>
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(-45deg); border-radius: 2px;"></div>
</div>
_x000D_
_x000D_
_x000D_

How to find the Windows version from the PowerShell command line

Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer

returns

WindowsProductName    WindowsVersion OsHardwareAbstractionLayer
------------------    -------------- --------------------------
Windows 10 Enterprise 1709           10.0.16299.371 

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

WebElement xx = driver.findElement(By.linkText("your element"));
                Actions action = new Actions(driver);
                System.out.println("To open new tab");
                  action.contextClick(xx).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_DOWN);
                    robot.keyPress(KeyEvent.VK_ENTER);

Want to upgrade project from Angular v5 to Angular v6

Check the step by step upgrade details from Angular 5 to Angular 6. These provides details on issues you encounter during upgrade and how to resolve them.

  • Update your node version to 8 or above and Install Angular cli latest globally by npm i -g @angular/cli@latest.
  • Angular 6 uses angular.json as configuration file instead of .anguar-cli.json. Also tslint has been changed. Check https://github.com/angular/angular-cli/wiki/angular-workspace for latest configuration details. You have to move any of your existing configuration to new configuration file.
  • To do this create another dummy project with latest cli using ng new ‘your-project’ and same defaults such as prefix, style etc you used earlier for your project. Create new project with cli https://github.com/angular/angular-cli/wiki/new
  • Use https://update.angular.io/ to check what has been changed from your current version of Angular ? Angular 6. It provides usage of how to change/fix them.
  • Follow the steps above and copy/update the angular.json file created in step2. Do npm i in your project to get all dependencies and do npm update
  • Now comes the big part. RxJS upgrade and resolving conflicts. RxJS has standardised imports of operators and Observable creators with this release. Do npm i -g rxjs-tslint and add below lint configuration in tslint.json
{
  "rulesDirectory": [
    "node_modules/rxjs-tslint"
  ],
  "rules": {
    "rxjs-collapse-imports": true,
    "rxjs-pipeable-operators-only": true,
    "rxjs-no-static-observable-methods": true,
    "rxjs-proper-imports": true
  }
}
  • Now run ng lint --fix. This fixes few items but most of the remaining issues will be highlighted and you have to fix it manually.

Operators Name change:

do -> tap, 
catch -> catchError, 
switch -> switchAll, 
finally -> finalize

All operators moved to rxjs/operators

import { map, filter, reduce } from 'rxjs/operators';

Observable creation methods are moved to rxjs

   import { Observable, Subject, of, from } from 'rxjs'; 

You are all set. Welcome to Angular 6 :) Check my blog post here on how to upgrade

Count the number of occurrences of a character in a string in Javascript

This below is the simplest logic, which is very easy to understand

  //Demo string with repeat char 
  let str = "Coffee"
  //Splitted the str into an char array for looping
  let strArr = str.split("")
  //This below is the final object which holds the result
  let obj = {};
  //This loop will count char (You can also use traditional one for loop)
  strArr.forEach((value,index)=>{
      //If the char exists in the object it will simple increase its value
      if(obj[value] != undefined)
      {
          obj[value] = parseInt(obj[value]) + 1;
      }//else it will add the new one with initializing 1
      else{
          obj[value] =1;
      }      
  });

  console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}

How to insert data to MySQL having auto incremented primary key?

In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.

INSERT INTO test.authors (
   instance_id,host_object_id,check_type,is_raw_check,
   current_check_attempt,max_check_attempts,state,state_type,
   start_time,start_time_usec,end_time,end_time_usec,command_object_id,
   command_args,command_line,timeout,early_timeout,execution_time,
   latency,return_code,output,long_output,perfdata
) VALUES (
   '1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
   '2012-01-03 12:50:59','198963','21','',
   '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
   '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
   '','rta=2.860000m=0%;80;100;0'
);

How many times a substring occurs

You could use the startswith method:

def count_substring(string, sub_string):
    x = 0
    for i in range(len(string)):
        if string[i:].startswith(sub_string):
            x += 1
    return x

Importing a CSV file into a sqlite3 database table using Python

You're right that .import is the way to go, but that's a command from the SQLite3.exe shell. A lot of the top answers to this question involve native python loops, but if your files are large (mine are 10^6 to 10^7 records), you want to avoid reading everything into pandas or using a native python list comprehension/loop (though I did not time them for comparison).

For large files, I believe the best option is to create the empty table in advance using sqlite3.execute("CREATE TABLE..."), strip the headers from your CSV files, and then use subprocess.run() to execute sqlite's import statement. Since the last part is I believe the most pertinent, I will start with that.

subprocess.run()

from pathlib import Path
db_name = Path('my.db').resolve()
csv_file = Path('file.csv').resolve()
result = subprocess.run(['sqlite3',
                         str(db_name),
                         '-cmd',
                         '.mode csv',
                         '.import '+str(csv_file).replace('\\','\\\\')
                                 +' <table_name>'],
                        capture_output=True)

Explanation
From the command line, the command you're looking for is sqlite3 my.db -cmd ".mode csv" ".import file.csv table". subprocess.run() runs a command line process. The argument to subprocess.run() is a sequence of strings which are interpreted as a command followed by all of it's arguments.

  • sqlite3 my.db opens the database
  • -cmd flag after the database allows you to pass multiple follow on commands to the sqlite program. In the shell, each command has to be in quotes, but here, they just need to be their own element of the sequence
  • '.mode csv' does what you'd expect
  • '.import '+str(csv_file).replace('\\','\\\\')+' <table_name>' is the import command.
    Unfortunately, since subprocess passes all follow-ons to -cmd as quoted strings, you need to double up your backslashes if you have a windows directory path.

Stripping Headers

Not really the main point of the question, but here's what I used. Again, I didn't want to read the whole files into memory at any point:

with open(csv, "r") as source:
    source.readline()
    with open(str(csv)+"_nohead", "w") as target:
        shutil.copyfileobj(source, target)

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

The pma_table_uiprefs table contains user preferences. In phpMyAdmin's config.inc.php, access to this table (and other tables in the configuration storage) is done via the control user. In your case, the controluser parameter is empty, therefore the query fails.

For a short-term fix, put the "//" characters in config.inc.php at the start of this line:

    $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';

then log out and log back in.

For a long-term fix, correctly set up the configuration storage, see http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage

Could not find method compile() for arguments Gradle

It should be exclude module: 'net.milkbowl:vault:1.2.27'(add module:) as explained in documentation for DependencyHandler linked from http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html#dependencies(groovy.lang.Closure) because ModuleDependency.exclude(java.util.Map) method is used.

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

Scrolling to an Anchor using Transition/CSS3

While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.

So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:

HTML

<div class="header">
    <p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
    <p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
    <p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
    <p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
    <div id="S1" class="curtain">
    blabla
    </div>
    <div id="S2" class="curtain">
    blabla
    </div>
    <div id="S3" class="curtain">
    blabla
    </div>
    <div id="S4" class="curtain">
    blabla
    </div>
 </div>

NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).

JS code:

<script>
function scrollTo(to, duration) {
    if (document.body.scrollTop == to) return;
    var diff = to - document.body.scrollTop;
    var scrollStep = Math.PI / (duration / 10);
    var count = 0, currPos;
    start = element.scrollTop;
    scrollInterval = setInterval(function(){
        if (document.body.scrollTop != to) {
            count = count + 1;
            currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
            document.body.scrollTop = currPos;
        }
        else { clearInterval(scrollInterval); }
    },10);
}

function test(elID)
{
    var dest = document.getElementById(elID);
    scrollTo(dest.offsetTop, 500);
}
</script>

It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.

Thanks everyone for your help.

Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

Reference member variables as class members

Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.

Change Screen Orientation programmatically using a Button

Use this to set the orientation of the screen:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

or

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

and don't forget to add this to your manifest:

android:configChanges = "orientation"

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

if you tried running java with -version argument, and even though the problem could not be solved by any means, then you might have installed many java versions, like JDK 1.8 and JDK 1.7 at the same time.

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

How to do what head, tail, more, less, sed do in Powershell?

Get-Content (alias: gc) is your usual option for reading a text file. You can then filter further:

gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt     # also head
gc log.txt | select -last 10  # tail
gc -Tail 10 log.txt           # also tail (since PSv3), also much faster than above option
gc log.txt | more             # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed

This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.

The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).

ImportError: No module named sqlalchemy

first install the library

pip install flask_sqlalchemy 

after that

from flask_sqlalchemy import SQLAlchemy

put this in app.py file to get the access of database through SQLAlchemy

How to keep form values after post

you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

One way of doing it is to draw the image to a bitmap context that is backed by a given buffer for a given colorspace (in this case it is RGB): (note that this will copy the image data to that buffer, so you do want to cache it instead of doing this operation every time you need to get pixel values)

See below as a sample:

// First get the image into your data buffer
CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];

How to make picturebox transparent?

Try using an ImageList

ImageList imgList = new ImageList;

imgList.TransparentColor = Color.White;

Load the image like this:

picturebox.Image = imgList.Images[img_index];

php foreach with multidimensional array

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});

Comparing the contents of two files in Sublime Text

The Diff Option only appears if the files are in a folder that is part of a Project.

Than you can actually compare files natively right in Sublime Text.

Navigate to the folder containing them through Open Folder... or in a project Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar Right click and select the Diff files... option.

Convert string to decimal, keeping fractions

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

How do I parse a URL into hostname and path in javascript?

js-uri (available on Google Code) takes a string URL and resolves a URI object from it:

var some_uri = new URI("http://www.example.com/foo/bar");

alert(some_uri.authority); // www.example.com
alert(some_uri);           // http://www.example.com/foo/bar

var blah      = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full);         // http://www.example.com/foo/blah

How to "grep" out specific line ranges of a file

The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.

sed -n '1234,5555p' someFile

How should I escape strings in JSON?

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

All answers mentioned here are too old and lengthy.The best and short solution that work with latest Navigationview is

@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
    super.onDrawerSlide(drawerView, slideOffset);

    try {
        //int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
            // Do something for lollipop and above versions

        Window window = getWindow();

        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        // finally change the color to any color with transparency

         window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDarktrans));}

    } catch (Exception e) {

        Crashlytics.logException(e);

    }
}

this is going to change your status bar color to transparent when you open the drawer

Now when you close the drawer you need to change status bar color again to dark.So you can do it in this way.

        public void onDrawerClosed(View drawerView) {
        super.onDrawerClosed(drawerView);
        try {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions

    Window window = getWindow();

    // clear FLAG_TRANSLUCENT_STATUS flag:
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

    // finally change the color again to dark
    window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));}
    } catch (Exception e) {
    Crashlytics.logException(e);
                    }
                    }

and then in main layout add a single line i.e

            android:fitsSystemWindows="true"

and your drawer layout will look like

            <android.support.v4.widget.DrawerLayout     
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/drawer_layout"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

and your navigation view will look like

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/drawer"
        />

I have tested it and its fully working.Hope it helps someone.This may not be the best approach but it works smoothly and is simple to implement. Mark it up if it helps.Happy coding :)

How to write a basic swap function in Java

Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

Output:

New values of x and y are 10, 5

Make an image width 100% of parent div, but not bigger than its own width

If the image is smaller than parent...

.img_100 {
  width: 100%;
}

How to display (print) vector in Matlab?

I prefer the following, which is cleaner:

x = [1, 2, 3];
g=sprintf('%d ', x);
fprintf('Answer: %s\n', g)

which outputs

Answer: 1 2 3

What is a "bundle" in an Android application

Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.

You can use it like this:

Intent intent = new...
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("myKey", AnyValue);  
startActivity(intent);

You can get the passed values by doing:

Bundle extras = intent.getExtras(); 
String tmp = extras.getString("myKey");

You can find more info at:

How do I find the maximum of 2 numbers?

I noticed that if you have divisions it rounds off to integer, it would be better to use:

c=float(max(a1,...,an))/b

Sorry for the late post!

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

Install msi with msiexec in a Specific Directory

Use INSTALLLOCATION. When you have problems, use the /lv log.txt to dump verbose logs. The logs would tell you if there is a property change that would override your own options. If you already installed the product, then a second run might just update it without changing the install location. You will have to uninstall first (use the /x option).

How to get the cursor to change to the hand when hovering a <button> tag

see: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

so you need to add: cursor:pointer;

In your case use:

#more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use

<input type="button" id="more" />

If you want to apply this to more than one button then you have more than one possibility:

using CLASS

.more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />

or apply to a html context:

input[type=button] {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" value="first" />
<input type="button" value="second" />

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

How to create a file in Ruby

The directory doesn't exist. Make sure it exists as open won't create those dirs for you.

I ran into this myself a while back.

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.

How to check if a string starts with one of several prefixes?

A simple solution is:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed"))
// ... you get the idea ...

A fancier solution would be:

List<String> days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
String day = newStr4.substring(0, 3).toUpperCase();
if (days.contains(day)) {
    // ...
}

C++ code file extension? .cc vs .cpp

It doesn't matter which of those extensions you'd use. Pick whichever you like more, just be consistent with naming. The only exception I'm aware of with this naming convention is that I couldn't make WinDDK (or is it WDK now?) to compile .cc files. On Linux though that's hardly a problem.

Best way to check function arguments?

One way is to use assert:

def myFunction(a,b,c):
    "This is an example function I'd like to check arguments of"
    assert isinstance(a, int), 'a should be an int'
    # or if you want to allow whole number floats: assert int(a) == a
    assert b > 0 and b < 10, 'b should be betwen 0 and 10'
    assert isinstance(c, str) and c, 'c should be a non-empty string'

How to fix "set SameSite cookie to none" warning?

I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)

EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):

$cookie_options = array(
  'expires' => time() + 60*60*24*30,
  'path' => '/',
  'domain' => '.domain.com', // leading dot for compatibility or use subdomain
  'secure' => true, // or false
  'httponly' => false, // or false
  'samesite' => 'None' // None || Lax || Strict
);

setcookie('cors-cookie', 'my-site-cookie', $cookie_options);

If you have PHP 7.2 or lower (as Robert's answered below):

setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):

setcookie('cookieName', 'cookieValue', [
  'expires' => time()+(7*24*3600,
  'path' => '/',
  'domain' => 'domain.com',
  'samesite' => 'None',
  'secure' => true,
  'httponly' => true
]);

Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":

chrome://flags/#cookie-deprecation-messages

See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies too.

Need to get a string after a "word" in a string in c#

use indexOf() function

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}

Fix footer to bottom of page

My solution:

html, body {
  min-height: 100%
}

body {
  padding-bottom: 88px;
}

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 88px;
}

How to mkdir only if a directory does not already exist?

Try mkdir -p:

mkdir -p foo

Note that this will also create any intermediate directories that don't exist; for instance,

mkdir -p foo/bar/baz

will create directories foo, foo/bar, and foo/bar/baz if they don't exist.

Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.

If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:

[ -d foo ] || mkdir foo

Create directory if it does not exist

Try the -Force parameter:

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist

You can use Test-Path -PathType Container to check first.

See the New-Item MSDN help article for more details.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

String format currency

As others have said, you can achieve this through an IFormatProvider. But bear in mind that currency formatting goes well beyond the currency symbol. For example a correctly-formatted price in the US may be "$ 12.50" but in France this would be written "12,50 $" (the decimal point is different as is the position of the currency symbol). You don't want to lose this culture-appropriate formatting just for the sake of changing the currency symbol. And the good news is that you don't have to, as this code demonstrates:

var cultureInfo = Thread.CurrentThread.CurrentCulture;   // You can also hardcode the culture, e.g. var cultureInfo = new CultureInfo("fr-FR"), but then you lose culture-specific formatting such as decimal point (. or ,) or the position of the currency symbol (before or after)
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need

var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".

How should I store GUID in MySQL tables?

My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.

Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.

How to set maximum height for table-cell?

Try

   <td style="word-wrap: break-word">Long text here</td>

How can I generate an HTML report for Junit results?

Junit xml format is used outside of Java/Maven/Ant word. Jenkins with http://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin is a solution.

For the one shot solution I have found this tool that does the job: https://www.npmjs.com/package/junit-viewer

junit-viewer --results=surefire-reports --save=file_location.html

--results= is directory with xml files (test reports)

How to fix "'System.AggregateException' occurred in mscorlib.dll"

In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.

How would I get a cron job to run every 30 minutes?

Try this:

0,30 * * * * your command goes here

According to the official Mac OS X crontab(5) manpage, the / syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.

Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs.

Using 'make' on OS X

I agree with the other two answers: install the Apple Developer Tools.

But it is also worth noting that OS X ships with ant and rake.

How do I clone a job in Jenkins?

To copy an existing job, go to http://your-jenkins/newJob and use the "Copy existing job" option. Enter the name of the existing job - Jenkins will verify whether it exists.

The default tab on the front page of Jenkins should list all existing jobs, but maybe your predecessor deleted the tab. You can create a new tab listing all jobs from http://your-jenkins/newView.

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

How do I get a list of all the duplicate items using pandas in python?

For my database duplicated(keep=False) did not work until the column was sorted.

data.sort_values(by=['Order ID'], inplace=True)
df = data[data['Order ID'].duplicated(keep=False)]

Get file from project folder java

If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.

To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.

Based on user4284592's answer, the following worked for me:

ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("./docs/doc.pdf").getFile());

with the following directory structure:

{root dir}/target/classes/docs/doc.pdf

Here's an explanation, so you don't just blindly copy and paste my code:

  • java.lang.ClassLoader is an object that is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defined it and can fetch it with getClassLoader() method.
  • ClassLoader's getResource method finds the resource with the given name. A resource is some data that can be accessed by class code in a way that is independent of the location of the code.

Adding blur effect to background in swift

This worked for me on Swift 5

let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)

What are alternatives to document.write?

As a recommended alternative to document.write you could use DOM manipulation to directly query and add node elements to the DOM.

How to convert object to Dictionary<TKey, TValue> in C#?

You can use this:

Dictionary<object,object> mydic = ((IEnumerable)obj).Cast<object>().ToList().ToDictionary(px => px.GetType().GetProperty("Key").GetValue(px), pv => pv.GetType().GetProperty("Value").GetValue(pv));

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

Getting the error "Missing $ inserted" in LaTeX

In my code, when I got the error, I checked the possible source, In a line, I had typed a beginning \[ and an ending \] due to which the error of missing $ appeared though I tried using $ for both the brackets. Removing the brackets or using $[$ instead of $\[$ solved my problem. If you've something like that, try altering.

Insert a line break in mailto body

For the Single line and double line break here are the following codes.

Single break: %0D0A
Double break: %0D0A%0D0A

php - get numeric index of associative array

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Static array vs. dynamic array in C++

I think the semantics being used in your class are confusing. What's probably meant by 'static' is simply "constant size", and what's probably meant by "dynamic" is "variable size". In that case then, a constant size array might look like this:

int x[10];

and a "dynamic" one would just be any kind of structure that allows for the underlying storage to be increased or decreased at runtime. Most of the time, the std::vector class from the C++ standard library will suffice. Use it like this:

std::vector<int> x(10); // this starts with 10 elements, but the vector can be resized.

std::vector has operator[] defined, so you can use it with the same semantics as an array.

WampServer orange icon

In case that helps anybody I had the same issue with wampserver3.2.0_x64 on Windows 10 Enterprise.

Tried everything from the answers of this thread and nothing helped.

I then installed wampserver3.1.0_x86 instead and got the green light on first launch. I have no explanation but at least the desired end result.

Find a file with a certain extension in folder

Use this code for read file with all type of extension file.

string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");

How do I convert strings between uppercase and lowercase in Java?

Assuming that all characters are alphabetic, you can do this:

From lowercase to uppercase:

// Uppercase letters. 
class UpperCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('a' + i);
      System.out.print(ch); 

      // This statement turns off the 6th bit.   
      ch = (char) ((int) ch & 65503); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

From uppercase to lowercase:

// Lowercase letters. 
class LowerCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('A' + i);
      System.out.print(ch);
      ch = (char) ((int) ch | 32); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

Razor View throwing "The name 'model' does not exist in the current context"

You are likely to use in the code a variable named model.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

If you want to use Angular with an unsupported TypeScript version, add this to your tsconfig.json to ignore the warning:

  "angularCompilerOptions": {
    "disableTypeScriptVersionCheck": true,
  },

Adding script tag to React/JSX

componentDidMount() {
  const head = document.querySelector("head");
  const script = document.createElement("script");
  script.setAttribute(
    "src",
    "https://assets.calendly.com/assets/external/widget.js"
  );
  head.appendChild(script);
}

Jquery how to find an Object by attribute in an Array

Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):

var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

var daily = _.findWhere(purposeObjects, {purpose: 'daily'});

daily would equal:

{"purpose":"daily"}

Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/

To return more than one (if you had more in your array) you could use _.where(...)