Programs & Examples On #Prototypejs

Prototype is a JavaScript Framework that extends built-in classes to ease JS development. Do not use this tag for questions about the JS prototype object extension, as that is unrelated

How to show loading spinner in jQuery?

I've used the following with jQuery UI Dialog. (Maybe it works with other ajax callbacks?)

$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
    height: 300,
    width: 600,
    title: 'Wait for it...'
});

The contains an animated loading gif until its content is replaced when the ajax call completes.

How to autosize a textarea using Prototype?

Probably the shortest solution:

jQuery(document).ready(function(){
    jQuery("#textArea").on("keydown keyup", function(){
        this.style.height = "1px";
        this.style.height = (this.scrollHeight) + "px"; 
    });
});

This way you don't need any hidden divs or anything like that.

Note: you might have to play with this.style.height = (this.scrollHeight) + "px"; depending on how you style the textarea (line-height, padding and that kind of stuff).

Testing the type of a DOM element in JavaScript

I have another way of testing the same.

_x000D_
_x000D_
Element.prototype.typeof = "element";_x000D_
var element = document.body; // any dom element_x000D_
if (element && element.typeof == "element"){_x000D_
   return true; _x000D_
   // this is a dom element_x000D_
}_x000D_
else{_x000D_
  return false; _x000D_
  // this isn't a dom element_x000D_
}
_x000D_
_x000D_
_x000D_

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Here is working code for me

I wanted to convert 'Text' string to HTML element

var diva = UWA.createElement('div');
diva.innerHTML = '<a href="http://wwww.example.com">Text</a>';
var aelement = diva.firstChild;

How to iterate (keys, values) in JavaScript?

As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:

for (var key in dictionary) {
    if (!dictionary.hasOwnProperty(key)) {
        continue;
    }
    console.log(key, dictionary[key]);
}

Edit: info about Object.hasOwnProperty here

Text-align class for inside a table

Using Bootstrap 3.x using text-right works perfectly:

<td class="text-right">
  text aligned
</td>

SQL Joins Vs SQL Subqueries (Performance)?

You can use an Explain Plan to get an objective answer.

For your problem, an Exists filter would probably perform the fastest.

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

how to include js file in php?

PHP is completely irrelevant for what you are doing. The generated HTML is what counts.

In your case, you are missing the src attribute. Use

 <script type="text/javascript" src="file.js"></script>

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

How to calculate md5 hash of a file using javascript

Apart from the impossibility to get file system access in JS, I would not put any trust at all in a client-generated checksum. So generating the checksum on the server is mandatory in any case. – Tomalak Apr 20 '09 at 14:05

Which is useless in most cases. You want the MD5 computed at client side, so that you can compare it with the code recomputed at server side and conclude the upload went wrong if they differ. I have needed to do that in applications working with large files of scientific data, where receiving uncorrupted files were key. My cases was simple, cause users had the MD5 already computed from their data analysis tools, so I just needed to ask it to them with a text field.

iptables LOG and DROP in one rule

nflog is better

sudo apt-get -y install ulogd2

ICMP Block rule example:

iptables=/sbin/iptables
# Drop ICMP (PING)
$iptables -t mangle -A PREROUTING -p icmp -j NFLOG --nflog-prefix 'ICMP Block'
$iptables -t mangle -A PREROUTING -p icmp -j DROP

And you can search prefix "ICMP Block" in log:

/var/log/ulog/syslogemu.log

Returning a pointer to a vector element in c++

Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself.

Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element.

In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often.

EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos'

Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer.

Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const_' from the definition of the iterator).

What is the difference between properties and attributes in HTML?

Difference HTML properties and attributes:

Let's first look at the definitions of these words before evaluating what the difference is in HTML:

English definition:

  • Attributes are referring to additional information of an object.
  • Properties are describing the characteristics of an object.

In HTML context:

When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:

  • Attributes are additional information which we can put in the HTML to initialize certain DOM properties.
  • Properties are formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered

It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.

Furthermore have different DOM elements different properties. For example, an <input> element has a value property which is not present on a <div> property.

Example:

Let's take the following HTML document:

 <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">  <!-- charset is a attribute -->
  <meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
  <title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>

Then we inspect the <div>, in the JS console:

 console.dir(document.getElementById('foo'));

We see the following DOM properties (chrome devtools, not all properties shown):

html properties and attributes

  • We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
  • We can see that the class attribute in the HTML has no corresponding class property (class is reserved keyword in JS). But actually 2 properties, classList and className.

Asynchronously wait for Task<T> to complete with timeout

Here's a extension method version that incorporates cancellation of the timeout when the original task completes as suggested by Andrew Arnott in a comment to his answer.

public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) {

    using (var timeoutCancellationTokenSource = new CancellationTokenSource()) {

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task) {
            timeoutCancellationTokenSource.Cancel();
            return await task;  // Very important in order to propagate exceptions
        } else {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

Getting only response header from HTTP POST using curl

While the other answers have not worked for me in all situations, the best solution I could find (working with POST as well), taken from here:

curl -vs 'https://some-site.com' 1> /dev/null

JSON order mixed up

Underscore-java uses linkedhashmap to store key/value for json. I am the maintainer of the project.

Map<String, Object> myObject = new LinkedHashMap<>();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");

System.out.println(U.toJson(myObject));

Handling NULL values in Hive

I use below sql to exclude the null string and empty string lines.

select * from table where length(nvl(column1,0))>0

Because, the length of empty string is 0.

select length('');
+-----------+--+
| length()  |
+-----------+--+
| 0         |
+-----------+--+

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

Install specific version using laravel installer

Via composer installing specific version 7.*

composer create-project --prefer-dist laravel/laravel:^7.0 project_name

To install specific version 6.* and below use the following command:

composer create-project --prefer-dist laravel/laravel project_name "6.*"

Object spread vs. Object.assign

I'd like to add this simple example when you have to use Object.assign.

class SomeClass {
  constructor() {
    this.someValue = 'some value';
  }

  someMethod() {
    console.log('some action');
  }
}


const objectAssign = Object.assign(new SomeClass(), {});
objectAssign.someValue; // ok
objectAssign.someMethod(); // ok

const spread = {...new SomeClass()};
spread.someValue; // ok
spread.someMethod(); // there is no methods of SomeClass!

It can be not clear when you use JavaScript. But with TypeScript it is easier if you want to create instance of some class

const spread: SomeClass = {...new SomeClass()} // Error

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

I had the same issue. It is solved when I made composer globally available. Now I am able to tun the commands from any where in the folder.

composer update

composer require "samplelibraryyouwant"

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

How to import existing *.sql files in PostgreSQL 8.4?

Well, the shortest way I know of, is following:

psql -U {user_name} -d {database_name} -f {file_path} -h {host_name}

database_name: Which database should you insert your file data in.

file_path: Absolute path to the file through which you want to perform the importing.

host_name: The name of the host. For development purposes, it is mostly localhost.

Upon entering this command in console, you will be prompted to enter your password.

How to redirect all HTTP requests to HTTPS

 Redirect 301 / https://example.com/

(worked for me when none of the above answers worked)

Bonus:

ServerAlias www.example.com example.com

(fixed https://www.example.com not found)

Deleting a pointer in C++

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

How can I submit a form using JavaScript?

HTML

<!-- change id attribute to name  -->

<form method="post" action="yourUrl" name="theForm">
    <button onclick="placeOrder()">Place Order</button>
</form>

JavaScript

function placeOrder () {
    document.theForm.submit()
}

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

How to redirect to a 404 in Rails?

The selected answer doesn't work in Rails 3.1+ as the error handler was moved to a middleware (see github issue).

Here's the solution I found which I'm pretty happy with.

In ApplicationController:

  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, with: :handle_exception
  end

  def not_found
    raise ActionController::RoutingError.new('Not Found')
  end

  def handle_exception(exception=nil)
    if exception
      logger = Logger.new(STDOUT)
      logger.debug "Exception Message: #{exception.message} \n"
      logger.debug "Exception Class: #{exception.class} \n"
      logger.debug "Exception Backtrace: \n"
      logger.debug exception.backtrace.join("\n")
      if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
        return render_404
      else
        return render_500
      end
    end
  end

  def render_404
    respond_to do |format|
      format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

  def render_500
    respond_to do |format|
      format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
      format.all { render nothing: true, status: 500}
    end
  end

and in application.rb:

config.after_initialize do |app|
  app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end

And in my resources (show, edit, update, delete):

@resource = Resource.find(params[:id]) or not_found

This could certainly be improved, but at least, I have different views for not_found and internal_error without overriding core Rails functions.

Ruby: How to turn a hash into HTTP parameters?

If you are in the context of a Faraday request, you can also just pass the params hash as the second argument and faraday takes care of making proper param URL part out of it:

faraday_instance.get(url, params_hsh)

How to add smooth scrolling to Bootstrap's scroll spy function

I combined it, and this is the results -

$(document).ready(function() {
     $("#toTop").hide();

            // fade in & out
       $(window).scroll(function () {
                    if ($(this).scrollTop() > 400) {
                        $('#toTop').fadeIn();
                    } else {
                        $('#toTop').fadeOut();
                    }
                });     
  $('a[href*=#]').each(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
      var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
      var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
       if ($target) {
         var targetOffset = $target.offset().top;
         $(this).click(function() {
           $('html, body').animate({scrollTop: targetOffset}, 400);
           return false;
         });
      }
    }
  });
});

I tested it and it works fine. hope this will help someone :)

What is the difference between JOIN and UNION?

You may see the same schematic explanations for both, but these are totally confusing.

For UNION:

Enter image description here

For JOIN:

Enter image description here

Deserialize JSON to ArrayList<POJO> using Jackson

You can deserialize directly to a list by using the TypeReference wrapper. An example method:

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;
}

And is used thus:

final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);

TypeReference Javadoc

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

CodeIgniter - return only one row?

To add on to what Alisson said you could check to see if a row is returned.

// Query stuff ...
$query = $this->db->get();

if ($query->num_rows() > 0)
{
    $row = $query->row(); 
    return $row->campaign_id;
}

return null; // or whatever value you want to return for no rows found

how to convert string to numerical values in mongodb

You can easily convert the string data type to numerical data type.

Don't forget to change collectionName & FieldName. for ex : CollectionNmae : Users & FieldName : Contactno.

Try this query..

db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});

How to write log file in c#?

if(!File.Exists(filename)) //No File? Create
{
    fs = File.Create(filename);
    fs.Close();
}
if(File.ReadAllBytes().Length >= 100*1024*1024) // (100mB) File to big? Create new
{
    string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end
    if(filename.contains("-")) //Check if older log contained -x
    {
         int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers
         lognumber++; //Increment lognumber by 1
         filename = filenamebase + "-" + lognumber + ".log"; //Override filename
    }
    else 
    {
         filename = filenamebase + "-1.log"; //Override filename
    }
    fs = File.Create(filename);
    fs.Close();
}

Refer link:

http://www.codeproject.com/Questions/163337/How-to-write-in-log-Files-in-C

How can I make a CSS table fit the screen width?

Put the table in a container element that has

overflow:scroll; max-width:95vw;

or make the table fit to the screen and overflow:scroll all table cells.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
* append(item) add item to the end of the list,
* insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In my case: spring boot 2 ,multiple datasource(default and custom). entityManager.createQuery go wrong: 'entity is not mapped'

while debug, i find out that the entityManager's unitName is wrong(should be custom,but the fact is default) the right way:

@PersistenceContext(unitName = "customer1") // !important, 
private EntityManager em;

the customer1 is from the second datasource config class:

@Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier("customer1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
            .persistenceUnit("customer1")
            // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
            // injects an EntityManager.
            // It's generally better to use PersistenceContext unless you really need to
            // manage the EntityManager lifecycle manually.
            // ?4?
            .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}

Then,the entityManager is right.

But, em.persist(entity) doesn't work,and the transaction doesn't work.

Another important point is:

@Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
    //test persist,working right!
    Trade t = new Trade();
    em.persist(t);
    log.info("t.id" + t.getSysTradeId());

    //test transactional, working right!
    int a = 3/0;
}

customer1TransactionManager is from the second datasource config class:

@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
        @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

The whole second datasource config class is :

package com.lichendt.shops.sync;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
        // ?1??????DAO???? ,????DAO?? com.xx.DAO??,????? com.xx.DAO
        basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "customer1DatasourceProperties")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource")
    public DataSourceProperties customer1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "customer1DataSource")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource") //
    // ?2?datasource?????,???? ?mysql?yaml???
    public DataSource dataSource() {
        // return DataSourceBuilder.create().build();
        return customer1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "customer1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("customer1DataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // ?3???????????
                .persistenceUnit("customer1")
                // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
                // injects an EntityManager.
                // It's generally better to use PersistenceContext unless you really need to
                // manage the EntityManager lifecycle manually.
                // ?4?
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
    }

    @Bean(name = "customer1TransactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

How do you truncate all tables in a database using TSQL?

For SQL 2005,

EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'

Couple more links for 2000 and 2005/2008..

Check If array is null or not in php

if array is look like this [null] or [null, null] or [null, null, null, ...]

you can use implode:

implode is use for convert array to string.

if(implode(null,$arr)==null){
     //$arr is empty
}else{
     //$arr has some value rather than null
}

C# How to change font of a label

I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in

- XP SP3 and Win 10 Pro 64

private void SetFont(Form f, string name, int size, FontStyle style)
{
    Font replacementFont = new Font(name, size, style);
    f.Font = replacementFont;
}

Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.

    /// To call the function do this.
    /// e.g in the form load event etc.

public Form1()
{
      InitializeComponent();
      SetFont(this, "Arial", 8, FontStyle.Bold);  
      // This sets the whole form and 
      // everything below it.
      // Shaun Cassidy.
}

You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.

Github DLL

/// and then import the namespace
using Droitech.TextFont;

/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);

Simple.

SSIS how to set connection string dynamically from a config file

These answers are right, but old and works for Depoloyement Package Model. What I Actually needed is to change the server name, database name of a connection manager and i found this very helpful:

https://www.youtube.com/watch?v=_yLAwTHH_GA

Better for people using SQL Server 2012-2014-2016 ... with Deployment Project Model

Display loading image while post with ajax

<div id="load" style="display:none"><img src="ajax-loader.gif"/></div>

function getData(p){
        var page=p;
        document.getElementById("load").style.display = "block";  // show the loading message.
        $.ajax({
            url: "loadData.php?id=<? echo $id; ?>",
            type: "POST",
            cache: false,
            data: "&page="+ page,
            success : function(html){
                $(".content").html(html);
        document.getElementById("load").style.display = "none";
            }
        });

How can I output UTF-8 from Perl?

Thanks, finally got an solution to not put utf8::encode all over code. To synthesize and complete for other cases, like write and read files in utf8 and also works with LoadFile of an YAML file in utf8

use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

open(FH, ">test.txt"); 
print FH "something éá";

use YAML qw(LoadFile Dump);
my $PUBS = LoadFile("cache.yaml");
my $f = "2917";
my $ref = $PUBS->{$f};
print "$f \"".$ref->{name}."\" ". $ref->{primary_uri}." ";

where cache.yaml is:

---
2917:
  id: 2917
  name: Semanário
  primary_uri: 2917.xml

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

Ranges of floating point datatype in C?

A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:

(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) = 
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) = 
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38

Read files from a Folder present in project

This was helpful for me, if you use the

var dir = Directory.GetCurrentDirectory()

the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName

then print the dir value and verify the path is giving you

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Node.js fs.readdir recursive directory search

here is the complete working code. As per your requirement. you can get all files and folders recursively.

var recur = function(dir) {
            fs.readdir(dir,function(err,list){
                list.forEach(function(file){
                    var file2 = path.resolve(dir, file);
                    fs.stat(file2,function(err,stats){
                        if(stats.isDirectory()) {
                            recur(file2);
                        }
                        else {
                            console.log(file2);
                        }
                    })
                })
            });
        };
        recur(path);

in path give your directory path in which you want to search like "c:\test"

How to make the background image to fit into the whole page without repeating using plain css?

try something like

background: url(bgimage.jpg) no-repeat;
background-size: 100%;

Where does Visual Studio look for C++ header files?

There exists a newer question what is hitting the problem better asking How do include paths work in Visual Studio?

There is getting revealed the way to do it in the newer versions of VisualStudio

  • in the current project only (as the question is set here too) as well as
  • for every new project as default

The second is the what the answer of Steve Wilkinson above explains, what is, as he supposed himself, not the what Microsoft would recommend.

To say it the shortway here: do it, but do it in the User-Directory at

C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0

in the XML-file

Microsoft.Cpp.Win32.user.props

and/or

Microsoft.Cpp.x64.user.props

and not in the C:\program files - directory, where the unmodified Factory-File of Microsoft is expected to reside.

Then you do it the way as VisualStudio is doing it too and everything is regular.

For more info why to do it alike, see my answer there.

WooCommerce: Finding the products in database

Bulk add new categories to Woo:

Insert category id, name, url key

INSERT INTO wp_terms 
VALUES
  (57, 'Apples', 'fruit-apples', '0'),
  (58, 'Bananas', 'fruit-bananas', '0');

Set the term values as catergories

INSERT INTO wp_term_taxonomy 
VALUES
  (57, 57, 'product_cat', '', 17, 0),
  (58, 58, 'product_cat', '', 17, 0)

17 - is parent category, if there is one

key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id

After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

Deserialize JSON string to c# object

I believe you are looking for this:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Scanner is skipping nextLine() after using next() or nextFoo()?

As nextXXX() methods don't read newline, except nextLine(). We can skip the newline after reading any non-string value (int in this case) by using scanner.skip() as below:

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(x);
double y = sc.nextDouble();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(y);
char z = sc.next().charAt(0);
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(z);
String hello = sc.nextLine();
System.out.println(hello);
float tt = sc.nextFloat();
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
System.out.println(tt);

What is the best way to concatenate two vectors?

One more simple variant which was not yet mentioned:

copy(A.begin(),A.end(),std::back_inserter(AB));
copy(B.begin(),B.end(),std::back_inserter(AB));

And using merge algorithm:

#include <algorithm> #include <vector> #include <iterator> #include <iostream> #include <sstream> #include <string> template<template<typename, typename...> class Container, class T> std::string toString(const Container<T>& v) { std::stringstream ss; std::copy(v.begin(), v.end(), std::ostream_iterator<T>(ss, "")); return ss.str(); }; int main() { std::vector<int> A(10); std::vector<int> B(5); //zero filled std::vector<int> AB(15); std::for_each(A.begin(), A.end(), [](int& f)->void { f = rand() % 100; }); std::cout << "before merge: " << toString(A) << "\n"; std::cout << "before merge: " << toString(B) << "\n"; merge(B.begin(),B.end(), begin(A), end(A), AB.begin(), [](int&,int&)->bool {}); std::cout << "after merge: " << toString(AB) << "\n"; return 1; }

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

Specify JDK for Maven to use

I say you setup the JAVA_HOME environment variable like Pascal is saying: In Cygwin if you use bash as your shell should be:

export JAVA_HOME=/cygdrive/c/pathtothejdk

It never harms to also prepend the java bin directory path to the PATH environment variable with:

export PATH=${JAVA_HOME}/bin:${PATH}

Also add maven-enforce-plugin to make sure the right JDK is used. This is a good practice for your pom.

<build>
 <plugins>
   <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-enforcer-plugin</artifactId>
      <executions>
        <execution>
          <id>enforce-versions</id>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireJavaVersion>
                <version>1.6</version>
              </requireJavaVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Please, see Maven Enforcer plugin – Usage.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Identifying and removing null characters in UNIX

A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv to convert it to UTF-8.

Reading content from URL with Node.js

try using the on error event of the client to find the issue.

var http = require('http');

var options = {
    host: 'google.com',
    path: '/'
}
var request = http.request(options, function (res) {
    var data = '';
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();

How to sum columns in a dataTable?

 for (int i=0;i<=dtB.Columns.Count-1;i++)
 {
   array(0, i) = dtB.Compute("SUM([" & dtB.Columns(i).ColumnName & "])", "")                   
 }

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

jQuery validate: How to add a rule for regular expression validation?

Extending PeterTheNiceGuy's answer a bit:

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "Please check your input."
);

This would allow you to pass a regex object to the rule.

$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });

Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.

Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:

$("password").rules("add", {
    regex: [
        /^[a-zA-Z'.\s]{8,40}$/,
        /^.*[a-z].*$/,
        /^.*[A-Z].*$/,
        /^.*[0-9].*$/
    ],
    '!regex': /password|123/
});

But implementing those would maybe be too much.

How do you Encrypt and Decrypt a PHP String?

Historical Note: This was written at the time of PHP4. This is what we call "legacy code" now.

I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.

I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.

If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.

Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.


Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP

//Listing 3: Encrypting Data Using the mcrypt_ecb Function 

<?php 
echo("<h3> Symmetric Encryption </h3>"); 
$key_value = "KEYVALUE"; 
$plain_text = "PLAINTEXT"; 
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT); 
echo ("<p><b> Text after encryption : </b>"); 
echo ( $encrypted_text ); 
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT); 
echo ("<p><b> Text after decryption : </b>"); 
echo ( $decrypted_text ); 
?> 

A few warnings:

1) Never use reversible, or "symmetric" encryption when a one-way hash will do.

2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.

3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.

Be that as it may, have fun :)

Get path of executable

I'm not sure about Linux, but try this for Windows:

#include <windows.h>
#include <iostream>

using namespace std ;

int main()
{
     char ownPth[MAX_PATH]; 

     // When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
     HMODULE hModule = GetModuleHandle(NULL);
     if (hModule != NULL)
     {
         // Use GetModuleFileName() with module handle to get the path
         GetModuleFileName(hModule, ownPth, (sizeof(ownPth))); 
         cout << ownPth << endl ;
         system("PAUSE");
         return 0;
     }
     else
     {
         cout << "Module handle is NULL" << endl ;
         system("PAUSE");
         return 0;
     }
}

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

Can gcc output C code after preprocessing?

Suppose we have a file as Message.cpp or a .c file

Steps 1: Preprocessing (Argument -E )

g++ -E .\Message.cpp > P1

P1 file generated has expanded macros and header file contents and comments are stripped off.

Step 2: Translate Preprocessed file to assembly (Argument -S). This task is done by compiler

g++ -S .\Message.cpp

An assembler (ASM) is generated (Message.s). It has all the assembly code.

Step 3: Translate assembly code to Object code. Note: Message.s was generated in Step2. g++ -c .\Message.s

An Object file with the name Message.o is generated. It is the binary form.

Step 4: Linking the object file. This task is done by linker

g++ .\Message.o -o MessageApp

An exe file MessageApp.exe is generated here.

#include <iostream>
using namespace std;

 //This a sample program
  int main()
{
cout << "Hello" << endl;
 cout << PQR(P,K) ;
getchar();
return 0;
}

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Installing SciPy and NumPy using pip

you need the libblas and liblapack dev packages if you are using Ubuntu.

aptitude install libblas-dev liblapack-dev
pip install scipy

Download file and automatically save it to folder

Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:

    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        e.Cancel = true;
        WebClient client = new WebClient();

        client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);

        client.DownloadDataAsync(e.Url);
    }

    void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        string filepath = textBox1.Text;
        File.WriteAllBytes(filepath, e.Result);
        MessageBox.Show("File downloaded");
    }

How to remove specific elements in a numpy array

Use numpy.delete() - returns a new array with sub-arrays along an axis deleted

numpy.delete(a, index)

For your specific question:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]

new_a = np.delete(a, index)

print(new_a) #Prints `[1, 2, 5, 6, 8, 9]`

Note that numpy.delete() returns a new array since array scalars are immutable, similar to strings in Python, so each time a change is made to it, a new object is created. I.e., to quote the delete() docs:

"A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place..."

If the code I post has output, it is the result of running the code.

SoapFault exception: Could not connect to host

With me, this problem in base Address in app.config of WCF service: When I've used:

<baseAddresses><add baseAddress="http://127.0.0.1:9022/Service/GatewayService"/> </baseAddresses>

it's ok if use .net to connect with public ip or domain.

But when use PHP's SoapClient to connect to "http://[online ip]:9022/Service/GatewayService", it's throw exception "Coulod not connect to host"

I've changed baseAddress to [online ip]:9022 and everything's ok.

Accessing Google Account Id /username via Android

Used these lines:

AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");

the length of array accounts is always 0.

Set language for syntax highlighting in Visual Studio Code

Note that for "Untitled" editor ("Untitled-1", "Untitled-2"), you now can set the language in the settings.

The previous setting was:

"files.associations": {
        "untitled-*": "javascript"
 }

This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-"

See "Untitled editor improvements"

Regarding the associated language for those "Untitled" editors:

By default, untitled files do not have a specific language mode configured.

VS Code has a setting, files.defaultLanguage, to configure a default language for untitled files.

With this release, the setting can take a new value {activeEditorLanguage} that will dynamically use the language mode of the currently active editor instead of a fixed default.

In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/untitled-copy2.gif

And see workbench.editor.untitled.labelFormat in VSCode 1.43.

Android ADB commands to get the device properties

For Power-Shell

./adb shell getprop | Select-String -Pattern '(model)|(version.sdk)|(manufacturer)|(platform)|(serialno)|(product.name)|(brand)'

For linux(burrowing asnwer from @0x8BADF00D)

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

For single string find in power shell

./adb shell getprop | Select-String -Pattern 'model'

or

./adb shell getprop | Select-String -Pattern '(model)'

For multiple

./adb shell getprop | Select-String -Pattern '(a|b|c|d)'

How to secure database passwords in PHP?

Previously we stored DB user/pass in a configuration file, but have since hit paranoid mode -- adopting a policy of Defence in Depth.

If your application is compromised, the user will have read access to your configuration file and so there is potential for a cracker to read this information. Configuration files can also get caught up in version control, or copied around servers.

We have switched to storing user/pass in environment variables set in the Apache VirtualHost. This configuration is only readable by root -- hopefully your Apache user is not running as root.

The con with this is that now the password is in a Global PHP variable.

To mitigate this risk we have the following precautions:

  • The password is encrypted. We extend the PDO class to include logic for decrypting the password. If someone reads the code where we establish a connection, it won't be obvious that the connection is being established with an encrypted password and not the password itself.
  • The encrypted password is moved from the global variables into a private variable The application does this immediately to reduce the window that the value is available in the global space.
  • phpinfo() is disabled. PHPInfo is an easy target to get an overview of everything, including environment variables.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

When user press F5 although new request goes to web server and get a responce for the request as well. But when the responce header is Parsed it check the required information in browser cache. If the required information in cache has not expired then that information is restored from in cache itself.

When user click on CTRL-F5 even then new request goes to web server and get a responce. But this time when the responce header is Parsed it do not check any required information in cache, and bring all updated information form server only.

Generating a random hex color code with PHP

Valid hex colors can contain 0 to 9 and A to F so if we create a string with those characters and then shuffle it, we can grab the first 6 characters to create a random hex color code. An example is below!

code

echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);

I tested this in a while loop and generated 10,000 unique colors.

code I used to generate 10,000 unique colors:

$colors = array();
while (true) {
   $color          = substr(str_shuffle('ABCDEF0123456789'), 0, 6);
   $colors[$color] = '#' . $color;
   if ( count($colors) == 10000 ) {
      echo implode(PHP_EOL, $colors);
      break;
   }
}

Which gave me these random colors as the result.


outis pointed out that my first example couldn't generate hexadecimals such as '4488CC' so I created a function which would be able to generate hexadecimals like that.

code

function randomHex() {
   $chars = 'ABCDEF0123456789';
   $color = '#';
   for ( $i = 0; $i < 6; $i++ ) {
      $color .= $chars[rand(0, strlen($chars) - 1)];
   }
   return $color;
}

echo randomHex();

The second example would be better to use because it can return a lot more different results than the first example, but if you aren't going to generate a lot of color codes then the first example would work just fine.

How do I rename a repository on GitHub?

  • Navigate to your repository path.
  • Click on setting button which is there in right panne.
  • Replace old repository name to new name.
  • Click on Rename button

How to count the number of files in a directory using Python

import os

def count_files(in_directory):
    joiner= (in_directory + os.path.sep).__add__
    return sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
    )

>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049

MySQL: Fastest way to count number of rows

If you need to get the count of the entire result set you can take following approach:

SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();

This isn't normally faster than using COUNT albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.

Doing these two queries is good for pagination for getting totals but not particularly for using WHERE clauses.

Is a URL allowed to contain a space?

Yes, the space is usually encoded to "%20" though. Any parameters that pass to a URL should be encoded, simply for safety reasons.

How to check if a windows form is already open, and close it if it is?

try this

 bool IsOpen = false;
    foreach (Form f in Application.OpenForms)
    {
        if (f.Text == "Form2")
        {
            IsOpen = true;
            f.Focus();
            break;
        }
    }

    if (IsOpen == false)
    {
        Form2 f2 = new Form2();
        f2.MdiParent = this;
        f2.Show();
    }

Change Volley timeout duration

To handle Android Volley Timeout you need to use RetryPolicy

RetryPolicy

  • Volley provides an easy way to implement your RetryPolicy for your requests.
  • Volley sets default Socket & ConnectionTImeout to 5 secs for all requests.

RetryPolicy is an interface where you need to implement your logic of how you want to retry a particular request when a timeout happens.

It deals with these three parameters

  • Timeout - Specifies Socket Timeout in millis per every retry attempt.
  • Number Of Retries - Number of times retry is attempted.
  • Back Off Multiplier - A multiplier which is used to determine exponential time set to socket for every retry attempt.

For ex. If RetryPolicy is created with these values

Timeout - 3000 ms, Num of Retry Attempts - 2, Back Off Multiplier - 2.0

Retry Attempt 1:

  • time = time + (time * Back Off Multiplier);
  • time = 3000 + 6000 = 9000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 9 Secs

Retry Attempt 2:

  • time = time + (time * Back Off Multiplier);
  • time = 9000 + 18000 = 27000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 27 Secs

So at the end of Retry Attempt 2 if still Socket Timeout happens Volley would throw a TimeoutError in your UI Error response handler.

//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. 
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

How to apply !important using .css()?

Most of these answers are now outdated, IE7 support is not an issue.

The best way to do this that supports IE11+ and all modern browsers is:

const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');

Or if you want, you can create a small jQuery plugin that does this. This plugin closely matches jQuery's own css() method in the parameters it supports:

/**
 * Sets a CSS style on the selected element(s) with !important priority.
 * This supports camelCased CSS style property names and calling with an object 
 * like the jQuery `css()` method. 
 * Unlike jQuery's css() this does NOT work as a getter.
 * 
 * @param {string|Object<string, string>} name
 * @param {string|undefined} value
 */   
jQuery.fn.cssImportant = function(name, value) {
  const $this = this;
  const applyStyles = (n, v) => {
    // Convert style name from camelCase to dashed-case.
    const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
      return m1 + "-" + upper.toLowerCase() + m2;
    }); 
    // Loop over each element in the selector and set the styles.
    $this.each(function(){
      this.style.setProperty(dashedName, v, 'important');
    });
  };
  // If called with the first parameter that is an object,
  // Loop over the entries in the object and apply those styles. 
  if(jQuery.isPlainObject(name)){
    for(const [n, v] of Object.entries(name)){
       applyStyles(n, v);
    }
  } else {
    // Otherwise called with style name and value.
    applyStyles(name, value);
  }
  // This is required for making jQuery plugin calls chainable.
  return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Example jsfiddle here.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to copy a collection from one database to another in MongoDB

I would abuse the connect function in mongo cli mongo doc. so that means you can start one or more connection. if you want to copy customer collection from test to test2 in same server. first you start mongo shell

use test
var db2 = connect('localhost:27017/test2')

do a normal find and copy the first 20 record to test2.

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

or filter by some criteria

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

just change the localhost to IP or hostname to connect to remote server. I use this to copy test data to a test database for testing.

exception in initializer error in java when using Netbeans

Make sure the project does not have any errors. Delete the project from workspace(make the workspace a different directory from the git folder) and import again.

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

Hi you can do it this way

    temp = sp.coo_matrix((data, (row, col)), shape=(3, 59))
    temp1 = temp.tocsr()

    #Cosine similarity
    row_sums = ((temp1.multiply(temp1)).sum(axis=1))
    rows_sums_sqrt = np.array(np.sqrt(row_sums))[:,0]
    row_indices, col_indices = temp1.nonzero()
    temp1.data /= rows_sums_sqrt[row_indices]
    temp2 = temp1.transpose()
    temp3 = temp1*temp2

How to show loading spinner in jQuery?

I ended up with two changes to the original reply.

  1. As of jQuery 1.8, ajaxStart and ajaxStop should only be attached to document. This makes it harder to filter only a some of the ajax requests. Soo...
  2. Switching to ajaxSend and ajaxComplete makes it possible to interspect the current ajax request before showing the spinner.

This is the code after these changes:

$(document)
    .hide()  // hide it initially
    .ajaxSend(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").show();
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").hide();
    })

JVM property -Dfile.encoding=UTF8 or UTF-8?

If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8), if you don't set it on the command-line with -Dfile.encoding, the JDK will default file.encoding and the default Charset like this:

System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

... yields:

file.encoding: UTF-8
defaultCharset: UTF-8

... suggesting the default is UTF-8 on such a platform.

Additionally, if java.nio.charset.Charset.defaultCharset() finds file.encoding not-set, it looks for java.nio.charset.Charset.forName("UTF-8"), suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.

If you run the same program on the same platform with java -Dfile.encoding=UTF8, without the hypen, it yields:

file.encoding: UTF8
defaultCharset: UTF-8

... noting that the default charset has been canonicalized from UTF8 to UTF-8.

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

PivotTable's Report Filter using "greater than"

Use a value filter. Click the dropdown arrow next to your Row Labels and you'll see a choice between Sort A to Z, Label Filters, and Value Filters. Selecting a Greater Than value filter will let you choose which column to use to filter out rows, even if that column has no dropdown arrow itself.

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Disable autocomplete via CSS

CSS does not have this ability. You would need to use client-side scripting.

Usage of MySQL's "IF EXISTS"

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;

Insert image after each list item

My solution to do this:

li span.show::after{
  content: url("/sites/default/files/new5.gif");
  padding-left: 5px;
}

Function to check if a string is a date

Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.

The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.

CORS with POSTMAN

Generally, Postman used for debugging and used in the development phase. But in case you want to block it even from postman try this.

    const referrer_domain = "[enter-the-domain-name-of-the-referrer]"
    //check for the referrer domain
    app.all('/*', function(req, res, next) {
      if(req.headers.referer.indexOf(referrer_domain) == -1){
        res.send('Invalid Request')
      }

      next();
    });

How do I make a batch file terminate upon encountering an error?

@echo off

set startbuild=%TIME%

C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error

copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q

echo Start Copy: %TIME%

set copystart=%TIME%

xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm

echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%

c:\link\warnings.log

:error

c:\link\errors.log

Remove Identity from a column in a table

In SQL Server you can turn on and off identity insert like this:

SET IDENTITY_INSERT table_name ON

-- run your queries here

SET IDENTITY_INSERT table_name OFF

Lost connection to MySQL server during query?

I think you can use mysql_ping() function.

This function checks for connection to the server alive or not. if it fails then you can reconnect and proceed with your query.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

How to switch activity without animation in Android?

If your context is an activity you can call overridePendingTransition:

Call immediately after one of the flavors of startActivity(Intent) or finish to specify an explicit transition animation to perform next.

So, programmatically:

this.startActivity(new Intent(v.getContext(), newactivity.class));
this.overridePendingTransition(0, 0);

SQL Server Script to create a new user

You can use:

CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO 

To create the login (See here for more details).

Then you may need to use:

CREATE USER user_name 

To create the user associated with the login for the specific database you want to grant them access too.

(See here for details)

You can also use:

GRANT permission  [ ,...n ] ON SCHEMA :: schema_name

To set up the permissions for the schema's that you assigned the users to.

(See here for details)

Two other commands you might find useful are ALTER USER and ALTER LOGIN.

Order of execution of tests in TestNG

If you don't want to use the @Test(priority = ) option in TestNG, you can make use of the javaassist library and TestNG's IMethodInterceptor to prioritize the tests according to the order by which the test methods are defined in the test class. This is based on the solution provided here.

Add this listener to your test class:

package cs.jacob.listeners;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;

public class PriorityInterceptor implements IMethodInterceptor {
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {

    Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() {
        private int getLineNo(IMethodInstance mi) {
        int result = 0;

        String methodName = mi.getMethod().getConstructorOrMethod().getMethod().getName();
        String className  = mi.getMethod().getConstructorOrMethod().getDeclaringClass().getCanonicalName();
        ClassPool pool    = ClassPool.getDefault();

        try {
            CtClass cc        = pool.get(className);
            CtMethod ctMethod = cc.getDeclaredMethod(methodName);
            result            = ctMethod.getMethodInfo().getLineNumber(0);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        return result;
        }

        public int compare(IMethodInstance m1, IMethodInstance m2) {
        return getLineNo(m1) - getLineNo(m2);
        }
    };

    IMethodInstance[] array = methods.toArray(new IMethodInstance[methods.size()]);
    Arrays.sort(array, comparator);
    return Arrays.asList(array);
    }
}

This basically finds out the line numbers of the methods and sorts them by ascending order of their line number, i.e. the order by which they are defined in the class.

How do I write a compareTo method which compares objects?

if (s.compareTo(t) > 0) will compare string s to string t and return the int value you want.

    public int Compare(Object obj) // creating a method to compare {   
        Student s = (Student) obj; //creating a student object

        // compare last names
        return  this.lastName.compareTo(s.getLastName());    
    }

Now just test for a positive negative return from the method as you would have normally.

Cheers

How to remove blank lines from a Unix file

awk 'NF' filename

awk 'NF > 0' filename

sed -i '/^$/d' filename

awk '!/^$/' filename

awk '/./' filename

The NF also removes lines containing only blanks or tabs, the regex /^$/ does not.

adding classpath in linux

I don't like setting CLASSPATH. CLASSPATH is a global variable and as such it is evil:

  • If you modify it in one script, suddenly some java programs will stop working.
  • If you put there the libraries for all the things which you run, and it gets cluttered.
  • You get conflicts if two different applications use different versions of the same library.
  • There is no performance gain as libraries in the CLASSPATH are not shared - just their name is shared.
  • If you put the dot (.) or any other relative path in the CLASSPATH that means a different thing in each place - that will cause confusion, for sure.

Therefore the preferred way is to set the classpath per each run of the jvm, for example:

java -Xmx500m -cp ".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar"    "folder.subfolder../dit1/some.xml

If it gets long the standard procedure is to wrap it in a bash or batch script to save typing.

Defining private module functions in python

For methods: (I am not sure if this exactly what you want)

print_thrice.py

def private(method):
    def methodist(string):
        if __name__ == "__main__":
            method(string)
    return methodist
    
@private
def private_print3(string):
    print(string * 3)

private_print3("Hello ") # output: Hello Hello Hello

other_file.py

from print_thrice import private_print3
private_print3("Hello From Another File? ") # no output

This is probably not a perfect solution, as you can still "see" and/or "call" the method. Regardless, it doesn't execute.

How to reset the state of a Redux store?

My take to keep Redux from referencing to the same variable of the initial state:

// write the default state as a function
const defaultOptionsState = () => ({
  option1: '',
  option2: 42,
});

const initialState = {
  options: defaultOptionsState() // invoke it in your initial state
};

export default (state = initialState, action) => {

  switch (action.type) {

    case RESET_OPTIONS:
    return {
      ...state,
      options: defaultOptionsState() // invoke the default function to reset this part of the state
    };

    default:
    return state;
  }
};

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

The main reason it is useful in industry is the plug-ins built on top of the core functionality. Almost all active Matlab development for the last few years has focused on these.

Unfortunately, you won't have much opportunity to use these in an academic environment.

HTTP GET Request in Node.js Express

Try using the simple http.get(options, callback) function in node.js:

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.

How do I get the value of a textbox using jQuery?

Possible Duplicate:

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

 var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

 var txt=$('input:text[name=DrugDurationLength]').val();

How to split a string by spaces in a Windows batch file?

I ended up with the following:

set input=AAA BBB CCC DDD EEE FFF
set nth=4
for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%a
echo %nthstring%

With this you can parameterize the input and index. Make sure to put this code in a bat file.

How to import JSON File into a TypeScript file?

Thanks for the input guys, I was able to find the fix, I added and defined the json on top of the app.component.ts file:

var json = require('./[yourFileNameHere].json');

This ultimately produced the markers and is a simple line of code.

jQuery UI Accordion Expand/Collapse All

I second bigvax comment earlier but you need to make sure that you add

        jQuery("#jQueryUIAccordion").({ active: false,
                              collapsible: true });

otherwise you wont be able to open the first accordion after collapsing them.

    $('.close').click(function () {
    $('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
    $('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
    $('.ui-accordion-content').removeClass('ui-accordion-content-active').attr({'aria-expanded':'false','aria-hidden':'true'}).hide();
   }

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Converting any object to a byte array in java

To convert the object to a byte array use the concept of Serialization and De-serialization.

The complete conversion from object to byte array explained in is tutorial.

http://javapapers.com/core-java/java-serialization/

Q. How can we convert object into byte array?

Q. How can we serialize a object?

Q. How can we De-serialize a object?

Q. What is the need of serialization and de-serialization?

Remove non-numeric characters (except periods and commas) from a string

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

How to remove duplicate values from a multi-dimensional array in PHP

Another way. Will preserve keys as well.

function array_unique_multidimensional($input)
{
    $serialized = array_map('serialize', $input);
    $unique = array_unique($serialized);
    return array_intersect_key($input, $unique);
}

How can I get a precise time, for example in milliseconds in Objective-C?

For those we need the Swift version of the answer of @Jeff Thompson:

// Get a current time for where you want to start measuring from
var date = NSDate()

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
var timePassed_ms: Double = date.timeIntervalSinceNow * -1000.0

I hope this help you.

good example of Javadoc

How about the JDK source code?

Floating Point Exception C++ Why and what is it?

Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

JavaScript Array splice vs slice

Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.

Using cURL with a username and password?

You can also just send the user name by writing:

curl -u USERNAME http://server.example

Curl will then ask you for the password, and the password will not be visible on the screen (or if you need to copy/paste the command).

intellij idea - Error: java: invalid source release 1.9

I also had the same problem in IntellijIdea, after selecting the project, then File > ProjectStructure > ProjectSettings > Modules -> sources the option was showing - the Language Level set at 9:

So, I Just change it to 8. Still my issue didn't got resolve.

The main issue was with pom.xml. I reimported the pom.xml file and my issue got resolved.

So, whenever you changed the pom.xml file, IDEA needs to update the project structure. For example if you've added there some more dependencies, IDEA needs to add them as project libraries.

In "Settings > Build, Execution, Deployment > Build Tools > Maven > Importing" you can choose "Import Maven projects automatically". This will automatically invoke "Reimport" action when the pom.xml is changed.

enter image description here

Viewing full output of PS command

If you grep the command that you are looking for with a pipe from ps aux, it will wrap the text automatically. I used a lot of the other answers on here, but sometimes if you are looking for something specific, it is nice to just use grep and you know that it will wrap lines.

For instance ps aux | grep ffmpeg .

checking memory_limit in PHP

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
    }
}

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

A much more simple solution (thanks to http://daniel.fone.net.nz/blog/2014/12/01/fixing-connection-errors-after-upgrading-postgres/) . I had upgraded to postgres 9.4. In my case, all I needed to do (after a day of googling and not succeeding)

gem uninstall pg
gem uninstall activerecord-postgresql-adapter
bundle install

Restart webrick, and done!

git stash -> merge stashed change with current changes

tl;dr

Run git add first.


I just discovered that if your uncommitted changes are added to the index (i.e. "staged", using git add ...), then git stash apply (and, presumably, git stash pop) will actually do a proper merge. If there are no conflicts, you're golden. If not, resolve them as usual with git mergetool, or manually with an editor.

To be clear, this is the process I'm talking about:

mkdir test-repo && cd test-repo && git init
echo test > test.txt
git add test.txt && git commit -m "Initial version"

# here's the interesting part:

# make a local change and stash it:
echo test2 > test.txt
git stash

# make a different local change:
echo test3 > test.txt

# try to apply the previous changes:
git stash apply
# git complains "Cannot apply to a dirty working tree, please stage your changes"

# add "test3" changes to the index, then re-try the stash:
git add test.txt
git stash apply
# git says: "Auto-merging test.txt"
# git says: "CONFLICT (content): Merge conflict in test.txt"

... which is probably what you're looking for.

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

How to implement a material design circular progress bar in android

With the Material Components library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
      android:indeterminate="true"          
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:indicatorColor="@array/progress_colors"
      app:indicatorSize="xxdp"
      app:showAnimationBehavior="inward"/>

where array/progress_colors is an array with the colors:

  <integer-array name="progress_colors">
    <item>@color/yellow_500</item>
    <item>@color/blue_700</item>
    <item>@color/red_500</item>
  </integer-array>

enter image description here

Note: it requires at least the version 1.3.0

How to calculate distance between two locations using their longitude and latitude value

There is an android.location.Location.distanceBetween() method which does this quite well.

Android Developer Docs: Location

How to create an Observable from static data similar to http one in Angular?

This way you can create Observable from data, in my case I need to maintain shopping cart:

service.ts

export class OrderService {
    cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    cartItems$ = this.cartItems.asObservable();

    // I need to maintain cart, so add items in cart

    addCartData(data) {
        const currentValue = this.cartItems.value; // get current items in cart
        const updatedValue = [...currentValue, data]; // push new item in cart

        if(updatedValue.length) {
          this.cartItems.next(updatedValue); // notify to all subscribers
        }
      }
}

Component.ts

export class CartViewComponent implements OnInit {
    cartProductList: any = [];
    constructor(
        private order: OrderService
    ) { }

    ngOnInit() {
        this.order.cartItems$.subscribe(items => {
            this.cartProductList = items;
        });
    }
}

Show two digits after decimal point in c++

Using header file stdio.h you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().

It simply printf specific digits after decimal point.

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
   double total=100;
   printf("%.2lf",total);//this prints 100.00 like as C
}

Sequelize.js delete query?

This example shows how to you promises instead of callback.

Model.destroy({
   where: {
      id: 123 //this will be your id that you want to delete
   }
}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted
  if(rowDeleted === 1){
     console.log('Deleted successfully');
   }
}, function(err){
    console.log(err); 
});

Check this link out for more info http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

Cannot open include file 'afxres.h' in VC2010 Express

managed to fix this by copying the below folder from another Visual Studio setup (non-express)

from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc

to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc

How do I erase an element from std::vector<> by index?

I suggest to read this since I believe that is what are you looking for.https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

If you use for example

 vec.erase(vec.begin() + 1, vec.begin() + 3);

you will erase n -th element of vector but when you erase second element, all other elements of vector will be shifted and vector sized will be -1. This can be problem if you loop through vector since vector size() is decreasing. If you have problem like this provided link suggested to use existing algorithm in standard C++ library. and "remove" or "remove_if".

Hope that this helped

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

PHP-FPM doesn't write to error log

There is a bug https://bugs.php.net/bug.php?id=61045 in php-fpm from v5.3.9 and till now (5.3.14 and 5.4.4). Developer promised fix will go live in next release. If you don't want to wait - use patch on that page and re-build or rollback to 5.3.8.

Bootstrap Modal sitting behind backdrop

Just remove the backdrop, insert this code in your css file

.modal-backdrop {
      /* bug fix - no overlay */    
      display: none;    
}

Refused to apply inline style because it violates the following Content Security Policy directive

As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none) in your HTML. Put that style in your CSS file instead.

To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:

"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."

Is it possible that one domain name has multiple corresponding IP addresses?

This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.

Show constraints on tables command

Analogous to @Resh32, but without the need to use the USE statement:

SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name" 
      AND TABLE_NAME = "table_name" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

Useful, e.g. using the ORM.

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

How to increase the gap between text and underlining in CSS

An alternative for multiline texts or links, you can wrap your texts in a span inside a block element.

<a href="#">
    <span>insert multiline texts here</span>
</a> 

then you can just add border-bottom and padding on the <span>.

a {
  width: 300px;
  display: block;
}

span {
  padding-bottom: 10px;
  border-bottom: 1px solid #0099d3;
  line-height: 48px;
}

You may refer to this fiddle. https://jsfiddle.net/Aishaterr/vrpb2ey7/2/

how to set active class to nav menu from twitter bootstrap

You can use this JavaScript\jQuery code:

// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');

It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.

A simple solution that works!


Original source:

Bootstrap add active class to li

Check/Uncheck checkbox with JavaScript

I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:

// check
$('#checkbox_id').click()

Style input type file?

Use the clip property along with opacity, z-index, absolute positioning, and some browser filters to place the file input over the desired button:

http://en.wikibooks.org/wiki/Cascading_Style_Sheets/Clipping

How to list running screen sessions?

To list all of the screen sessions for a user, run the following command as that user:

screen -ls

To see all screen sessions on a specific machine you can do:

ls -laR /var/run/screen/

I get this on my machine:

gentle ~ # ls -laR /var/run/screen/

/var/run/screen/:
total 1
drwxrwxr-x  4 root utmp   96 Mar  1  2005 .
drwxr-xr-x 10 root root  840 Feb  1 03:10 ..
drwx------  2 josh users  88 Jan 13 11:33 S-josh
drwx------  2 root root   48 Feb 11 10:50 S-root

/var/run/screen/S-josh:
total 0
drwx------ 2 josh users 88 Jan 13 11:33 .
drwxrwxr-x 4 root utmp  96 Mar  1  2005 ..
prwx------ 1 josh users  0 Feb 11 10:41 12931.pts-0.gentle

/var/run/screen/S-root:
total 0
drwx------ 2 root root 48 Feb 11 10:50 .
drwxrwxr-x 4 root utmp 96 Mar  1  2005 ..

This is a rather brilliantly Unixy use of Unix Sockets wrapped in filesystem permissions to handle security, state, and streams.

How to read an external local JSON file in JavaScript?

Very simple.
Rename your json file to ".js" instead ".json".

<script type="text/javascript" src="my_json.js"></script>

So follow your code normally.

<script type="text/javascript">
var obj = JSON.parse(contacts);

However, just for information, the content my json it's looks like the snip below.

contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';

Pull new updates from original GitHub repository into forked GitHub repository

If there is nothing to lose you could also just delete your fork just go to settings... go to danger zone section below and click delete repository. It will ask you to input the repository name and your password after. After that you just fork the original again.

Using import fs from 'fs'

In order to use import { readFileSync } from 'fs', you have to:

  1. Be using Node.js 10 or later
  2. Use the --experimental-modules flag (in Node.js 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

The other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.

Here's the Node.js 10 ESM documentation.

Iterating over all the keys of a map

Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for k, _ := range m { ... }

Less aggressive compilation with CSS3 calc

There is several escaping options with same result:

body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }

Callback after all asynchronous forEach callbacks are completed

It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:

// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);
});

output:

4000 started
2000 started
1: 2000
0: 4000

If we check for index === array.length - 1, callback will be called upon completion of first iteration, whilst first element is still pending!

To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);
});

PowerShell To Set Folder Permissions

Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:

$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl

Error importing Seaborn module in Python

I had the same problem and I am using iPython. pip or conda by itself did not work for me but when I use !conda it did work.

!conda install seaborn

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This works perfectly for me, not matter how the date was coded previously.

library(lubridate)
data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

How to get all properties values of a JavaScript Object (without knowing the keys)?

Apparently - as I recently learned - this is the fastest way to do it:

var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
    // do whatever in here
    var obj = objs[objKeys[i]];
}

How to check "hasRole" in Java Code with Spring Security?

This two annotation below is equal, "hasRole" will auto add prefix "ROLE_". Make sure you have the right annotation. This role is set in UserDetailsService#loadUserByUsername.

@PreAuthorize("hasAuthority('ROLE_user')")
@PreAuthorize("hasRole('user')")

then, you can get the role in java code.

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_user"))){
    System.out.println("user role2");
}

How to select specified node within Xpath node sets by index with Selenium?

This is a FAQ:

//someName[3]

means: all someName elements in the document, that are the third someName child of their parent -- there may be many such elements.

What you want is exactly the 3rd someName element:

(//someName)[3]

Explanation: the [] has a higher precedence (priority) than //. Remember always to put expressions of the type //someName in brackets when you need to specify the Nth node of their selected node-list.

Cannot find java. Please use the --jdkhome switch

I do recommend you to change the configuration of JDK used by NetBeans in netbeans.conf config file:

netbeans_jdkhome="C:\Program Files\Java\..."

How can we print line numbers to the log in java

My way it works for me

String str = "select os.name from os where os.idos="+nameid;  try {
        PreparedStatement stmt = conn.prepareStatement(str);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            a = rs.getString("os.n1ame");//<<<----Here is the ERROR          
        }
        stmt.close();
  } catch (SQLException e) {
        System.out.println("error line : " + e.getStackTrace()[2].getLineNumber());            
        return a;
  }

Change the icon of the exe file generated from Visual Studio 2010

To specify an application icon

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. In the Icon list, choose an icon (.ico) file.

To specify an application icon and add it to your project

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

The icon file is added to your project as a content file.

reference : for details see here

git: fatal: Could not read from remote repository

I was getting this problem intermittently, where most of the time it would not give the error message. The solution for me was to configure LDAP correctly after my LDAP server's IP address had changed.

The /etc/gitlab/gitlab.rb configuration for LDAP was pointing to a non-existent IP address, and so changing the host to point to the proper hostname for the LDAP server fixed the issue.

To diagnose the issue, use the gitlab-ctl tail command to help you find stacktraces. For me, I found this stacktrace:

==> /var/log/gitlab/gitlab-rails/production.log <==

Net::LDAP::Error (No route to host - connect(2) for 10.10.10.12:389):
  /opt/gitlab/embedded/lib/ruby/gems/2.3.0/gems/net-ldap-0.16.0/lib/net/ldap/connection.rb:72:in `open_connection'
...

Make the changes to the host value in /etc/gitlab/gitlab.rb

gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
   main: 
     label: 'My LDAP'
     # this was an IP address
     # host: '10.10.10.12'
     host: 'internal-ldap-server' # this is the fix
     port: 389

After changing the config file above, be sure to reconfigure gitlab

gitlab-ctl reconfigure

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

How to write a test which expects an Error to be thrown in Jasmine?

You are using:

expect(fn).toThrow(e)

But if you'll have a look on the function comment (expected is string):

294 /**
295  * Matcher that checks that the expected exception was thrown by the actual.
296  *
297  * @param {String} expected
298  */
299 jasmine.Matchers.prototype.toThrow = function(expected) {

I suppose you should probably write it like this (using lambda - anonymous function):

expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");

This is confirmed in the following example:

expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");

Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):

throw {
   name: "Error",
   message: "Parsing is not possible"
}

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Table column sizing

I can resolve this problem using the following code using Bootstrap 4:

<table class="table">
  <tbody>
    <tr class="d-flex">
      <th class="col-3" scope="row">Indicador:</th>
      <td class="col-9">this is my indicator</td>
    </tr>

    <tr class="d-flex">
      <th class="col-3" scope="row">Definición:</th>
      <td class="col-9">This is my definition</td>
    </tr>

  </tbody>
</table>

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

disable all form elements inside div

How about achieving this using only HTML attribute 'disabled'

<form>
 <fieldset disabled>
  <div class="row">
   <input type="text" placeholder="">
   <textarea></textarea>
   <select></select>
  </div>
  <div class="pull-right">
    <button class="button-primary btn-sm" type="submit">Submit</button>
  </div>
 </fieldset>
</form>

Just by putting disabled in the fieldset all the fields inside of that fieldset get disabled.

$('fieldset').attr('disabled', 'disabled');

Read .mat files in Python

There is also the MATLAB Engine for Python by MathWorks itself. If you have MATLAB, this might be worth considering (I haven't tried it myself but it has a lot more functionality than just reading MATLAB files). However, I don't know if it is allowed to distribute it to other users (it is probably not a problem if those persons have MATLAB. Otherwise, maybe NumPy is the right way to go?).

Also, if you want to do all the basics yourself, MathWorks provides (if the link changes, try to google for matfile_format.pdf or its title MAT-FILE Format) a detailed documentation on the structure of the file format. It's not as complicated as I personally thought, but obviously, this is not the easiest way to go. It also depends on how many features of the .mat-files you want to support.

I've written a "small" (about 700 lines) Python script which can read some basic .mat-files. I'm neither a Python expert nor a beginner and it took me about two days to write it (using the MathWorks documentation linked above). I've learned a lot of new stuff and it was quite fun (most of the time). As I've written the Python script at work, I'm afraid I cannot publish it... But I can give some advice here:

  • First read the documentation.
  • Use a hex editor (such as HxD) and look into a reference .mat-file you want to parse.
  • Try to figure out the meaning of each byte by saving the bytes to a .txt file and annotate each line.
  • Use classes to save each data element (such as miCOMPRESSED, miMATRIX, mxDOUBLE, or miINT32)
  • The .mat-files' structure is optimal for saving the data elements in a tree data structure; each node has one class and subnodes

Intel's HAXM equivalent for AMD on Windows OS

You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".

Why and when to use angular.copy? (Deep Copy)

I know its already answered, still i am just trying to make it simple. So angular.copy(data) you can use in case where you want to modify/change your received object by keeping its original values unmodified/unchanged.

For example: suppose i have made api call and got my originalObj, now i want to change the values of api originalObj for some case but i want the original values too so what i can do is, i can make a copy of my api originalObj in duplicateObj and modify duplicateObj this way my originalObj values will not change. In simple words duplicateObj modification will not reflect in originalObj unlike how js obj behave.

 $scope.originalObj={
            fname:'sudarshan',
            country:'India'
        }
        $scope.duplicateObj=angular.copy($scope.originalObj);
        console.log('----------originalObj--------------');
        console.log($scope.originalObj);
        console.log('-----------duplicateObj---------------');
        console.log($scope.duplicateObj);

        $scope.duplicateObj.fname='SUD';
        $scope.duplicateObj.country='USA';
        console.log('---------After update-------')
        console.log('----------originalObj--------------');
        console.log($scope.originalObj);
        console.log('-----------duplicateObj---------------');
        console.log($scope.duplicateObj);

Result is like....

    ----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}

jQuery convert line breaks to br (nl2br equivalent)

demo: http://so.devilmaycode.it/jquery-convert-line-breaks-to-br-nl2br-equivalent

function nl2br (str, is_xhtml) {   
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

Rebase array keys after unsetting elements

Just an additive.

I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."

First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.

Here's my simple, working example:

$array = array(1,2,3,4,5);

for ($i = 0; $i < count($array); $i++) {
    if($array[$i] == 1 || $array[$i] == 2) {
        array_splice($array, $i, 1);
        $i--;
    }
}

Will output:

array(3) {
    [0]=> int(3)
    [1]=> int(4)
    [2]=> int(5)
}

This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:

$files = array(
    array(
        'name' => 'example.zip',
        'size' => '100000000',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '10726556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '110726556',
        'type' => 'application/x-zip-compressed',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example2.zip',
        'size' => '12356556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
        'deleteUrl' => 'server/php/?file=example2.zip',
        'deleteType' => 'DELETE'
    )
);

for ($i = 0; $i < count($files); $i++) {
    if ($i > 0) {
        if (is_array($files[$i-1])) {
            if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
                if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
                $i--;
                array_splice($files, $i, 1);
            }
        }
    }
}

Will output:

array(1) {
    [0]=> array(6) {
            ["name"]=> string(11) "example.zip"
            ["size"]=> string(9) "110726556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
        }
    [1]=> array(6) {
            ["name"]=> string(11) "example2.zip"
            ["size"]=> string(9) "12356556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
        }
}

As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

Javascript window.open pass values using POST

Thank you php-b-grader. I improved the code, it is not necessary to use window.open(), the target is already specified in the form.

// Create a form
var mapForm = document.createElement("form");
mapForm.target = "_blank";    
mapForm.method = "POST";
mapForm.action = "abmCatalogs.ftl";

// Create an input
var mapInput = document.createElement("input");
mapInput.type = "text";
mapInput.name = "variable";
mapInput.value = "lalalalala";

// Add the input to the form
mapForm.appendChild(mapInput);

// Add the form to dom
document.body.appendChild(mapForm);

// Just submit
mapForm.submit();

for target options --> w3schools - Target

How do I select child elements of any depth using XPath?

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

Its .net Version mismatch of the dll so try changing to from in app.config or web.config. Generally have a higher Framework than lower because when we add system's dll to the lower version built .net application so it won't work therefore just change to the higher version

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

Subset data to contain only columns whose names match a condition

You can also use starts_with and dplyr's select() like so:

df <- df %>% dplyr:: select(starts_with("ABC"))

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)
                              ^

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

Creating C formatted strings (not printing them)

I haven't done this, so I'm just going to point at the right answer.

C has provisions for functions that take unspecified numbers of operands, using the <stdarg.h> header. You can define your function as void log_out(const char *fmt, ...);, and get the va_list inside the function. Then you can allocate memory and call vsprintf() with the allocated memory, format, and va_list.

Alternately, you could use this to write a function analogous to sprintf() that would allocate memory and return the formatted string, generating it more or less as above. It would be a memory leak, but if you're just logging out it may not matter.