Programs & Examples On #Symfony

Symfony is an open source PHP web development framework for PHP 5.5.9+, focusing on easy and fast development cycles and including state-of-the-art design patterns and programming philosophies. Symfony should not be confused with Symphony CMS. This tag should not be used for questions about Symfony 1.x. Please use Symfony1 tag instead.

How do I read configuration settings from Symfony2 config.yml?

Rather than defining contact_email within app.config, define it in a parameters entry:

parameters:
    contact_email: [email protected]

You should find the call you are making within your controller now works.

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);

How to set default value for form field in Symfony2?

->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
     $form = $event->getForm(); 
     $data = $event->getData(); 

     if ($data == null) {
         $form->add('position', IntegerType::class, array('data' => 0));
     }

});

Accessing session from TWIG template

I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Rather than using $_SESSION, it's also better to use Symfony's Session class since it handles automatically starting/stopping the session.

I've got the following extension in /src/AppBundle/Twig/AppExtension.php:

<?php    
namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\Session\Session;

class AppExtension extends \Twig_Extension {

    public function getGlobals() {
        $session = new Session();
        return array(
            'session' => $session->all(),
        );
    }

    public function getName() {
        return 'app_extension';
    }
}

Then add this in /app/config/services.yml:

services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

Then the session can be accessed from any view using:

{{ session.my_variable }}

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

symfony 2 No route found for "GET /"

I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

example : instead of just putting http://localhost/app_dev.php

put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

it will display Hello Ai . I hope I answer your question.

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

What is the difference between .yaml and .yml extension?

As @David Heffeman indicates the recommendation is to use .yaml when possible, and the recommendation has been that way since September 2006.

That some projects use .yml is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).

The best way to approach this is to be rigorous when creating new files (i.e. use .yaml) and be permissive when accepting input (i.e. allow .yml when you encounter it), possible automatically upgrading/correcting these errors when possible.

The other recommendation I have is to document the argument(s) why you have to use .yml, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml has more pages than .yaml" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml extension instead of the correct .yaml, but I think you will be hard pressed to do so.

Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose used .yml, but in later versions started to use .yaml, although they still support .yml). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml instead of appveyor.yml for building the windows wheels of my YAML parser for Python).


On the other hand:

The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.

So it seems fitting that they also use a subset of the recommended extension.

Getting the base url of the website and globally passing it to twig in Symfony 2

In Symfony 5 and in the common situation of a controller method use the injected Request object:

public function controllerFunction(Request $request, LoggerInterface $logger)
  ...
  $scheme = $request->getSchemeAndHttpHost();
  $logger->info('Domain is: ' . $scheme);
  ...
  //prepare to render
  $retarray = array(
    ...
    'scheme' => $scheme,
    ...
    );
  return $this->render('Template.html.twig', $retarray);
}

How to sort findAll Doctrine's method?

This works for me:

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));

Keeping the first array empty fetches back all data, it worked in my case.

How to use a findBy method with comparative criteria

The class Doctrine\ORM\EntityRepository implements Doctrine\Common\Collections\Selectable API.

The Selectable interface is very flexible and quite new, but it will allow you to handle comparisons and more complex criteria easily on both repositories and single collections of items, regardless if in ORM or ODM or completely separate problems.

This would be a comparison criteria as you just requested as in Doctrine ORM 2.3.2:

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('prize', 200));

$result = $entityRepository->matching($criteria);

The major advantage in this API is that you are implementing some sort of strategy pattern here, and it works with repositories, collections, lazy collections and everywhere the Selectable API is implemented.

This allows you to get rid of dozens of special methods you wrote for your repositories (like findOneBySomethingWithParticularRule), and instead focus on writing your own criteria classes, each representing one of these particular filters.

How to include CSS file in Symfony 2 and Twig?

And you can use %stylesheets% (assetic feature) tag:

{% stylesheets
    "@MainBundle/Resources/public/colorbox/colorbox.css"
    "%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}

You can write path to css as parameter (%parameter_name%).

More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

symfony2 : failed to write cache directory

if symfony version less than 2.8

_x000D_
_x000D_
sudo chmod -R 777 app/cache/*
_x000D_
_x000D_
_x000D_

if symfony version great than or equal 3.0

_x000D_
_x000D_
sudo chmod -R 777 var/cache/*
_x000D_
_x000D_
_x000D_

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

database_password: password would between quotes: " or '.

like so:

database_password: "password"

Count Rows in Doctrine QueryBuilder

Since Doctrine 2.6 it is possible to use count() method directly from EntityRepository. For details see the link.

https://github.com/doctrine/doctrine2/blob/77e3e5c96c1beec7b28443c5b59145eeadbc0baf/lib/Doctrine/ORM/EntityRepository.php#L161

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

How to use absolute path in twig functions

Additional info to generate absolute URL using a command (to send an email for instance)

In a command, {{ absolute_url(path('index')) }} is not working out of the box.

You will need to add the additional configuration shown in antongorodezkiy's answer.

But in case you don't want to change the configuration because you are not sure how it could impact the whole app, you can configure the router in the command.

Here is the doc :

https://symfony.com/doc/3.4/console/request_context.html

Here is the code :

use Symfony\Component\Routing\RouterInterface;
// ...

class DemoCommand extends Command
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        parent::__construct();

        $this->router = $router;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $context = $this->router->getContext();
        $context->setHost('example.com');
        $context->setScheme('https');
        $context->setBaseUrl('my/path');

        $url = $this->router->generate('route-name', ['param-name' => 'param-value']);
        // ...
    }
}

To generate the URL in the Twig template

<a href="{{ absolute_url(path(...)) }}"></a>

You can fetch the HOST and SCHEME from your env file

$context = $this->router->getContext();
$context->setHost($_ENV['NL_HOST']);
$context->setScheme($_ENV['NL_SCHEME']);

Just define the variable in .env and .env.local files

NL_HOST=mydomain.com
NL_SCHEME=https

How do I delete an entity from symfony2

From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>
    {% for guest in guests %}
    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
    {% endfor %}
</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.

The CSRF token is invalid. Please try to resubmit the form

I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.

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');

Access POST values in Symfony2 request object

what worked for me was using this:

$data = $request->request->all();
$name = $data['form']['name'];

How can I send JSON response in symfony2 controller

Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper

public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

Symfony - generate url with parameter in controller

It's pretty simple :

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));

How to get the root dir of the Symfony2 application?

If you are using this path to access parts of the projects which are not code (for example an upload directory, or a SQLite database) then it might be better to turn the path into a parameter, like this:

parameters:
    database_path: '%kernel.root_dir%/../var/sqlite3.db'

This parameter can be injected everywhere you need it, so you don't have to mess around with paths in your code any more. Also, the parameter can be overridden at deployment time. Finally, every maintaining programmer will have a better idea what you are using it for.

Update: Fixed kernel.root_dir constant usage.

How to set a class attribute to a Symfony2 form input

You can to this in Twig or the FormClass as shown in the examples above. But you might want to decide in the controller which class your form should get. Just keep in mind to not have much logic in the controller in general!

    $form = $this->createForm(ContactForm::class, null, [
        'attr' => [
            'class' => 'my_contact_form'
        ]
    ]);

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Just want to share my situation on this matter.

Problem context:

  1. Running composer in a vagrant box.
  2. Was getting this message after try to run composer require "laravel-doctrine/orm:~1.4.13":

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.

  1. Have tried setting php.ini memory limit to -1. (still not working).

Solution:

  1. Apparently my composer.json and composer.lock has some issues. Ran $ composer validate, and the result was: "The lock file is not up to date with the latest changes in composer.json, it is recommended that you run composer update."

  2. So I ran $ composer update, and all dependencies are resolved. Imho, when the dependencies has some issues, maybe the tree building is out of sync, hence the out of memory issue.

Hope this helps anyone out there.

How do I get the entity that represents the current user in Symfony2?

Well, first you need to request the username of the user from the session in your controller action like this:

$username=$this->get('security.context')->getToken()->getUser()->getUserName();

then do a query to the db and get your object with regular dql like

$em = $this->get('doctrine.orm.entity_manager');    
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();

the $user should now hold the user with this username ( you could also use other fields of course)

...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:

security:
 provider:
  example:
   entity: {class Acme\AuctionBundle\Entity\User, property: username}

hope this helps!

How to get the request parameters in Symfony 2?

$request = Request::createFromGlobals();
$getParameter = $request->get('getParameter');

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

How to render a DateTime object in a Twig template

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  <style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
     }
    });

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

return isFormValid;
}   
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>

How to get config parameters in Symfony2 Twig Templates

The above given ans are correct and works fine. I used in a different way.

config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: app.yml }
    - { resource: app_twig.yml }

app.yml

parameters:
  app.version:           1.0.1

app_twig.yml

twig:
  globals:
    version: %app.version%

Inside controller:

$application_version = $this->container->getParameter('app.version');
// Here using app.yml

Inside template/twig file:

Project version {{ version }}!
{#  Here using app_twig.yml content.  #}
{#  Because in controller we used $application_version  #}

To use controller output:

Controller:

public function indexAction() {
        $application_version = $this->container->getParameter('app.version');
        return array('app_version' => $application_version);
    }

template/twig file :

Project version {{ app_version }}

I mentioned the different for better understand.

Call PHP function from Twig template

Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.

How to know which version of Symfony I have?

Use the following command in your Terminal/Command Prompt:

php bin/console --version

This will give you your Symfony Version.

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

How to get form values in Symfony2 controller

If Symfony 4 or 5, juste use this code (Where name is the name of your field):

$request->request->get('name');

symfony 2 twig limit the length of the text and put three dots

An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').

Here's an example where I shorten only text blocks longer than 10 words:

{% set text = myentity.text |split(' ') %} 

{% if text|length > 10 %} 
    {% for t in text|slice(0, 10) %}
        {{ t }} 
    {% endfor %}
    ...
{% else %}
    {{ text|join(' ') }}
{% endif %}

Running Composer returns: "Could not open input file: composer.phar"

Your composer.phar must be in Source files. I had same problem and I just cut my composer.phar into mine framework-standard-edition folder, where is my whole strong textproject.

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Found a similar way to fix this issue (at least it did for me).

  1. First check where the CLI php.ini is located:

    php -i | grep "php.ini"

  2. In my case I ended up with : Configuration File (php.ini) Path => /etc

  3. Then cd .. all the way back and cd into /etc, do ls in my case php.ini didn't show up, only a php.ini.default

  4. Now, copy the php.ini.default file named as php.ini:

    sudo cp php.ini.default php.ini

  5. In order to edit, change the permissions of the file:

    sudo chmod ug+w php.ini

    sudo chgrp staff php.ini

  6. Open directory and edit the php.ini file:

    open .

    Tip: If you are not able to edit the php.ini due to some permissions issue then copy 'php.ini.default' and paste it on your desktop and rename it to 'php.ini' then open it and edit it following step 7. Then move (copy+paste) it in /etc folder. Issue will be resolved.

  7. Search for [Date] and make sure the following line is in the correct format:

    date.timezone = "Europe/Amsterdam"

I hope this could help you out.

How to check if an user is logged in Symfony2 inside a controller?

If you are using security annotation from the SensioFrameworkExtraBundle, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider):

  • @Security("is_authenticated()"): to check that the user is authed and not anonymous
  • @Security("is_anonymous()"): to check if the current user is the anonymous user
  • @Security("is_fully_authenticated()"): equivalent to is_granted('IS_AUTHENTICATED_FULLY')
  • @Security("is_remember_me()"): equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')

How to get the server path to the web directory in Symfony2 from inside the controller?

You are on Symfony, think "Dependency Injection" ^^

In all my SF project, I do in parameters.yml:

web_dir: "%kernel.root_dir%/../web"

So I can safely use this parameter within controller:

$this->getParameter('web_dir');

How do I read from parameters.yml in a controller in symfony2?

In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.

$this->container->getParameter('api_user');

This documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');

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

Symfony 3 and newer

I recently made a function which creates a tree of form errors. This will be helpful for returning list of errors back to front-end. This is based on form types having:

'error_bubbling' => false

Code:

public static function getFormErrorsTree(FormInterface $form): array
{
    $errors = [];

    if (count($form->getErrors()) > 0) {
        foreach ($form->getErrors() as $error) {
            $errors[] = $error->getMessage();
        }
    } else {
        foreach ($form->all() as $child) {
            $childTree = self::getFormErrorsTree($child);

            if (count($childTree) > 0) {
                $errors[$child->getName()] = $childTree;
            }
        }
    }

    return $errors;
}

Output:

Array
(
    [name] => Array
        (
            [0] => This value is not valid.
        )

    [emails] => Array
        (
            [0] => Array
                (
                    [0] => Given e-mail is not valid.
                    [1] => Given e-mail is not valid #2.
                )
            [1] => Array
                (
                    [0] => Given e-mail is not valid.
                    [1] => Given e-mail is not valid #2.
                )

        )

)

Notice: I know that errors from deeper level fields can be overwritten if higher level has errors, but this is on purpose for my usage.

Symfony2 Setting a default choice field selection

the solution: for type entity use option "data" but value is a object. ie:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array
(

    'class' => 'TestGeneralBundle:Sucursal',
    'property'=>'descripcion',
    'label' => 'Sucursal',
    'required' => false,
    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           

))

Path of assets in CSS files in Symfony 2

I have came across the very-very-same problem.

In short:

  • Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)
  • Willing to have the images in the "public" dir (Resources/public/images/devil.png)
  • Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png

I have made a test with ALL possible (sane) combinations of the following:

  • @notation, relative notation
  • Parse with cssrewrite, without it
  • CSS image background vs direct <img> tag src= to the very same image than CSS
  • CSS parsed with assetic and also without parsing with assetic direct output
  • And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).

This gave me a total of 14 combinations on the same twig, and this route was launched from

  • "/app_dev.php/"
  • "/app.php/"
  • and "/"

thus giving 14 x 3 = 42 tests.

Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.

The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.

I observed the following:

Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.

These are the results:

  1. Result launched with /app_dev.php/ Result launched with /app_dev.php/

  2. Result launched with /app.php/ Result launched with /app.php/

  3. Result launched with / enter image description here

So... ONLY - The second image - Div B - Div C are the allowed syntaxes.

Here there is the TWIG code:

<html>
    <head>
            {% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: ABCDEF #}

            <link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets 'bundles/commondirty/css_original/d.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: GHIJKL #}

            <link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    </head>
    <body>
        <div class="container">
            <p>
                <img alt="Devil" src="../bundles/commondirty/images/devil.png">
                <img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
            </p>
            <p>
                <div class="a">
                    A
                </div>
                <div class="b">
                    B
                </div>
                <div class="c">
                    C
                </div>
                <div class="d">
                    D
                </div>
                <div class="e">
                    E
                </div>
                <div class="f">
                    F
                </div>
            </p>
            <p>
                <div class="g">
                    G
                </div>
                <div class="h">
                    H
                </div>
                <div class="i">
                    I
                </div>
                <div class="j">
                    J
                </div>
                <div class="k">
                    K
                </div>
                <div class="l">
                    L
                </div>
            </p>
        </div>
    </body>
</html>

The container.css:

div.container
{
    border: 1px solid red;
    padding: 0px;
}

div.container img, div.container div 
{
    border: 1px solid green;
    padding: 5px;
    margin: 5px;
    width: 64px;
    height: 64px;
    display: inline-block;
    vertical-align: top;
}

And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.

.a
{
    background: red url('../images/devil.png');
}

The "directories" structure is:

Directories Directories

All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.

But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:

Compilation process Compilation process

Note I do this for the --env=prod environment.

Just a few final thoughts:

  • This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.

  • Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.

  • Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.

BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.

So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.

The winner is C

The winner is C

How to update a single library with Composer?

You can basically do following one to install new package as well.

php composer.phar require

then terminal will ask you to enter the name of the package for searching.

$ Search for a package []: //Your package name here

Then terminal will ask the version of the package (If you would like to have the latest version just leave it blank)

$ Enter the version constraint to require (or leave blank to use the latest version) []: //your version number here

Then you just press the return key. Terminal will ask for another package, if you dont want to install another one just press the return key and you will be done.

How to get current route in Symfony 2?

With Symfony 4.2.7, I'm able to implement the following in my twig template, which displays the custom route name I defined in my controller(s).

In index.html.twig

<div class="col">
    {% set current_path =  app.request.get('_route') %}
    {{ current_path }}
</div>

In my controller


    ...

    class ArticleController extends AbstractController {
        /**
         * @Route("/", name="article_list")
         * @Method({"GET"})
         */
        public function index() {
        ...
        }

        ...
     }

The result prints out "article_list" to the desired page in my browser.

The EntityManager is closed

This is a very tricky problem since, at least for Symfony 2.0 and Doctrine 2.1, it is not possible in any way to reopen the EntityManager after it closes.

The only way I found to overcome this problem is to create your own DBAL Connection class, wrap the Doctrine one and provide exception handling (e.g. retrying several times before popping the exception out to the EntityManager). It is a bit hacky and I'm afraid it can cause some inconsistency in transactional environments (i.e. I'm not really sure of what happens if the failing query is in the middle of a transaction).

An example configuration to go for this way is:

doctrine:
  dbal:
    default_connection: default
    connections:
      default:
        driver:   %database_driver%
        host:     %database_host%
        user:     %database_user%
        password: %database_password%
        charset:  %database_charset%
        wrapper_class: Your\DBAL\ReopeningConnectionWrapper

The class should start more or less like this:

namespace Your\DBAL;

class ReopeningConnectionWrapper extends Doctrine\DBAL\Connection {
  // ...
}

A very annoying thing is that you have to override each method of Connection providing your exception-handling wrapper. Using closures can ease some pain there.

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()

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

AngularJS - add HTML element to dom in directive without jQuery

In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.

So basically, you can rewrite your code to something like this:

link: function (scope, iElement, iAttrs) {
  var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');
  angular.element(svgTag).appendTo(iElement[0]);
  //...
}

Differences between strong and weak in Objective-C

A dummy answer :-

I think explanation is given in above answer, so i am just gonna tell you where to use STRONG and where to use WEAK :

Use of Weak :- 1. Delegates 2. Outlets 3. Subviews 4. Controls, etc.

Use of Strong :- Remaining everywhere which is not included in WEAK.

How to change plot background color?

Something like this? Use the axisbg keyword to subplot:

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(Granted, not a scatter plot, and not a black background.)

enter image description here

Java Does Not Equal (!=) Not Working?

== and != work on object identity. While the two Strings have the same value, they are actually two different objects.

use !"success".equals(statusCheck) instead.

Find the paths between two given nodes?

Dijkstra's algorithm applies more to weighted paths and it sounds like the poster was wanting to find all paths, not just the shortest.

For this application, I'd build a graph (your application sounds like it wouldn't need to be directed) and use your favorite search method. It sounds like you want all paths, not just a guess at the shortest one, so use a simple recursive algorithm of your choice.

The only problem with this is if the graph can be cyclic.

With the connections:

  • 1, 2
  • 1, 3
  • 2, 3
  • 2, 4

While looking for a path from 1->4, you could have a cycle of 1 -> 2 -> 3 -> 1.

In that case, then I'd keep a stack as traversing the nodes. Here's a list with the steps for that graph and the resulting stack (sorry for the formatting - no table option):

current node (possible next nodes minus where we came from) [stack]

  1. 1 (2, 3) [1]
  2. 2 (3, 4) [1, 2]
  3. 3 (1) [1, 2, 3]
  4. 1 (2, 3) [1, 2, 3, 1] //error - duplicate number on the stack - cycle detected
  5. 3 () [1, 2, 3] // back-stepped to node three and popped 1 off the stack. No more nodes to explore from here
  6. 2 (4) [1, 2] // back-stepped to node 2 and popped 1 off the stack.
  7. 4 () [1, 2, 4] // Target node found - record stack for a path. No more nodes to explore from here
  8. 2 () [1, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes to explore from here
  9. 1 (3) [1] //back-stepped to node 1 and popped 2 off the stack.
  10. 3 (2) [1, 3]
  11. 2 (1, 4) [1, 3, 2]
  12. 1 (2, 3) [1, 3, 2, 1] //error - duplicate number on the stack - cycle detected
  13. 2 (4) [1, 3, 2] //back-stepped to node 2 and popped 1 off the stack
  14. 4 () [1, 3, 2, 4] Target node found - record stack for a path. No more nodes to explore from here
  15. 2 () [1, 3, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes
  16. 3 () [1, 3] // back-stepped to node 3 and popped 2 off the stack. No more nodes
  17. 1 () [1] // back-stepped to node 1 and popped 3 off the stack. No more nodes
  18. Done with 2 recorded paths of [1, 2, 4] and [1, 3, 2, 4]

How to make a DIV not wrap?

Use display:flex and white-space:nowrap

_x000D_
_x000D_
p{_x000D_
  display:flex;_x000D_
  white-space:nowrap;_x000D_
  overflow:auto;_x000D_
}
_x000D_
<h2>Sample Text.</h2>_x000D_
_x000D_
<p>Some example text that will not wrap..lla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum d</p>_x000D_
_x000D_
<h3>Then some other text</h3>
_x000D_
_x000D_
_x000D_

Validating parameters to a Bash script

#!/bin/sh
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 1 ] || die "1 argument required, $# provided"
echo $1 | grep -E -q '^[0-9]+$' || die "Numeric argument required, $1 provided"

while read dir 
do
    [ -d "$dir" ] || die "Directory $dir does not exist"
    rm -rf "$dir"
done <<EOF
~/myfolder1/$1/anotherfolder 
~/myfolder2/$1/yetanotherfolder 
~/myfolder3/$1/thisisafolder
EOF

edit: I missed the part about checking if the directories exist at first, so I added that in, completing the script. Also, have addressed issues raised in comments; fixed the regular expression, switched from == to eq.

This should be a portable, POSIX compliant script as far as I can tell; it doesn't use any bashisms, which is actually important because /bin/sh on Ubuntu is actually dash these days, not bash.

how to reset <input type = "file">

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

See How to reset file input with JavaScript for more information.

How do I enable saving of filled-in fields on a PDF form?

There is a setting inside the PDF file that turns on the allow saving with data bit. However, it requires that you have a copy of Adobe Acrobat installed to change the bit.

The only other option is to print it to a PDF print driver which would save the data merged with the pdf file.

UPDATE: The relevant information from adobe is at: http://www.adobeforums.com/webx?13@@.3bbb313f/7

How to trigger ngClick programmatically

The best solution is to use:

domElement.click()

Because the angularjs triggerHandler(angular.element(domElement).triggerHandler('click')) click events does not bubble up in the DOM hierarchy, but the one above does - just like a normal mouse click.

https://docs.angularjs.org/api/ng/function/angular.element

http://api.jquery.com/triggerhandler/

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

How to detect the device orientation using CSS media queries?

I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:

For Mobile

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.

}


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

For Tablet

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

Desktop

make as per your design requirement enjoy...(:

Thanks, Jitu

Create an array with same element repeated multiple times

Another one-liner:

Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })

Strip out HTML and Special Characters

All the other solutions are creepy because they are from someone that arrogantly simply thinks that English is the only language in the world :)

All those solutions strip also diacritics like ç or à.

The perfect solution, as stated in PHP documentation, is simply:

$clear = strip_tags($des);

mysql stored-procedure: out parameter

I know this is an old thread, but if anyone is looking for an answer of why their procedures doesn't work in the workbench and think the only result is "Query canceled" or anything like that without clues:

the output with errors or problems is hiddenl. I do not know why, I do understand it's annoying, but it is there. just move your cursor above the line above the message, it will turn in an double arrow (up and down) you can then click and drag that line up, then you will see a console with the message you missed!

Convert a JSON String to a HashMap

There’s an older answer using javax.json posted here, however it only converts JsonArray and JsonObject, but there are still JsonString, JsonNumber, and JsonValue wrapper classes in the output. If you want to get rid of these, here’s my solution which will unwrap everything.

Beside that, it makes use of Java 8 streams and is contained in a single method.

/**
 * Convert a JsonValue into a “plain” Java structure (using Map and List).
 * 
 * @param value The JsonValue, not <code>null</code>.
 * @return Map, List, String, Number, Boolean, or <code>null</code>.
 */
public static Object toObject(JsonValue value) {
    Objects.requireNonNull(value, "value was null");
    switch (value.getValueType()) {
    case ARRAY:
        return ((JsonArray) value)
                .stream()
                .map(JsonUtils::toObject)
                .collect(Collectors.toList());
    case OBJECT:
        return ((JsonObject) value)
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Entry::getKey,
                        e -> toObject(e.getValue())));
    case STRING:
        return ((JsonString) value).getString();
    case NUMBER:
        return ((JsonNumber) value).numberValue();
    case TRUE:
        return Boolean.TRUE;
    case FALSE:
        return Boolean.FALSE;
    case NULL:
        return null;
    default:
        throw new IllegalArgumentException("Unexpected type: " + value.getValueType());
    }
}

What is mutex and semaphore in Java ? What is the main difference?

The object of synchronization Semaphore implements a classical traffic light. A traffic light controls access to a resource shared by a counter. If the counter is greater than zero, access is granted; If it is zero, access is denied. The counter counts the permissions that allow access to the shared resource. Then, to access the resource, a thread must receive permission from the traffic light. In general, to use a traffic light, the thread that wants to access the shared resource tries to acquire a permit. If the traffic light count is greater than zero, the thread acquires a permit, and the traffic light count is decremented. Otherwise the thread is locked until it can get a permission. When the thread no longer needs to access the shared resource, it releases the permission, so the traffic light count is increased. If there is another thread waiting for a permit, it acquires a permit at that time. The Semaphore class of Java implements this mechanism.

Semaphore has two builders:

Semaphore(int num)
Semaphore(int num, boolean come)

num specifies the initial count of the permit. Then num specifies the number of threads that can access a shared resource at a given time. If num is one, it can access the resource one thread at a time. By setting come as true, you can guarantee that the threads you are waiting for are granted permission in the order they requested.

Dart/Flutter : Converting timestamp

You can use intl package, first import

import 'package:intl/intl.dart';

And then

int timeInMillis = 1586348737122;
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat.yMMMd().format(date); // Apr 8, 2020

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

TypeError : Unhashable type

... and so you should do something like this:

set(tuple ((a,b) for a in range(3)) for b in range(3))

... and if needed convert back to list

How to find what code is run by a button or element in Chrome using Developer Tools

Alexander Pavlov's answer gets the closest to what you want.

Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.


1. Setting up the Event Listener Breakpoint

You were close on this one.

  1. Open the Chrome Dev Tools (F12), and go to the Sources tab.
  2. Drill down to Mouse -> Click
    Chrome Dev Tools -> Sources tab -> Mouse -> Click
    (click to zoom)

2. Click the button!

Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:

Chrome Dev Tools paused script execution (click to zoom)


3. Find the glorious code!

Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.

  1. Press the F11 key (Step In) until desired source code appears
  2. Source code finally reached
    • In the jsFiddle sample provided above, I had to press F11 108 times before reaching the desired event handler/function
    • Your mileage may vary, depending on the version of jQuery (or framework library) used to bind the events
    • With enough dedication and time, you can find any event handler/function

Desired event handler/function


4. Explanation

I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.

Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:

    // ...snip...

    if ( !(eventHandle = elemData.handle) ) {
        eventHandle = elemData.handle = function( e ) {
            // Discard the second event of a jQuery.event.trigger() and
            // when an event is called after a page has unloaded
            return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
                jQuery.event.dispatch.apply( elem, arguments ) : undefined;
        };
    }

    // ...snip...

The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.

Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.

Change background color of R plot

Like

par(bg = 'blue')
# Now do plot

Soft keyboard open and close listener in an activity in Android

private boolean isKeyboardShown = false;
private int prevContentHeight = 0;
private ViewGroup contentLayout;

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener =
        new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        int contentHeight = contentLayout.getHeight();
        int rootViewHeight = contentLayout.getRootView().getHeight();

        if (contentHeight > 0) {

            if (!isKeyboardShown) {
                if (contentHeight < prevContentHeight) {
                    isKeyboardShown = true;
                    onShowKeyboard(rootViewHeight - contentHeight);
                }
            } else {
                if (contentHeight > prevContentHeight) {
                    isKeyboardShown = false;
                    onHideKeyboard();
                }
            }

            prevContentHeight = contentHeight;
        }
    }
};

I've modified the Jaap's accepted answer a bit. But in my case, there are few assumptions such as android:windowSoftInputMode=adjustResize and the keyboard does not show up at the beginning when the app starts. And also, I assume that the screen in regard matches the parent's height.

contentHeight > 0 this check provides me to know if the regarding screen is hidden or shown to apply keyboard event listening for this specific screen. Also I pass the layout view of the regarding screen in attachKeyboardListeners(<your layout view here>) in my main activity's onCreate() method. Every time when the height of the regarding screen changes, I save it to prevContentHeight variable to check later whether the keyboard is shown or hidden.

For me, so far it's been worked pretty well. I hope that it works for others too.

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

jQuery to remove an option from drop down list, given option's text/value

Once you have localized the dropdown element

dropdownElement = $("#dropdownElement");

Find the <option> element using the JQuery attribute selector

dropdownElement.find('option[value=foo]').remove();

Disable Pinch Zoom on Mobile Web

This is all I needed:

<meta name="viewport" content="user-scalable=no"/>

Pure CSS to make font-size responsive based on dynamic amount of characters

calc(42px + (60 - 42) * (100vw - 768px) / (1440 - 768));

use this equation.

For anything larger or smaller than 1440 and 768, you can either give it a static value, or apply the same approach.

The drawback with vw solution is that you cannot set a scale ratio, say a 5vw at screen resolution 1440 may ended up being 60px font-size, your idea font size, but when you shrink the window width down to 768, it may ended up being 12px, not the minimal you want. With this approach, you can set your upper boundary and lower boundary, and the font will scale itself in between.

run program in Python shell

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

Checking if a variable is an integer in PHP

/!\ Best anwser is not correct, is_numeric() returns true for integer AND all numeric forms like "9.1"

For integer only you can use the unfriendly preg_match('/^\d+$/', $var) or the explicit and 2 times faster comparison :

if ((int) $var == $var) {
    // $var is an integer
}

PS: i know this is an old post but still the third in google looking for "php is integer"

Origin http://localhost is not allowed by Access-Control-Allow-Origin

If you are making the fetch call to your localhost which I'm guessing is run by node.js in the same directory as your backbone code, than it will most likely be on http://localhost:3000 or something like that. Than this should be your model:

var model = Backbone.Model.extend({
    url: '/item'
});

And in your node.js you now have to accept that call like this:

app.get('/item', function(req, res){
    res.send('some info here');
});

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.

How can I run a windows batch file but hide the command window?

You could write a windows service that does nothing but execute your batch file. Since services run in their own desktop session, the command window won't be visible by the user.

c# foreach (property in object)... Is there a simple way of doing this?

A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.

How to remove a variable from a PHP session array

Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:

$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?> 

So, unset has no effect to internal array counter!!!

http://us.php.net/unset

How to extract text from an existing docx file using python-docx

Using python-docx, as @Chinmoy Panda 's answer shows:

for para in doc.paragraphs:
    fullText.append(para.text)

However, para.text will lost the text in w:smarttag (Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])

Arduino Tools > Serial Port greyed out

Same comment as Philip Kirkbride. It wasn't a permission issue, but using the Arduino IDE downloaded from their website solved my problem. Thanks! Michael

How to send and retrieve parameters using $state.go toParams and $stateParams?

The Nathan Matthews's solution did not work for me but it is totally correct but there is little point to reaching a workaround:

The key point is: Type of defined parameters and toParamas of $state.go should be same array or object on both sides of state transition.

For example when you define a params in a state as follows you means params is array because of using "[]":

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      ['index', 'anotherKey'],
    controller:  'overviewController'
})

So also you should pass toParams as array like this:

params = { 'index': 123, 'anotherKey': 'This is a test' }
paramsArr = (val for key, val of params)
$state.go('view', paramsArr)

And you can access them via $stateParams as array like this:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams[0];
    var anotherKey = $stateParams[1];
});

Better solution is using object instead of array in both sides:

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      {'index': null, 'anotherKey': null},
    controller:  'overviewController'
})

I replaced [] with {} in params definition. For passing toParams to $state.go also you should using object instead of array:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })

then you can access them via $stateParams easily:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

How to iterate using ngFor loop Map containing key as string and values as map iteration

As people have mentioned in the comments keyvalue pipe does not retain the order of insertion (which is the primary purpose of Map).

Anyhow, looks like if you have a Map object and want to preserve the order, the cleanest way to do so is entries() function:

<ul>
    <li *ngFor="let item of map.entries()">
        <span>key: {{item[0]}}</span>
        <span>value: {{item[1]}}</span>
    </li>
</ul>

How can you check for a #hash in a URL using JavaScript?

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

How to set a default row for a query that returns no rows?

*SQL solution

Suppose you have a review table which has primary key "id".

SELECT * FROM review WHERE id = 1555
UNION ALL
SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1

if table doesn't have review with 1555 id then this query will provide a review of id 1.

Why does the JFrame setSize() method not set the size correctly?

On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:

frame.setSize(width, height + 22);

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

Found this in google groups and this worked for me..

Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, width, height, clearPaint); 

This removes drawings rectangles etc. while keeping set bitmap..

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

C# Foreach statement does not contain public definition for GetEnumerator

You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

Your code also seems a bit strange, like you are nesting lists?

CRON command to run URL address every 5 minutes

I try GET 'http://example.com/?var=value' Important use ' add >/dev/null 2>&1 for not send email when this activate Sorry for my English

Jquery, checking if a value exists in array or not

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

What is an idiomatic way of representing enums in Go?

Referring to the answer of jnml, you could prevent new instances of Base type by not exporting the Base type at all (i.e. write it lowercase). If needed, you may make an exportable interface that has a method that returns a base type. This interface could be used in functions from the outside that deal with Bases, i.e.

package a

type base int

const (
    A base = iota
    C
    T
    G
)


type Baser interface {
    Base() base
}

// every base must fulfill the Baser interface
func(b base) Base() base {
    return b
}


func(b base) OtherMethod()  {
}

package main

import "a"

// func from the outside that handles a.base via a.Baser
// since a.base is not exported, only exported bases that are created within package a may be used, like a.A, a.C, a.T. and a.G
func HandleBasers(b a.Baser) {
    base := b.Base()
    base.OtherMethod()
}


// func from the outside that returns a.A or a.C, depending of condition
func AorC(condition bool) a.Baser {
    if condition {
       return a.A
    }
    return a.C
}

Inside the main package a.Baser is effectively like an enum now. Only inside the a package you may define new instances.

Get started with Latex on Linux

If you use Ubuntu or Debian, I made a tutorial easy to follow: Install LaTeX on Ubuntu or Debian. This tutorial explains how to install LaTeX and how to create your first PDF.

Is it possible to style html5 audio tag?

If you want to style the browsers standard music player in the CSS:

audio {
    enter code here;
}

Android: Is it possible to display video thumbnails?

I really suggest you to use the Glide library. It's among the most efficient way to generate and display a video thumbnail for a local video file.

Just add this line to your gradle file :

compile 'com.github.bumptech.glide:glide:3.7.0'

And it will become as simple as :

String filePath = "/storage/emulated/0/Pictures/example_video.mp4";

Glide  
    .with( context )
    .load( Uri.fromFile( new File( filePath ) ) )
    .into( imageViewGifAsBitmap );

You can find more informations here : https://futurestud.io/blog/glide-displaying-gifs-and-videos

Cheers !

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

Lollipop : draw behind statusBar with its color set to transparent

With Android Studio 1.4, the template project with boiler plate code sets Overlay theme on your AppbarLayout and/or Toolbar. They are also set to be rendered behind the status bar by fitSystemWindow attribute = true. This will cause only toolbar to be rendered directly below the status bar and everything else will rendered beneath the toolbar. So the solutions provided above won't work on their own. You will have to make the following changes.

  • Remove the Overlay theme or change it to non overlay theme for the toolbar.
  • Put the following code in your styles-21.xml file.

    @android:color/transparent

  • Assign this theme to the activity containing the navigation drawer in the AndroidManifest.xml file.

This will make the Navigation drawer to render behind the transparent status bar.

How to load a controller from another controller in codeigniter?

I had a similar problem. I wanted to have two controllers:

homepage.php - public facing homepage

home.php - home screen once a user was logged in

and I wanted them both to read from 'mydomain.com'

I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php

function _remap()
{
  if(user_is_logged_in())
  {
    require_once(APPPATH.'controllers/home.php'); 
    $oHome =  new Home();
    $oHome->index();
  }
  else
  {
    $this->index();
  }
}

Keyboard shortcut to comment lines in Sublime Text 3

In case anyone has had further issues with Sublime 3 on Windows 7, the above suggestions all did not work for me. However, when I 1 - reran the app as administrator and 2 - highlighted, and chose Edit -> Comment -> toggle comment, afterwards I was able to use a user preferences set keybinding to toggle comments. I don't really have an explanation for why it worked, except that it did.

Can I force a page break in HTML printing?

CSS

@media print {
  .pagebreak { 
     page-break-before: always; 
  }
}

HTML

<div class="pagebreak"></div>

How to get main div container to align to centre?

I would omit the * { text-align:center } declaration, as it sets center alignment for all elements.

Usually with a fixed width container margin: 0 auto should be enough

Reset CSS display property to default value

Unset display:

You can use the value unset which works in both Firefox and Chrome.

display: unset;

.foo     { display: none;  }
.foo.bar { display: unset; }

MyISAM versus InnoDB

I have briefly discussed this question in a table so you can conclude whether to go with InnoDB or MyISAM.

Here is a small overview of which db storage engine you should use in which situation:

                                                 MyISAM   InnoDB
----------------------------------------------------------------
Required full-text search                        Yes      5.6.4
----------------------------------------------------------------
Require transactions                                      Yes
----------------------------------------------------------------
Frequent select queries                          Yes      
----------------------------------------------------------------
Frequent insert, update, delete                           Yes
----------------------------------------------------------------
Row locking (multi processing on single table)            Yes
----------------------------------------------------------------
Relational base design                                    Yes

Summary

  • In almost all circumstances, InnoDB is the best way to go
  • But, frequent reading, almost no writing, use MyISAM
  • Full-text search in MySQL <= 5.5, use MyISAM

Virtual Serial Port for Linux

There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.

It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!

On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):

#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif

When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.

edit:

I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.

The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.

edit:

The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.

I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.

If anyone is interested in my version of the code, send me a message and I'll send it to you.

How to convert a string into double and vice versa?

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

Google Maps: how to get country, state/province/region, city given a lat/long value?

I wrote this function that extracts what you are looking for based on the address_components returned from the gmaps API. This is the city (for example).

export const getAddressCity = (address, length) => {
  const findType = type => type.types[0] === "locality"
  const location = address.map(obj => obj)
  const rr = location.filter(findType)[0]

  return (
    length === 'short'
      ? rr.short_name
      : rr.long_name
  )
}

Change locality to administrative_area_level_1 for the State etc.

In my js code I am using like so:

const location =`${getAddressCity(address_components, 'short')}, ${getAddressState(address_components, 'short')}`

Will return: Waltham, MA

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

OK, found solution.

In the file database.php, by default, it comes the "mysql" part:

 'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

all you need to do is change the values :

'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),

by your database name (you must create one if you dont have any) and by that database username

like this

'database' => env('DB_DATABASE', 'MyDatabase'),
'username' => env('DB_USERNAME', 'MyUsername'),

How to extract a string between two delimiters

If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:

\[(.*?)\] this is your pattern. And in each group(1) will get you your string.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
    m.group(1); //is your string. do what you want
}

T-SQL to list all the user mappings with database roles/permissions for a Login

I wrote a little query to find permission of a user on a specific database.

    SELECT * FROM   
    (
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,p.NAME AS 'GRANTEE'
    ,m.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.database_role_members rm ON rm.role_principal_id = p.principal_id
    LEFT JOIN sys.database_principals m ON rm.member_principal_id = m.principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    UNION ALL
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,'SELF-GRANTED' AS 'GRANTEE'
    ,p.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    ) AS [union]
    WHERE [union].USERNAME = 'Username' -- Username you will search for
    ORDER BY [union].RIGHT_ON, [union].PERMISSION, [union].GRANTEE

The permissions of fixed database roles do not appear in sys.database_permissions. Therefore, database principals may have additional permissions not listed here.

I does not prefer

    EXECUTE AS USER = 'userName';
    SELECT * FROM fn_my_permissions(NULL, 'DATABASE') 

Because it's just retrieving which permissions the user has not where they come from!

Maybe i find out how to join the fixed database roles permission granted for the user one day...

Pls enjoy Life and hate the Users :D

Beautiful Soup and extracting a div and its contents by ID

I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".

This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.

The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.

This is my code, where I just try to print the number of tags "div" with class "fcontent":

from BeautifulSoup import BeautifulSoup 
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f) 
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)

Access Tomcat Manager App from different host

To access the tomcat manager from different machine you have to follow bellow steps:

1. Update conf/tomcat-users.xml file with user and some roles:

<role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".

Here tomcat user and password is : admin

2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):

Default configuration:

<Context antiResourceLocking="false" privileged="true" >
  
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
  
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>

Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .

2.a : Allow specefic IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />

Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address

2.b : Allow all IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />

Here using allow=".*" you are allowing all IP.

Thanks :)

TypeScript: Interfaces vs Types

the documentation has explained

  • One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.in older versions of TypeScript, type aliases couldn’t be extended or implemented from (nor could they extend/implement other types). As of version 2.7, type aliases can be extended by creating a new intersection type
  • On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.

Interfaces vs. Type Aliases

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

Java doesn't support true closures, even though using an anonymous class like you are using here (new TimerTask() { ... }) looks like a kind of closure.

edit - See the comments below - the following is not a correct explanation, as KeeperOfTheSoul points out.

This is why it doesn't work:

The variables lastPrice and price are local variables in the main() method. The object that you create with the anonymous class might last until after the main() method returns.

When the main() method returns, local variables (such as lastPrice and price) will be cleaned up from the stack, so they won't exist anymore after main() returns.

But the anonymous class object references these variables. Things would go horribly wrong if the anonymous class object tries to access the variables after they have been cleaned up.

By making lastPrice and price final, they are not really variables anymore, but constants. The compiler can then just replace the use of lastPrice and price in the anonymous class with the values of the constants (at compile time, of course), and you won't have the problem with accessing non-existent variables anymore.

Other programming languages that do support closures do it by treating those variables specially - by making sure they don't get destroyed when the method ends, so that the closure can still access the variables.

@Ankur: You could do this:

public static void main(String args[]) {
    int period = 2000;
    int delay = 2000;

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        // Variables as member variables instead of local variables in main()
        private double lastPrice = 0;
        private Price priceObject = new Price();
        private double price = 0;

        public void run() {
            price = priceObject.getNextPrice(lastPrice);
            System.out.println();
            lastPrice = price;
        }
    }, delay, period);      
}

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

How to Extract Year from DATE in POSTGRESQL

Choose one from, where :my_date is a string input parameter of yyyy-MM-dd format:

SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));

or

SELECT DATE_PART('year', CAST(:my_date AS DATE));

Better use CAST than :: as there may be conflicts with input parameters.

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

Can I append an array to 'formdata' in javascript?

var formData = new FormData; var arr = ['item1', 'item2', 'item3'];

arr.forEach(item => {
    formData.append(
        "myFile",item
    ); });

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Open your file with Notepad++, select "Encoding" or "Encodage" menu to identify or to convert from ANSI to UTF-8 or the ISO 8859-1 code page.

What is exactly the base pointer and stack pointer? To what do they point?

First of all, the stack pointer points to the bottom of the stack since x86 stacks build from high address values to lower address values. The stack pointer is the point where the next call to push (or call) will place the next value. It's operation is equivalent to the C/C++ statement:

 // push eax
 --*esp = eax
 // pop eax
 eax = *esp++;

 // a function call, in this case, the caller must clean up the function parameters
 move eax,some value
 push eax
 call some address  // this pushes the next value of the instruction pointer onto the
                    // stack and changes the instruction pointer to "some address"
 add esp,4 // remove eax from the stack

 // a function
 push ebp // save the old stack frame
 move ebp, esp
 ... // do stuff
 pop ebp  // restore the old stack frame
 ret

The base pointer is top of the current frame. ebp generally points to your return address. ebp+4 points to the first parameter of your function (or the this value of a class method). ebp-4 points to the first local variable of your function, usually the old value of ebp so you can restore the prior frame pointer.

Converting between java.time.LocalDateTime and java.util.Date

Everything is here : http://blog.progs.be/542/date-to-java-time

The answer with "round-tripping" is not exact : when you do

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

if your system timezone is not UTC/GMT, you change the time !

Change color inside strings.xml

Just add your text between the font tags:

for blue color

<string name="hello_world"><font color='blue'>Hello world!</font></string>

or for red color

<string name="hello_world"><font color='red'>Hello world!</font></string>

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

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

Thread.Sleep(50);

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

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

Thread.Join

Auto-indent spaces with C in vim?

I think the best answer is actually explained on the vim wikia:

http://vim.wikia.com/wiki/Indenting_source_code

Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

How to access a dictionary element in a Django template?

Ideally, you would create a method on the choice object that found itself in votes, or create a relationship between the models. A template tag that performed the dictionary lookup would work, too.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

You can do execute this command : rails g migration rename_{old_table_name}to{new_table_name}

after you edit the file and add this code in the method change

rename_table :{old_table_name}, :{new_table_name}

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
{
   <partial name="_MyItemView" model="item" />
}

How can I turn a List of Lists into a List in Java 8?

flatmap is better but there are other ways to achieve the same

List<List<Object>> listOfList = ... // fill

List<Object> collect = 
      listOfList.stream()
                .collect(ArrayList::new, List::addAll, List::addAll);

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Swing vs JavaFx for desktop applications

I'd look around to find some (3rd party?) components that do what you want. I've had to create custom Swing components for an agenda view where you can book multiple resources, as well as an Excel-like grid that works well with keyboard navigation and so on. I had a terrible time getting them to work nicely because I needed to delve into many of Swing's many intricacies whenever I came upon a problem. Mouse and focus behaviour and a lot of other things can be very difficult to get right, especially for a casual Swing user. I would hope that JavaFX is a bit more future-orientated and smooth out of the box.

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

jQuery remove options from select

Iterating a list and removing multiple items using a find. Response contains an array of integers. $('#OneSelectList') is a select list.

$.ajax({
    url: "Controller/Action",
    type: "GET",
    success: function (response) {
        // Take out excluded years.
        $.each(response, function (j, responseYear) {
            $('#OneSelectList').find('[value="' + responseYear + '"]').remove();
        });
    },
    error: function (response) {
        console.log("Error");
    }
});

Set Background color programmatically

If you just want to use some of the predefined Android colors, you can use Color.COLOR (where COLOR is BLACK, WHITE, RED, etc.):

myView.setBackgroundColor(Color.GREEN);

Otherwise you can do as others have suggested with

myView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.myCustomGreen));

I don't recommend using a hex color directly. You should keep all of your custom colors in colors.xml.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Like the rest, I went with callables too. But they have one downside: by default, you can't order on them. Fortunately, there is a solution for that:

Django >= 1.8

def author(self, obj):
    return obj.book.author
author.admin_order_field  = 'book__author'

Django < 1.8

def author(self):
    return self.book.author
author.admin_order_field  = 'book__author'

"Expected an indented block" error?

You have to indent the docstring after the function definition there (line 3, 4):

def print_lol(the_list):
"""this doesn't works"""
    print 'Ain't happening'

Indented:

def print_lol(the_list):
    """this works!"""
    print 'Aaaand it's happening'

Or you can use # to comment instead:

def print_lol(the_list):
#this works, too!
    print 'Hohoho'

Also, you can see PEP 257 about docstrings.

Hope this helps!

MySQL Data - Best way to implement paging?

From the MySQL documentation:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

How to add constraints programmatically using Swift

the following code works for me in this scenario: an UIImageView forced landscape.

    imagePreview!.isUserInteractionEnabled = true
    imagePreview!.isExclusiveTouch = true
    imagePreview!.contentMode = UIView.ContentMode.scaleAspectFit
    
    // Remove all constraints
    imagePreview!.removeAllConstraints()
    
    // Add the new constraints
    let guide = view.safeAreaLayoutGuide
    imagePreview!.translatesAutoresizingMaskIntoConstraints = false
    imagePreview!.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
    imagePreview!.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
    imagePreview!.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 1.0).isActive = true

where removeAllConstraints is an extension

extension UIView {
    
    func removeAllConstraints() {
        var _superview = self.superview
        
        func removeAllConstraintsFromView(view: UIView) { for c in view.constraints { view.removeConstraint(c) } }
        
        while let superview = _superview {
            for constraint in superview.constraints {
                
                if let first = constraint.firstItem as? UIView, first == self {
                    superview.removeConstraint(constraint)
                }
                
                if let second = constraint.secondItem as? UIView, second == self {
                    superview.removeConstraint(constraint)
                }
            }
            
            _superview = superview.superview
        }
        
        self.removeConstraints(self.constraints)
        self.translatesAutoresizingMaskIntoConstraints = true
    }
}

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

How to restart Activity in Android

Well this is not listed but a combo of some that is already posted:

if (Build.VERSION.SDK_INT >= 11) {
    recreate();   
} else {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .Net <= 4.0 Use the TimeSpan class.

TimeSpan t = TimeSpan.FromSeconds( secs );

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                t.Hours, 
                t.Minutes, 
                t.Seconds, 
                t.Milliseconds);

(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds to avoid an exception.

How to gracefully handle the SIGKILL signal in Java

It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.

The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, as expected. On a kill -15 it DOES run the shutdown hook every time.

public class TestShutdownHook
{
    public static void main(String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}

There isn't any way to really gracefully handle a kill -9 in any program.

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

The only real option to handle a kill -9 is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps command looking for your program in the list and act accordingly when it disappeared.

#!/usr/bin/env bash

java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"

How to use BigInteger?

java.math.BigInteger is an immutable class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:

sum = sum.add(BigInteger.valueOf(i));

Delete the first three rows of a dataframe in pandas

A simple way is to use tail(-n) to remove the first n rows

df=df.tail(-3)

Are lists thread-safe?

Here's a comprehensive yet non-exhaustive list of examples of list operations and whether or not they are thread safe. Hoping to get an answer regarding the obj in a_list language construct here.

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

MySQL "NOT IN" query

NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL in MySQL

MySQL, as well as all other systems except SQL Server, is able to optimize LEFT JOIN / IS NULL to return FALSE as soon the matching value is found, and it is the only system that cared to document this behavior. […] Since MySQL is not capable of using HASH and MERGE join algorithms, the only ANTI JOIN it is capable of is the NESTED LOOPS ANTI JOIN

[…]

Essentially, [NOT IN] is exactly the same plan that LEFT JOIN / IS NULL uses, despite the fact these plans are executed by the different branches of code and they look different in the results of EXPLAIN. The algorithms are in fact the same in fact and the queries complete in same time.

[…]

It’s hard to tell exact reason for [performance drop when using NOT EXISTS], since this drop is linear and does not seem to depend on data distribution, number of values in both tables etc., as long as both fields are indexed. Since there are three pieces of code in MySQL that essentialy do one job, it is possible that the code responsible for EXISTS makes some kind of an extra check which takes extra time.

[…]

MySQL can optimize all three methods to do a sort of NESTED LOOPS ANTI JOIN. […] However, these three methods generate three different plans which are executed by three different pieces of code. The code that executes EXISTS predicate is about 30% less efficient […]

That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

(emphases added)

PostgreSQL: How to make "case-insensitive" query

You can use ILIKE. i.e.

SELECT id FROM groups where name ILIKE 'administrator'

Performance of Arrays vs. Lists

[See also this question]

I've modified Marc's answer to use actual random numbers and actually do the same work in all cases.

Results:

         for      foreach
Array : 1575ms     1575ms (+0%)
List  : 1630ms     2627ms (+61%)
         (+3%)     (+67%)

(Checksum: -1000038876)

Compiled as Release under VS 2008 SP1. Running without debugging on a [email protected], .NET 3.5 SP1.

Code:

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>(6000000);
        Random rand = new Random(1);
        for (int i = 0; i < 6000000; i++)
        {
            list.Add(rand.Next());
        }
        int[] arr = list.ToArray();

        int chk = 0;
        Stopwatch watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                chk += list[i];
            }
        }
        watch.Stop();
        Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            int len = arr.Length;
            for (int i = 0; i < len; i++)
            {
                chk += arr[i];
            }
        }
        watch.Stop();
        Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in list)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in arr)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);
        Console.WriteLine();

        Console.ReadLine();
    }
}

How do I check for a network connection?

You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

How to combine results of two queries into a single dataset

Try this:

GET THE RECORD FOR CURRENT_MONTH, LAST_MONTH AND ALL_TIME AND MERGE THEM INTO SINGLE ARRAY

$analyticsData = $this->user->getMemberInfoCurrentMonth($userId);
$analyticsData1 = $this->user->getMemberInfoLastMonth($userId);
$analyticsData2 = $this->user->getMemberInfAllTime($userId);                        

    foreach ($analyticsData2 as $arr) {                
        foreach ($analyticsData1 as $arr1) {
            if ($arr->fullname == $arr1->fullname) {
                $arr->last_send_count = $arr1->last_send_count;
                break;
            }else{
                $arr->last_send_count = 0;
            }
        }
        foreach ($analyticsData as $arr2) {
            if ($arr->fullname == $arr2->fullname) {
                $arr->current_send_count = $arr2->current_send_count;
                break;
            }else{
                $arr->current_send_count = 0;
            }
        }
    }
    echo "<pre>";
    print_r($analyticsData2);die;

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

What is IllegalStateException?

public class UserNotFoundException extends Exception {
    public UserNotFoundException(String message) {
        super(message)

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

What do >> and << mean in Python?

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

Get Insert Statement for existing row in MySQL

Laptop Lift's code works fine, but there were a few things I figured people may like.

Database handler is an argument, not hardcoded. Used the new mysql api. Replaced $id with an optional $where argument for flexibility. Used real_escape_string in case anyone has ever tried to do sql injection and to avoid simple breakages involving quotes. Used the INSERT table (field...) VALUES (value...)... syntax so that the fields are defined only once and then just list off the values of each row (implode is awesome). Because Nigel Johnson pointed it out, I added NULL handling.

I used $array[$key] because I was worried it might somehow change, but unless something is horribly wrong, it shouldn't anyway.

<?php
function show_inserts($mysqli,$table, $where=null) {
    $sql="SELECT * FROM `{$table}`".(is_null($where) ? "" : " WHERE ".$where).";";
    $result=$mysqli->query($sql);

    $fields=array();
    foreach ($result->fetch_fields() as $key=>$value) {
        $fields[$key]="`{$value->name}`";
    }

    $values=array();
    while ($row=$result->fetch_row()) {
        $temp=array();
        foreach ($row as $key=>$value) {
            $temp[$key]=($value===null ? 'NULL' : "'".$mysqli->real_escape_string($value)."'");
        }
        $values[]="(".implode(",",$temp).")";
    }
    $num=$result->num_rows;
    return "INSERT `{$table}` (".implode(",",$fields).") VALUES \n".implode(",\n",$values).";";
}
?>

JavaScript push to array

It's not an array.

var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;

or

var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;

you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)

var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});

Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.

Do you recommend using semicolons after every statement in JavaScript?

I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.

Run JavaScript in Visual Studio Code

Well, to simply run the code and show the output on the console you can create a task and execute it, pretty much as @canerbalci mentions.

The downside of this is that you will only get the output and thats it.

What I really like to do is to be able to debug the code, lets say Im trying to solve a small algorithm or trying a new ES6 feature, and I run it and there is something fishy with it, I can debug it inside VSC.

So, instead of creating a task for it, I modified the .vscode/launch.json file in this directory as follows:

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "program": "${file}",
        "stopOnEntry": true,
        "args": [],
        "cwd": "${fileDirname}",
        "runtimeExecutable": null,
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "NODE_ENV": "development"
        },
        "externalConsole": false,
        "sourceMaps": false,
        "outDir": null
    }
]
}

What this does is that it will launch whichever file you are currently on, within the debugger of VSC. Its set to stop on start.

To launch it, press F5 key, in the file you want to debug.

How do I "un-revert" a reverted Git commit?

I had an issue somebody made a revert to master to my branch, but I was needed to be able to merge it again but the problem is that the revert included all my commit. Lets look at that case we created our feature branch from M1 we merge our feature branch in M3 and revert on it in RM3

M1 -> M2 -> M3 -> M4- > RM3 -> M5
 \.         /
  F1->F2 -

How to make the F2 able to merge to M5?

git checkout master
git checkout -b brach-before-revert
git reset --hard M4
git checkout master
git checkout -b new-feature-branch
git reset --hard M1 
git merge --squash brach-before-revert

Effective way to find any file's Encoding

Providing the implementation details for the steps proposed by @CodesInChaos:

1) Check if there is a Byte Order Mark

2) Check if the file is valid UTF8

3) Use the local "ANSI" codepage (ANSI as Microsoft defines it)

Step 2 works because most non ASCII sequences in codepages other that UTF8 are not valid UTF8. https://stackoverflow.com/a/4522251/867248 explains the tactic in more details.

using System; using System.IO; using System.Text;

// Using encoding from BOM or UTF8 if no BOM found,
// check if the file is valid, by reading all lines
// If decoding fails, use the local "ANSI" codepage

public string DetectFileEncoding(Stream fileStream)
{
    var Utf8EncodingVerifier = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
    using (var reader = new StreamReader(fileStream, Utf8EncodingVerifier,
           detectEncodingFromByteOrderMarks: true, leaveOpen: true, bufferSize: 1024))
    {
        string detectedEncoding;
        try
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
            }
            detectedEncoding = reader.CurrentEncoding.BodyName;
        }
        catch (Exception e)
        {
            // Failed to decode the file using the BOM/UT8. 
            // Assume it's local ANSI
            detectedEncoding = "ISO-8859-1";
        }
        // Rewind the stream
        fileStream.Seek(0, SeekOrigin.Begin);
        return detectedEncoding;
   }
}


[Test]
public void Test1()
{
    Stream fs = File.OpenRead(@".\TestData\TextFile_ansi.csv");
    var detectedEncoding = DetectFileEncoding(fs);

    using (var reader = new StreamReader(fs, Encoding.GetEncoding(detectedEncoding)))
    {
       // Consume your file
        var line = reader.ReadLine();
        ...

Can you target <br /> with css?

Why not just use the HR tag? It's made exactly for what you want. Kinda like trying to make a fork for eating soup when there's a spoon right in front of you on the table.

How to put php inside JavaScript?

All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:

<FilesMatch "\.(js)$">
    AddHandler application/x-httpd-php .js
</FilesMatch>

Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:

<html>
<head>
<script>
function myFunction(){
   alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>

How can I switch themes in Visual Studio 2012

Also, you can use or create and share Visual Studio color schemes: https://studiostyl.es/

How to view unallocated free space on a hard disk through terminal

If you need to see your partitions and/or filers with available space, mentioned utilities are what you need. You just need to use options.

For instance: df -h will print you those information in "human-readable" form. If you need information only about free space, you could use: df -h | awk '{print $1" "$4}'.

expected assignment or function call: no-unused-expressions ReactJS

For me the error occured when using map. And I didn't use the return Statement inside the map.

{cart.map((cart_products,index) => {
    <span>{cart_products.id}</span>; 
})};

Above code produced error.

{cart.map((cart_products,index) => {
    return (<span>{cart_products.id}</span>); 
})};

Simply adding return solved it.

Can you split/explode a field in a MySQL query?

SELECT
  tab1.std_name, tab1.stdCode, tab1.payment,
  SUBSTRING_INDEX(tab1.payment, '|', 1) as rupees,
  SUBSTRING(tab1.payment, LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 1)) + 2,LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 2))) as date
FROM (
  SELECT DISTINCT
    si.std_name, hfc.stdCode,
    if(isnull(hfc.payDate), concat(hfc.coutionMoneyIn,'|', year(hfc.startDtae), '-',  monthname(hfc.startDtae)), concat(hfc.payMoney, '|', monthname(hfc.payDate), '-', year(hfc.payDate))) AS payment
  FROM hostelfeescollection hfc
  INNER JOIN hostelfeecollectmode hfm ON hfc.tranId = hfm.tranId
  INNER JOIN student_info_1 si ON si.std_code = hfc.stdCode
  WHERE hfc.tranId = 'TRAN-AZZZY69454'
) AS tab1

Making Maven run all tests, even when some fail

I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

Read and Write CSV files including unicode with Python 2.7

I couldn't respond to Mark above, but I just made one modification which fixed the error which was caused if data in the cells was not unicode, i.e. float or int data. I replaced this line into the UnicodeWriter function: "self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])" so that it became:

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
       self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
    def writerow(self, row):
        '''writerow(unicode) -> None
        This function takes a Unicode string and encodes it to the output.
        '''
        self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        data = self.encoder.encode(data)
        self.stream.write(data)
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

You will also need to "import types".

Converting int to bytes in Python 3

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

how to implement Pagination in reactJs

I've implemented pagination in pure React JS recently. Here is a working demo: http://codepen.io/PiotrBerebecki/pen/pEYPbY

You would of course have to adjust the logic and the way page numbers are displayed so that it meets your requirements.

Full code:

class TodoApp extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: ['a','b','c','d','e','f','g','h','i','j','k'],
      currentPage: 1,
      todosPerPage: 3
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    this.setState({
      currentPage: Number(event.target.id)
    });
  }

  render() {
    const { todos, currentPage, todosPerPage } = this.state;

    // Logic for displaying todos
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

    const renderTodos = currentTodos.map((todo, index) => {
      return <li key={index}>{todo}</li>;
    });

    // Logic for displaying page numbers
    const pageNumbers = [];
    for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
      pageNumbers.push(i);
    }

    const renderPageNumbers = pageNumbers.map(number => {
      return (
        <li
          key={number}
          id={number}
          onClick={this.handleClick}
        >
          {number}
        </li>
      );
    });

    return (
      <div>
        <ul>
          {renderTodos}
        </ul>
        <ul id="page-numbers">
          {renderPageNumbers}
        </ul>
      </div>
    );
  }
}


ReactDOM.render(
  <TodoApp />,
  document.getElementById('app')
);

How to pause a YouTube player when hiding the iframe?

I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:

<div id="videoModalXX">
...
    <button onclick="stopVideo(videoID);" type="button" class="close"></button>
    ...
    <iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>

In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:

function stopVideo(id)
{
    $("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}

I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.

Multiple axis line chart in excel

Taking the answer above as guidance;

I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.

Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.

The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.

Thanks to the guy above for the idea!

Which HTTP methods match up to which CRUD methods?

There's a great youtube video talk by stormpath with actually explains this, the URL should skip to the correct part of the video:

stormpath youtube video

Also it's worth watch it's over an hour of talking but very intersting if your thinking of investing time in building a REST api.

How can I move a tag on a git branch to a different commit?

Use the -f option to git tag:

-f
--force

    Replace an existing tag with the given name (instead of failing)

You probably want to use -f in conjunction with -a to force-create an annotated tag instead of a non-annotated one.

Example

  1. Delete the tag on any remote before you push

    git push origin :refs/tags/<tagname>
    
  2. Replace the tag to reference the most recent commit

    git tag -fa <tagname>
    
  3. Push the tag to the remote origin

    git push origin master --tags
    

Save and load weights in keras

For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

show dbs gives "Not Authorized to execute command" error

one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".

The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.

cmd-1:

use admin
db.createUser({
  user: "newUsername",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

cmd-2:

db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])

Padding between ActionBar's home icon and title

Im using a custom image instead of the default title text to the right of my apps logo. This is set up programatically like

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setCustomView(R.layout.include_ab_txt_logo);
    actionBar.setDisplayShowCustomEnabled(true);

The issues with the above answers for me are @Cliffus's suggestion does not work for me due to the issues others have outlined in the comments and while @dushyanth programatic padding setting may have worked in the past I would think that the fact that the spacing is now set using android:layout_marginEnd="8dip" since API 17 manually setting the padding should have no effect. See the link he posted to git to verify its current state.

A simple solution for me is to set a negative margin on my custom view in the actionBar, like so android:layout_marginLeft="-14dp". A quick test shows it works for me on 2.3.3 and 4.3 using ActionBarCompat

Hope this helps someone!

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

In short, to ensure proper unicode handling in Python 2:

  • use io.open for reading/writing files
  • use from __future__ import unicode_literals
  • configure other data inputs/outputs (e.g., databases, network) to use unicode
  • if you cannot configure outputs to utf-8, convert your output for them print(text.encode('ascii', 'replace').decode())

For explanations, see @Alastair McCormack's detailed answer.

How to make a list of n numbers in Python and randomly select any number?

Create the list (edited):

count_list = range(1, N+1)

Select random element:

import random
random.choice(count_list)

inject bean reference into a Quartz job in Spring?

This is the right answer http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring/15211030#15211030. and will work for most of the folks. But if your web.xml does is not aware of all applicationContext.xml files, quartz job will not be able to invoke those beans. I had to do an extra layer to inject additional applicationContext files

public class MYSpringBeanJobFactory extends SpringBeanJobFactory
        implements ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {

        try {
                PathMatchingResourcePatternResolver pmrl = new PathMatchingResourcePatternResolver(context.getClassLoader());
                Resource[] resources = new Resource[0];
                GenericApplicationContext createdContext = null ;
                    resources = pmrl.getResources(
                            "classpath*:my-abc-integration-applicationContext.xml"
                    );

                    for (Resource r : resources) {
                        createdContext = new GenericApplicationContext(context);
                        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(createdContext);
                        int i = reader.loadBeanDefinitions(r);
                    }

            createdContext.refresh();//important else you will get exceptions.
            beanFactory = createdContext.getAutowireCapableBeanFactory();

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



    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle)
            throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

You can add any number of context files you want your quartz to be aware of.

npm notice created a lockfile as package-lock.json. You should commit this file

came out of this issue by changing the version in package.json file and also changing the name of the package and finally deleted the package-lock.json file

How to fetch all Git branches

$ git remote update
$ git pull --all

This assumes all branches are tracked.

If they aren't you can fire this in Bash:

for remote in `git branch -r `; do git branch --track $remote; done

Then run the command.

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

Font Awesome 5 font-family issue

IF it's still not working for you, I had forgotten to add the fa-ul class onto the parent (UL) element:

<ul class="fa-ul">

Together with the 2 bits of advice provided already by others:

a) font-family: 'Font Awesome\ 5 Free';
b) font-weight: 900;

solved it for me.

FWIW, the include in my <head> tags is just:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />

And I am using this with React and Preact. No need for any special React npm installs or components.

How to pass form input value to php function

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

Removing leading zeroes from a field in a SQL statement

select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)

split python source code into multiple files?

Sure!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

How to insert data into elasticsearch

To test and try curl requests from Windows, you can make use of Postman client Chrome extension. It is very simple to use and quite powerful.

Or as suggested you can install the cURL util.

A sample curl request is as follows.

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"user" : "Arun Thundyill Saseendran",
"post_date" : "2009-03-23T12:30:00",
"message" : "trying out Elasticsearch"
}' "http://10.103.102.56:9200/sampleindex/sampletype/"

I am also getting started with and exploring ES in vast. So please let me know if you have any other doubts.

EDIT: Updated the index name and type name to be fully lowercase to avoid errors and follow convention.

How to create id with AUTO_INCREMENT on Oracle?

FUNCTION GETUNIQUEID_2 RETURN VARCHAR2
AS
v_curr_id NUMBER;
v_inc NUMBER;
v_next_val NUMBER;
pragma autonomous_transaction;
begin 
CREATE SEQUENCE sequnce
START WITH YYMMDD0000000001
INCREMENT BY 1
NOCACHE
select sequence.nextval into v_curr_id from dual;
if(substr(v_curr_id,0,6)= to_char(sysdate,'yymmdd')) then
v_next_val := to_number(to_char(SYSDATE+1, 'yymmdd') || '0000000000');
v_inc := v_next_val - v_curr_id;
execute immediate ' alter sequence sequence increment by ' || v_inc ;
select sequence.nextval into v_curr_id from dual;
execute immediate ' alter sequence sequence increment by 1';
else
dbms_output.put_line('exception : file not found');
end if;
RETURN 'ID'||v_curr_id;
END;

Python, Matplotlib, subplot: How to set the axis range?

Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))

signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)

fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))

plt.show()

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

Change MySQL default character set to UTF-8 in my.cnf?

This question already has a lot of answers, but Mathias Bynens mentioned that 'utf8mb4' should be used instead of 'utf8' in order to have better UTF-8 support ('utf8' does not support 4 byte characters, fields are truncated on insert). I consider this to be an important difference. So here is yet another answer on how to set the default character set and collation. One that'll allow you to insert a pile of poo ().

This works on MySQL 5.5.35.

Note, that some of the settings may be optional. As I'm not entirely sure that I haven't forgotten anything, I'll make this answer a community wiki.

Old Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+-------------------+
| Variable_name        | Value             |
+----------------------+-------------------+
| collation_connection | utf8_general_ci   |
| collation_database   | latin1_swedish_ci |
| collation_server     | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)

Config

#  
# UTF-8 should be used instead of Latin1. Obviously.
# NOTE "utf8" in MySQL is NOT full UTF-8: http://mathiasbynens.be/notes/mysql-utf8mb4

[client]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

New Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8mb4_general_ci |
| collation_database   | utf8mb4_unicode_ci |
| collation_server     | utf8mb4_unicode_ci |
+----------------------+--------------------+
3 rows in set (0.00 sec)

character_set_system is always utf8.

This won't affect existing tables, it's just the default setting (used for new tables). The following ALTER code can be used to convert an existing table (without the dump-restore workaround):

ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Edit:

On a MySQL 5.0 server: character_set_client, character_set_connection, character_set_results, collation_connection remain at latin1. Issuing SET NAMES utf8 (utf8mb4 not available in that version) sets those to utf8 as well.


Caveat: If you had a utf8 table with an index column of type VARCHAR(255), it can't be converted in some cases, because the maximum key length is exceeded (Specified key was too long; max key length is 767 bytes.). If possible, reduce the column size from 255 to 191 (because 191 * 4 = 764 < 767 < 192 * 4 = 768). After that, the table can be converted.

Get local IP address

Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].MapToIPv4() //returns 192.168.14.1

enter image description here

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

How do I use NSTimer?

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO];

-(void)timerCalled
{
     NSLog(@"Timer Called");
     // Your Code
}

SqlDataAdapter vs SqlDataReader

Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.

Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.

How to change the new TabLayout indicator color and height

Since I can't post a follow-up to android developer's comment, here's an updated answer for anyone else who needs to programmatically set the selected tab indicator color:

tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));

Similarly, for height:

tabLayout.setSelectedTabIndicatorHeight((int) (2 * getResources().getDisplayMetrics().density));

These methods were only recently added to revision 23.0.0 of the Support Library, which is why Soheil Setayeshi's answer uses reflection.

Is it possible to use if...else... statement in React render function?

There actually is a way to do exactly what OP is asking. Just render and call an anonymous function like so:

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}

Delete file from internal storage

This is an old topic, but I will add my experience, maybe someone finds this helpful

>     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created

2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it

solution1:

              Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri

here I initialize Content resolver and delete it with a passed parameter of that URI

            ContentResolver contentResolver = getContentResolver ();
            contentResolver.delete (uriDelete,null ,null );

solution2(my first solution-from head in this time I do know that ): content resolver exists...

              String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                    adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);

            File file = new File (path);
            if (file != null) {
                file.delete ();
            }

Hope that this will be helpful to someone happy coding

How do I add an image to a JButton

public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }

'python3' is not recognized as an internal or external command, operable program or batch file

For Python 27

virtualenv -p C:\Python27\python.exe django_concurrent_env

For Pyton36

 virtualenv -p C:\Python36\python.exe django_concurrent_env

sql server #region

I've used a technique similar to McVitie's, and only in stored procedures or scripts that are pretty long. I will break down certain functional portions like this:

BEGIN /** delete queries **/

DELETE FROM blah_blah

END /** delete queries **/

BEGIN /** update queries **/

UPDATE sometable SET something = 1

END /** update queries **/

This method shows up fairly nice in management studio and is really helpful in reviewing code. The collapsed piece looks sort of like:

BEGIN /** delete queries **/ ... /** delete queries **/

I actually prefer it this way because I know that my BEGIN matches with the END this way.

Pass in an enum as a method parameter

If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

How to shutdown a Spring Boot Application in a correct way?

As to @Jean-Philippe Bond 's answer ,

here is a maven quick example for maven user to configure HTTP endpoint to shutdown a spring boot web app using spring-boot-starter-actuator so that you can copy and paste:

1.Maven pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2.application.properties:

#No auth  protected 
endpoints.shutdown.sensitive=false

#Enable shutdown endpoint
endpoints.shutdown.enabled=true

All endpoints are listed here:

3.Send a post method to shutdown the app:

curl -X POST localhost:port/shutdown

Security Note:

if you need the shutdown method auth protected, you may also need

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

configure details:

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

An unhandled exception was generated during the execution of the current web request

As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

How to lose margin/padding in UITextView?

For iOS 10, the following line works for the top and bottom padding removing.

captionTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)

ExecutorService that interrupts tasks after a timeout

How about using the ExecutorService.shutDownNow() method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.

Unbound classpath container in Eclipse

To fix this:

  • Right click your project –> Build Path –>Configure Build Path
  • Select JRE Library and click Edit and from Edit library window choose alternate JRE whatever been configured with your eclipse then click Finish

Firefox 'Cross-Origin Request Blocked' despite headers

Turns out this has nothing to do with CORS- it was a problem with the security certificate. Misleading errors = 4 hours of headaches.

How to install SignTool.exe for Windows 10

You need to install the Windows 10 SDK.

  1. Visual Studio 2015 Update 1 contains it already, but it is not installed by default. You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change".

Visual Studio 2015 setup will start. Select "Modify".

In Visual Studio components list find "Universal Windows App Development Tools", open the list of sub-items and select "Windows 10 SDK (10.0.10240)".

Windows 10 SDK in VS 2015 Update 1 Setup

  1. Of cause you can install Windows 10 SDK directly from Microsoft: https://go.microsoft.com/fwlink/?LinkID=698771

As josant already wrote - when the installation finishes you will find the SignTool.exe in the folders:

  • x86 -> c:\Program Files (x86)\Windows Kits\10\bin\x86
  • x64 -> c:\Program Files (x86)\Windows Kits\10\bin\x64\

Merge Two Lists in R

This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

appendList <- function (x, val) 
{
    stopifnot(is.list(x), is.list(val))
    xnames <- names(x)
    for (v in names(val)) {
        x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
            appendList(x[[v]], val[[v]])
        else c(x[[v]], val[[v]])
    }
    x
}

> appendList(first,second)
$a
[1] 1 2

$b
[1] 2 3

$c
[1] 3 4

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

Insert if not exists Oracle

The statement is called MERGE. Look it up, I'm too lazy.

Beware, though, that MERGE is not atomic, which could cause the following effect (thanks, Marius):

SESS1:

create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;

SESS2: insert into t1 values(2, 2);

SESS1:

MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);

SESS2: commit;

SESS1: ORA-00001

Getting attributes of a class

two function:

def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

use:

>>> class MyClass:
    a = "12"
    b = "34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}

dropzone.js - how to do something after ALL files are uploaded

EDIT: There is now a queuecomplete event that you can use for exactly that purpose.


Previous answer:

Paul B.'s answer works, but an easier way to do so, is by checking if there are still files in the queue or uploading whenever a file completes. This way you don't have to keep track of the files yourself:

Dropzone.options.filedrop = {
  init: function () {
    this.on("complete", function (file) {
      if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
        doSomething();
      }
    });
  }
};

Determine number of pages in a PDF file

One Line:

int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;

Recommended: ITEXTSHARP

How to drop a table if it exists?

I hope this helps:

begin try drop table #tempTable end try
begin catch end catch

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Java, How to add values to Array List used as value in HashMap

Java 8+ has computeIfAbsent

examList.computeIfAbsent(map.get(id), k -> new ArrayList<>());
map.get(id).add(value);

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-

Windows batch: sleep

I just wrote my own sleep which called the Win32 Sleep API function.