Programs & Examples On #Qtembedded

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

BACKUP LOG cannot be performed because there is no current database backup

I am not sure whether the database backup file, you trying to restore, is coming from the same environment as you trying to restore it onto.

Remember that destination path of .mdf and .ldf files lives with the backup file itself.

If this is not a case, that means the backup file is coming from a different environment from your current hosting one, make sure that .mdf and .ldf file path is the same (exists) as on your machine, relocate these otherwise. (Mostly a case of restoring db in Docker image)

The way how to do it: In Databases -> Restore database -> [Files] option -> (Check "Relocate all files to folder" - mostly default path is populated on your hosting environment already)

How do I Convert DateTime.now to UTC in Ruby?

The string representation of a DateTime can be parsed by the Time class.

> Time.parse(DateTime.now.to_s).utc
=> 2015-10-06 14:53:51 UTC

How to initialize weights in PyTorch?

    import torch.nn as nn        

    # a simple network
    rand_net = nn.Sequential(nn.Linear(in_features, h_size),
                             nn.BatchNorm1d(h_size),
                             nn.ReLU(),
                             nn.Linear(h_size, h_size),
                             nn.BatchNorm1d(h_size),
                             nn.ReLU(),
                             nn.Linear(h_size, 1),
                             nn.ReLU())

    # initialization function, first checks the module type,
    # then applies the desired changes to the weights
    def init_normal(m):
        if type(m) == nn.Linear:
            nn.init.uniform_(m.weight)

    # use the modules apply function to recursively apply the initialization
    rand_net.apply(init_normal)

plot.new has not been called yet

Some action, very possibly not represented in the visible code, has closed the interactive screen device. It could be done either by a "click" on a close-button. (Could also be done by an extra dev.off() when plotting to a file-graphics device. This may happen if you paste in a mult-line plotting command that has a dev,off() at the end of it but errors out at the opening of the external device but then has hte dev.off() on a separate line so it accidentally closes the interactive device).

Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it. On Windows that might be window(); on a Mac, quartz(); and on a linux box, x11(). You also may need to issue a plot.new() command. I just follow orders. When I get that error I issue plot.new() and if I don't see a plot window, I issue quartz() as well. I then start over from the beginning with a new plot(., ., ...) command and any further additions to that plot screen image.

Difference between numeric, float and decimal in SQL Server

Not a complete answer, but a useful link:

"I frequently do calculations against decimal values. In some cases casting decimal values to float ASAP, prior to any calculations, yields better accuracy. "

http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/12/20/for-better-precision-cast-decimals-before-calculations.aspx

How to convert a file into a dictionary?

Simple Option

Most methods for storing a dictionary use JSON, Pickle, or line reading. Providing you're not editing the dictionary outside of Python, this simple method should suffice for even complex dictionaries. Although Pickle will be better for larger dictionaries.

x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w'))    # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y)                   # >>> True

How to write super-fast file-streaming code in C#?

The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:

http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/

SQL query for getting data for last 3 months

I'd use datediff, and not care about format conversions:

SELECT *
FROM   mytable
WHERE  DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

How to kill all processes matching a name?

From man 1 pkill

-f     The pattern is normally only matched against the process name.
       When -f is set, the full command line is used.

Which means, for example, if we see these lines in ps aux:

apache   24268  0.0  2.6 388152 27116 ?        S    Jun13   0:10 /usr/sbin/httpd
apache   24272  0.0  2.6 387944 27104 ?        S    Jun13   0:09 /usr/sbin/httpd
apache   24319  0.0  2.6 387884 27316 ?        S    Jun15   0:04 /usr/sbin/httpd

We can kill them all using the pkill -f option:

pkill -f httpd

C++ Calling a function from another class

Here's my solution to the issue. Tried to keep it straight and simple.

#include <iostream>
using namespace std;

class Game{
public:
  void init(){
    cout << "Hi" << endl;
  }
}g;

class b : Game{  //class b uses/imports class Game
public:
  void h(){
    init(); //Use function from class Game
  }
}A;

int main()
{
  A.h();
  return 0;
}

How to check if a string contains only digits in Java

Long.parseLong(data)

and catch exception, it handles minus sign.

Although the number of digits is limited this actually creates a variable of the data which can be used, which is, I would imagine, the most common use-case.

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

how to fix groovy.lang.MissingMethodException: No signature of method:

In my case it was simply that I had a variable named the same as a function.

Example:

def cleanCache = functionReturningABoolean()

if( cleanCache ){
    echo "Clean cache option is true, do not uninstall previous features / urls"
    uninstallCmd = ""
    
    // and we call the cleanCache method
    cleanCache(userId, serverName)
}
...

and later in my code I have the function:

def cleanCache(user, server){

 //some operations to the server

}

Apparently the Groovy language does not support this (but other languages like Java does). I just renamed my function to executeCleanCache and it works perfectly (or you can also rename your variable whatever option you prefer).

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Error on line 2 at column 1: Extra content at the end of the document

You might have output (maybe error/debug output) that precedes your call to

header("Content-type: text/xml");

Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).

What's the simplest way of detecting keyboard input in a script from the terminal?

This worked for me on macOS Sierra and Python 2.7.10 and 3.6.3

import sys,tty,os,termios
def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        while True:
            b = os.read(sys.stdin.fileno(), 3).decode()
            if len(b) == 3:
                k = ord(b[2])
            else:
                k = ord(b)
            key_mapping = {
                127: 'backspace',
                10: 'return',
                32: 'space',
                9: 'tab',
                27: 'esc',
                65: 'up',
                66: 'down',
                67: 'right',
                68: 'left'
            }
            return key_mapping.get(k, chr(k))
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
    while True:
        k = getkey()
        if k == 'esc':
            quit()
        else:
            print(k)
except (KeyboardInterrupt, SystemExit):
    os.system('stty sane')
    print('stopping.')

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

Laravel 5 – Clear Cache in Shared Hosting Server

As I can see: http://itsolutionstuff.com/post/laravel-5-clear-cache-from-route-view-config-and-all-cache-data-from-applicationexample.html

is it possible to use the code below with the new clear cache commands:

//Clear Cache facade value:
Route::get('/clear-cache', function() {
    $exitCode = Artisan::call('cache:clear');
    return '<h1>Cache facade value cleared</h1>';
});

//Reoptimized class loader:
Route::get('/optimize', function() {
    $exitCode = Artisan::call('optimize');
    return '<h1>Reoptimized class loader</h1>';
});

//Route cache:
Route::get('/route-cache', function() {
    $exitCode = Artisan::call('route:cache');
    return '<h1>Routes cached</h1>';
});

//Clear Route cache:
Route::get('/route-clear', function() {
    $exitCode = Artisan::call('route:clear');
    return '<h1>Route cache cleared</h1>';
});

//Clear View cache:
Route::get('/view-clear', function() {
    $exitCode = Artisan::call('view:clear');
    return '<h1>View cache cleared</h1>';
});

//Clear Config cache:
Route::get('/config-cache', function() {
    $exitCode = Artisan::call('config:cache');
    return '<h1>Clear Config cleared</h1>';
});

It's not necessary to give the possibility to clear the caches to everyone, especially in a production enviroment, so I suggest to comment that routes and, when it's needed, to de-comment the code and run the routes.

Generating unique random numbers (integers) between 0 and 'x'

I think, this is the most human approach (with using break from while loop), I explained it's mechanism in comments.

function generateRandomUniqueNumbersArray (limit) {

    //we need to store these numbers somewhere
    const array = new Array();
    //how many times we added a valid number (for if statement later)
    let counter = 0;

    //we will be generating random numbers until we are satisfied
    while (true) {

        //create that number
        const newRandomNumber = Math.floor(Math.random() * limit);

        //if we do not have this number in our array, we will add it
        if (!array.includes(newRandomNumber)) {
            array.push(newRandomNumber);
            counter++;
        }

        //if we have enought of numbers, we do not need to generate them anymore
        if (counter >= limit) {
            break;
        }
    }

    //now hand over this stuff
    return array;
}

You can of course add different limit (your amount) to the last 'if' statement, if you need less numbers, but be sure, that it is less or equal to the limit of numbers itself - otherwise it will be infinite loop.

Laravel Fluent Query Builder Join with subquery

I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.

So the main query in @ph4r05's answer would look something like this:

$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan');
        })
    ->setBindings($subq->getBindings());

Bitwise operation and usage

I think that the second part of the question:

Also, what are bitwise operators actually used for? I'd appreciate some examples.

Has been only partially addressed. These are my two cents on that matter.

Bitwise operations in programming languages play a fundamental role when dealing with a lot of applications. Almost all low-level computing must be done using this kind of operations.

In all applications that need to send data between two nodes, such as:

  • computer networks;

  • telecommunication applications (cellular phones, satellite communications, etc).

In the lower level layer of communication, the data is usually sent in what is called frames. Frames are just strings of bytes that are sent through a physical channel. This frames usually contain the actual data plus some other fields (coded in bytes) that are part of what is called the header. The header usually contains bytes that encode some information related to the status of the communication (e.g, with flags (bits)), frame counters, correction and error detection codes, etc. To get the transmitted data in a frame, and to build the frames to send data, you will need for sure bitwise operations.

In general, when dealing with that kind of applications, an API is available so you don't have to deal with all those details. For example, all modern programming languages provide libraries for socket connections, so you don't actually need to build the TCP/IP communication frames. But think about the good people that programmed those APIs for you, they had to deal with frame construction for sure; using all kinds of bitwise operations to go back and forth from the low-level to the higher-level communication.

As a concrete example, imagine some one gives you a file that contains raw data that was captured directly by telecommunication hardware. In this case, in order to find the frames, you will need to read the raw bytes in the file and try to find some kind of synchronization words, by scanning the data bit by bit. After identifying the synchronization words, you will need to get the actual frames, and SHIFT them if necessary (and that is just the start of the story) to get the actual data that is being transmitted.

Another very different low level family of application is when you need to control hardware using some (kind of ancient) ports, such as parallel and serial ports. This ports are controlled by setting some bytes, and each bit of that bytes has a specific meaning, in terms of instructions, for that port (see for instance http://en.wikipedia.org/wiki/Parallel_port). If you want to build software that does something with that hardware you will need bitwise operations to translate the instructions you want to execute to the bytes that the port understand.

For example, if you have some physical buttons connected to the parallel port to control some other device, this is a line of code that you can find in the soft application:

read = ((read ^ 0x80) >> 4) & 0x0f; 

Hope this contributes.

ImportError: No module named 'django.core.urlresolvers'

use this one:

from django.urls import reverse

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

        </list>    
    </property>     
    </bean>




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

How to draw a filled triangle in android canvas?

private void drawArrows(Point[] point, Canvas canvas, Paint paint) {

    float [] points  = new float[8];             
    points[0] = point[0].x;      
    points[1] = point[0].y;      
    points[2] = point[1].x;      
    points[3] = point[1].y;         
    points[4] = point[2].x;      
    points[5] = point[2].y;              
    points[6] = point[0].x;      
    points[7] = point[0].y;

    canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
    Path path = new Path();
    path.moveTo(point[0].x , point[0].y);
    path.lineTo(point[1].x,point[1].y);
    path.lineTo(point[2].x,point[2].y);
    canvas.drawPath(path,paint);

}

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

Oracle Age calculation from Date of birth and Today

SQL> select trunc(months_between(sysdate,dob)/12) year,
  2         trunc(mod(months_between(sysdate,dob),12)) month,
  3         trunc(sysdate-add_months(dob,trunc(months_between(sysdate,dob)/12)*12+trunc(mod(months_between(sysdate,dob),12)))) day
  4  from (Select to_date('15122000','DDMMYYYY') dob from dual);

      YEAR      MONTH        DAY
---------- ---------- ----------
         9          5         26

SQL>

Compiling a C++ program with gcc

It worked well for me. Just one line code in cmd.

First, confirm that you have installed the gcc (for c) or g++ (for c++) compiler.

In cmd for gcc type:

gcc --version

in cmd for g++ type:

g++ --version

If it is installed then proceed.

Now, compile your .c or .cpp using cmd

for .c syntax:

gcc -o exe_filename yourfilename.c

Example:

gcc -o myfile myfile.c

Here exe_filename (myfile in example) is the name of your .exe file which you want to produce after compilation (Note: i have not put any extension here). And yourfilename.c (myfile.c in example) is the your source file which has the .c extension.

Now go to folder containing your .c file, here you will find a file with .exe extension. Just open it. Hurray..

For .cpp syntax:

g++ -o exe_filename yourfilename.cpp

After it the process is same as for .c .

How does C compute sin() and other math functions?

If you want to look at the actual GNU implementation of those functions in C, check out the latest trunk of glibc. See the GNU C Library.

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

Copy a file in a sane, safe and efficient way

For those who like boost:

boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");

// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);

// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);

Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use

using namespace boost::filesystem

if you do not like those long type names

How to cut a string after a specific character in unix

This should do the trick:

$ echo "$var" | awk -F':' '{print $NF}'
/home/some/directory/file

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

I had the same error when we imported a key into a keystore that was build using a 64bit OpenSSL Version. When we followed the same procedure to import the key into a keystore that was build using a 32 bit OpenSSL version everything went fine.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I had the same issue, and solved it by adding 'mavenCentral()' to build.gradle(Project)

allprojects {
    repositories {
        ...
        mavenCentral()
    }
}

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

PHP - print all properties of an object

<?php var_dump(obj) ?>

or

<?php print_r(obj) ?>

These are the same things you use for arrays too.

These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.

If you want to know the member methods you can use get_class_methods():

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) 
{
    echo "$method_name<br/>";
}

Related stuff:

get_object_vars()

get_class_vars()

get_class() <-- for the name of the instance

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.


Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

How to copy data to clipboard in C#

My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException is here with my code that worked correctly with all browsers:

Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join();

credits to this post here

But this works only on localhost, so don't try this on a server, as it's not going to work.

On server-side, I did it by using zeroclipboard. The only way, after a lot of research.

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.

Checking for duplicate strings in JavaScript array

Using ES6 features

function checkIfDuplicateExists(w){
    return new Set(w).size !== w.length 
}

console.log(
    checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);

console.log(
    checkIfDuplicateExists(["a", "b", "c"]))
//false

What are the most useful Intellij IDEA keyboard shortcuts?

By far my favourite all purpose shortcut is Ctrl+Shift+A

It does a search as you type through all the commands in intellij. Not only that but when you find the command you want it also displays the corresponding shortcut key next to it!

How to save password when using Subversion from the console

I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config does not help to store the password.

The password was successfully saved after removing this folder (just in case renaming):

%USERPROFILE%\AppData\Roaming\Subversion\auth

Environment:

Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.

I just assigned a variable, but echo $variable shows something else

Additional to putting the variable in quotation, one could also translate the output of the variable using tr and converting spaces to newlines.

$ echo $var | tr " " "\n"
foo
bar
baz

Although this is a little more convoluted, it does add more diversity with the output as you can substitute any character as the separator between array variables.

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

How do I use Linq to obtain a unique list of properties from a list of objects?

IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();

Reading an integer from user input

I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to

  1. validate the input
  2. display an error message if invalid input is given, and
  3. loop through until a valid input is given.

This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.

static void Main(string[] args)
    {
        int intUserInput = 0;
        bool validUserInput = false;

        while (validUserInput == false)
        {
            try
            { Console.Write("Please enter an integer value greater than or equal to 1: ");
              intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
            }  
            catch (Exception) { } //catch exception for invalid input.

            if (intUserInput >= 1) //check to see that the user entered int >= 1
              { validUserInput = true; }
            else { Console.WriteLine("Invalid input. "); }

        }//end while

        Console.WriteLine("You entered " + intUserInput);
        Console.WriteLine("Press any key to exit ");
        Console.ReadKey();
    }//end main

In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to

if ( (intUserInput >= 1) && (intUserInput <= 4) )

This would work if you needed the user to pick an option of 1, 2, 3, or 4.

Redirect all output to file in Bash

Credits to osexp2003 and j.a. …


Instead of putting:

&>> your_file.log

behind a line in:

crontab -e

I use:

#!/bin/bash
exec &>> your_file.log
…

at the beginning of a BASH script.

Advantage: You have the log definitions within your script. Good for Git etc.

How can I get the current time in C#?

DateTime.Now.ToShortTimeString().ToString()

This Will give you DateTime as 10:50PM

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

JSON date to Java date?

Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).

So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX") produces a format that can parse both "2013-03-11T01:38:18.309Z" and "2013-03-11T01:38:18.309+0000" and will give you the same result.

Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.

I actually have more trouble on the JavaScript side to deal with both formats.

What size do you use for varchar(MAX) in your parameter declaration?

You do not need to pass the size parameter, just declare Varchar already understands that it is MAX like:

cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

Phonegap Cordova installation Windows

After hours of frustration... here's what i discovered.

  1. Ignore the installation documentation and all the command line, node.js stuff (seriously you will waste hours on this.
  2. Go to github and simply download the PhoneGap master .zip
  3. In that zip are project files for window phone, etc platform... just use those templates.

I don't know how such an easy process could have worse documentation. It as if it was written by lawyers.

Replace image src location using CSS

Here is another dirty hack :)

.application-title > img {
display: none;
}

.application-title::before {
content: url(path/example.jpg);
}

Display number always with 2 decimal places in <input>

Simply use the number pipe like so :

{{ numberValue | number : '.2-2'}}

The pipe above works as follows :

  • Show at-least 1 integer digit before decimal point, set by default
  • Show not less 2 integer digits after the decimal point
  • Show not more than 2 integer digits after the decimal point

Create a HTML table where each TR is a FORM

Tables are not meant for this, why don't you use <div>'s and CSS?

How to ensure that there is a delay before a service is started in systemd?

This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

"But since you asked for a way without using Before and After, you can use:

Type=idle

which as man systemd.service explains

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

How do I use a char as the case in a switch-case?

Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).

How to have a drop down <select> field in a rails form?

You create the collection in the Contact controller -

app/controllers/contacts_controller.erb 

Adding

@providers = Provider.all.by_name

to the new, create and edit methods, using a scope for the by_name in the Provider model - app/models/provider.rb - for the ordering by name

scope by_name  order(:name)

Then in the view - app/views/contacts/_form.html.erb - you use

<%= f.collection_select :provider_id, @providers, :id, :name, include_blank: true %>

For rails forms, I also strongly recommend you look at a form builder like simple_form - https://github.com/plataformatec/simple_form - which will do all the heavy lifting.

Display PDF file inside my android application

Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app

jQuery - on change input text

Seems to me like you are updating the value of the text field in javascript. onchange event will be triggered only when you key-in data and tab out of the text field.

One workaround is to trigger the textbox change event when modifying the textbox value from the script. See below,

$("#kat").change(function(){ 
    alert("Hello");
});


$('<tab_cell>').click (function () {
   $('#kat')
      .val($(this).text()) //updating the value of the textbox 
      .change();           //trigger change event.
});

How to view AndroidManifest.xml from APK file?

There is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer: http://www.javadecompilers.com/apk

Also if you wish just to check on some params you can, by their UI

Wait .5 seconds before continuing code VB.net

I've had better results by checking the browsers readystate before continuing to the next step. This will do nothing until the browser is has a "complete" readystate

Do While WebBrowser1.ReadyState <> 4
''' put anything here. 
Loop

CSS background image URL failing to load

You are using a local path. Is that really what you want? If it is, you need to use the file:/// prefix:

file:///H:/media/css/static/img/sprites/buttons-v3-10.png

obviously, this will work only on your local computer.

Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://, https://) pages has been widely disabled due to security reasons.

How to create the branch from specific commit in different branch

You have to do:

git branch <branch_name> <commit>

(you were interchanging the branch name and commit)

Or you can do:

git checkout -b <branch_name> <commit>

If in place of you use branch name, you get a branch out of tip of the branch.

Python group by

This answer is similar to @PaulMcG's answer but doesn't require sorting the input.

For those into functional programming, groupBy can be written in one line (not including imports!), and unlike itertools.groupby it doesn't require the input to be sorted:

from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict

def groupBy(key, seq):
 return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))

(The reason for ... or grp in the lambda is that for this reduce() to work, the lambda needs to return its first argument; because list.append() always returns None the or will always return grp. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)

This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input) will return this dict:

{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
 'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
 'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}

And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:

result = {key: [pair[0] for pair in values],
          for key, values in groupBy(lambda pair: pair[1], input).items()}

What generates the "text file busy" message in Unix?

root@h1:bin[0]# mount h2:/ /x             
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat 
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#

ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok

Classes cannot be accessed from outside package

public SmartSaverCals(Context context)
{
    this.context= context;
}

add public to Your constructor.in my case problem solved

Looping through all rows in a table column, Excel-VBA

I came across the same problem but no forum could help me, after some minutes I came out with an idea:

match(ColumnHeader,Table1[#Headers],0)

This will return you the number.

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

Change Name of Import in Java, or import two classes with the same name

It's probably worth noting that Groovy has this feature:

import java.util.Calendar
import com.example.Calendar as MyCalendar

MyCalendar myCalendar = new MyCalendar()

How to upgrade docker container after its image changed

Here's what it looks like using docker-compose when building a custom Dockerfile.

  1. Build your custom Dockerfile first, appending a next version number to differentiate. Ex: docker build -t imagename:version . This will store your new version locally.
  2. Run docker-compose down
  3. Edit your docker-compose.yml file to reflect the new image name you set at step 1.
  4. Run docker-compose up -d. It will look locally for the image and use your upgraded one.

-EDIT-

My steps above are more verbose than they need to be. I've optimized my workflow by including the build: . parameter to my docker-compose file. The steps looks this now:

  1. Verify that my Dockerfile is what I want it to look like.
  2. Set the version number of my image name in my docker-compose file.
  3. If my image isn't built yet: run docker-compose build
  4. Run docker-compose up -d

I didn't realize at the time, but docker-compose is smart enough to simply update my container to the new image with the one command, instead of having to bring it down first.

Unique device identification

You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.

By the way, on Panopticlick you can see how unique this usually is.

How to write a cron that will run a script every day at midnight?

You can execute shell script in two ways,either by using cron job or by writing a shell script

Lets assume your script name is "yourscript.sh"

First check the user permission of the script. use below command to check user permission of the script

ll script.sh

If the script is in root,then use below command

sudo crontab -e

Second if the script holds the user "ubuntu", then use below command

crontab -e

Add the following line in your crontab:-

55 23 * * * /path/to/yourscript.sh

Another way of doing this is to write a script and run it in the backgroud

Here is the script where you have to put your script name(eg:- youscript.sh) which is going to run at 23:55pm everyday

#!/bin/bash while true do /home/modassir/yourscript.sh sleep 1d done

save it in a file (lets name it "every-day.sh")

sleep 1d - means it waits for one day and then it runs again.

now give the permission to your script.use below command:-

chmod +x every-day.sh

now, execute this shell script in the background by using "nohup". This will keep executing the script even after you logout from your session.

use below command to execute the script.

nohup ./every-day.sh &

Note:- to run "yourscript.sh" at 23:55pm everyday,you have to execute "every-day.sh" script at exactly 23:55pm.

MultipartException: Current request is not a multipart request

In application.properties, please add this:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false

and in your html form, you need an : enctype="multipart/form-data". For example:

<form method="POST" enctype="multipart/form-data" action="/">

Hope this help!

How to crop a CvMat in OpenCV?

I understand this question has been answered but perhaps this might be useful to someone...

If you wish to copy the data into a separate cv::Mat object you could use a function similar to this:

void ExtractROI(Mat& inImage, Mat& outImage, Rect roi){
    /* Create the image */
    outImage = Mat(roi.height, roi.width, inImage.type(), Scalar(0));

    /* Populate the image */
    for (int i = roi.y; i < (roi.y+roi.height); i++){
        uchar* inP = inImage.ptr<uchar>(i);
        uchar* outP = outImage.ptr<uchar>(i-roi.y);
        for (int j = roi.x; j < (roi.x+roi.width); j++){
            outP[j-roi.x] = inP[j];
        }
    }
}

It would be important to note that this would only function properly on single channel images.

Javascript callback when IFRAME is finished loading?

I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:

$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.

    $("#myIframeId").load(function(){
       callback($("#myIframeId").html());
       $("#myIframeId").remove();

    });

});

It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p

Hope this helps :).

Localhost : 404 not found

open D:\xampp\apache\conf\extra\httpd-vhosts.conf

ServerName localhost DocumentRoot "D:\xampp\htdocs" SetEnv APPLICATION_ENV "development"
DirectoryIndex index.php AllowOverride FileInfo Require all granted

Restart Apache server

and then refresh your given url

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

Forcing anti-aliasing using css: Is this a myth?

No, there's not really any way to control this as a web developer.

Small exceptions are that you can do some fake forcing of anti-aliasing by using Flash through sIFR, and some browsers won't anti-alias bitmap/pixel fonts (as they shouldn't, more info: Anti-Aliasing / Anti-Anti-Aliasing).

Also, as Daniel mentioned, it's ideal to be using em units for all fonts, see The Incredible Em & Elastic Layouts with CSS for more information about this.

Cycles in an Undirected Graph

A connected, undirected graph G that has no cycles is a tree! Any tree has exactly n - 1 edges, so we can simply traverse the edge list of the graph and count the edges. If we count n - 1 edges then we return “yes” but if we reach the nth edge then we return “no”. This takes O (n) time because we look at at most n edges.

But if the graph is not connected,then we would have to use DFS. We can traverse through the edges and if any unexplored edges lead to the visited vertex then it has cycle.

Setting Margin Properties in code

One would guess that (and my WPF is a little rusty right now) that Margin takes an object and cannot be directly changed.

e.g

MyControl.Margin = new Margin(10,0,0,0);

String split on new line, tab and some number of spaces

Regex's aren't really the best tool for the job here. As others have said, using a combination of str.strip() and str.split() is the way to go. Here's a one liner to do it:

>>> data = '''\n\tName: John Smith
... \n\t  Home: Anytown USA
... \n\t    Phone: 555-555-555
... \n\t  Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t  Misc: Data with spaces'''
>>> {line.strip().split(': ')[0]:line.split(': ')[1] for line in data.splitlines() if line.strip() != ''}
{'Name': 'Jane Smith', 'Other Home': 'Somewhere Else', 'Notes': 'Other data', 'Misc': 'Data with spaces', 'Phone': '555-555-555', 'Home': 'Anytown USA'}

How to create a GUID in Excel?

I am using the following function in v.2013 excel vba macro code

Public Function GetGUID() As String 
    GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36) 
End Function 

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if (target.value === "[email protected]") {
            target.value= "";
        }
    }
    </script>
<input type="text" name="email" value="[email protected]" size="30" onfocus="clearThis(this)">

Try it out here: http://jsfiddle.net/2K3Vp/

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

git clone through ssh

Git 101:

git is a decentralized version control system. You do not necessary need a server to get up and running with git. Still you might want to do that as it looks cool, right? (It's also useful if you want to work on a single project from multiple computers.)

So to get a "server" running you need to run git init --bare <your_project>.git as this will create an empty repository, which you can then import on your machines without having to muck around in config files in your .git dir.

After this you could clone the repo on your clients as it is supposed to work, but I found that some clients (namely git-gui) will fail to clone a repo that is completely empty. To work around this you need to run cd <your_project>.git && touch <some_random_file> && git add <some_random_file> && git commit && git push origin master. (Note that you might need to configure your username and email for that machine's git if you hadn't done so in the past. The actual commands to run will be in the error message you get so I'll just omit them.)

So at this point you can clone the repository to any machine simply by running git clone <user>@<server>:<relative_path><your_project>.git. (As others have pointed out you might need to prefix it with ssh:// if you use the absolute path.) This assumes that you can already log in from your client to the server. (You'll also get bonus points for setting up a config file and keys for ssh, if you intend to push a lot of stuff to the remote server.)

Some relevant links:
This pretty much tells you what you need to know.
And this is for those who know the basic workings of git but sometimes forget the exact syntax.

"The public type <<classname>> must be defined in its own file" error in Eclipse

If .java file contains top level (not nested) public class, it have same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file.

If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run).

So assuming your code is placed in StaticDemoShow.java file you have two options:

  1. If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility)

    class StaticDemo { // It can no longer public
    
        static int a = 3;
        static int b = 4;
    
        static {
            System.out.println("Voila! Static block put into action");
        }
    
        static void show() {
            System.out.println("a= " + a);
            System.out.println("b= " + b);
        }
    
    }
    
    public class StaticDemoShow { // Only one top level public class in same .java file
        public static void main() {
            StaticDemo.show();
        }
    }
    
  2. Move all public classes to their own .java files. So in your case you would need to split it into two files:

    • StaticDemo.java

      public class StaticDemo { // Note: same name as name of file
      
          static int a = 3;
          static int b = 4;
      
          static {
              System.out.println("Voila! Static block put into action");
          }
      
          static void show() {
              System.out.println("a= " + a);
              System.out.println("b= " + b);
          }
      
      }
      
    • StaticDemoShow.java

      public class StaticDemoShow { 
          public static void main() {
              StaticDemo.show();
          }
      }
      

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

Eclipse "this compilation unit is not on the build path of a java project"

I found that I was getting this error due to having my files, including my main class, outside of the .src folder.

How do I close an open port from the terminal on the Mac?

You can also use this first command to kill a process that owns a particular port:

sudo netstat -ap | grep :<port_number>

For example, say this process holds port 8000 TCP, then running the command:

sudo netstat -ap | grep :8000

will output the line corresponding to the process holding port 8000, for example:

tcp  0  0 *:8000   *:* LISTEN  4683/procHoldingPort

In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds (which you wish to close).

Then kill the process, following the above example:

kill  4683

As others mentioned here out, if that doesn't work (you can try using kill with -9 as an argument):

kill -9 4683

Again, in general, it's better to avoid sending SIGKILL (-9) if you can.

How to show all shared libraries used by executables in Linux?

On OS X by default there is no ldd, objdump or lsof. As an alternative, try otool -L:

$ otool -L `which openssl`
/usr/bin/openssl:
    /usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
    /usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)

In this example, using which openssl fills in the fully qualified path for the given executable and current user environment.

PHP prepend leading zero before single digit number, on-the-fly

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Search the file my.cnf and comment the line

skip-networking

to

#skip-networking

Restart mysql

Shell script not running, command not found

Unix has a variable called PATH that is a list of directories where to find commands.

$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/david/bin

If I type a command foo at the command line, my shell will first see if there's an executable command /usr/local/bin/foo. If there is, it will execute /usr/local/bin/foo. If not, it will see if there's an executable command /usr/bin/foo and if not there, it will look to see if /bin/foo exists, etc. until it gets to /Users/david/bin/foo.

If it can't find a command foo in any of those directories, it tell me command not found.

There are several ways I can handle this issue:

  • Use the commandbash foo since foo is a shell script.
  • Include the directory name when you eecute the command like /Users/david/foo or $PWD/foo or just plain ./foo.
  • Change your $PATH variable to add the directory that contains your commands to the PATH.

You can modify $HOME/.bash_profile or $HOME/.profile if .bash_profile doesn't exist. I did that to add in /usr/local/bin which I placed first in my path. This way, I can override the standard commands that are in the OS. For example, I have Ant 1.9.1, but the Mac came with Ant 1.8.4. I put my ant command in /usr/local/bin, so my version of antwill execute first. I also added $HOME/bin to the end of the PATH for my own commands. If I had a file like the one you want to execute, I'll place it in $HOME/bin to execute it.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:

Run the following command from the ssh terminal and follow the instruction:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

Once its installed Open the Jupyter notebook and run following command:

!pip install opencv-contrib-python

Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.

Now refresh the notebook page and check whether it's installed or not by running import cv2 in the notebook.

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

best practice to generate random token for forgot password

You can also use DEV_RANDOM, where 128 = 1/2 the generated token length. Code below generates 256 token.

$token = bin2hex(mcrypt_create_iv(128, MCRYPT_DEV_RANDOM));

Set a default font for whole iOS app?

If you're using Swift, you can create a UILabel extension:

extension UILabel {

    @objc var substituteFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
    }

}

And then where you do your appearance proxying:

UILabel.appearance().substituteFontName = applicationFont

There is equivalent Objective-C code using UI_APPEARANCE_SELECTOR on a property with the name substituteFontName.

Addition

For the case where you'd want to set bold and regular fonts separately:

extension UILabel {

    @objc var substituteFontName : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.range(of:"Medium") == nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }

    @objc var substituteFontNameBold : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.range(of:"Medium") != nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }
}

Then for your UIAppearance proxies:

UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold

Note: if you're finding that the bold substitution isn't working, it's possible the default font name doesn't contain "Medium". Switch out that string for another match as needed (thanks to Mason in the comments below) .

How to show text in combobox when no item selected?

Here's how I do it. It might not be the best method, and offers least control; however, it's simple and quick and I thought it might be a good idea to share it so that more options are available for others.

<ComboBox SelectedIndex="0">
    <ComboBoxItem Visibility="Collapsed">Please select one...</ComboBoxItem>
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
    <ComboBoxItem>4</ComboBoxItem>
</ComboBox>

The idea behind this is that the initial selection is index 0, which is collapsed, so it's not available under selection for the user once they select something else. The downside is that you have to remember that if you're checking for a selected index, remember that index 0 means there was no selection made.

How to access a dictionary key value present inside a list?

First of all don't use 'list' as variable name.

If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):

res  = {}
for line in listOfDicts:
   res.update(line)
res['d']
>>> 4

Otherwise:

getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]

Or very base:

def get_value(listOfDicts, key):
    for subVal in listOfDicts:
        if key in subVal:
            return subVal[key]

How can I kill whatever process is using port 8080 so that I can vagrant up?

I needed to run this command

sudo lsof -i :80 # checks port 8080

Then i got

COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
acwebseca 312 root   36u  IPv4 0x34ae935da20560c1      0t0  TCP 192.168.1.3:50585->104.25.53.12:http (ESTABLISHED)

show which service is using the PID

ps -ef 312

Then I got this

  UID   PID  PPID   C STIME   TTY           TIME CMD
    0   312    58   0  9:32PM ??         0:02.70 /opt/cisco/anyconnect/bin/acwebsecagent -console

To uninstall cisco web security agent run

sudo /opt/cisco/anyconnect/bin/websecurity_uninstall.sh

credits to: http://tobyaw.livejournal.com/315396.html

Cannot issue data manipulation statements with executeQuery()

For Delete query - Use @Modifying and @Transactional before the @Query like:-

@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {

    @Modifying
    @Transactional
    @Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
    void deleteCopyByTradeId(Integer id);

}

It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery() error.

Edit:

Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.

@Transactional

By default, CRUD methods on repository instances are transactional. For read operations, 
the transaction configuration readOnly flag is set to true. 
All others are configured with a plain @Transactional so that default transaction 
configuration applies.

@Modifying

Indicates a query method should be considered as modifying query as that changes the way 
it needs to be executed. This annotation is only considered if used on query methods defined 
through a Query annotation). It's not applied on custom implementation methods or queries 
derived from the method name as they already have control over the underlying data access 
APIs or specify if they are modifying by their name.

Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL 
statements.

Difference between fprintf, printf and sprintf?

In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE type contains information about the stream. Normally, you don't mess with a FILE object's contents directly, you just pass a pointer to it to the various I/O routines.

There are three standard streams: stdin is a pointer to the standard input stream, stdout is a pointer to the standard output stream, and stderr is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:

$ myprog < inputfile.dat > output.txt 2> errors.txt

In this example, stdin now points to inputfile.dat, stdout points to output.txt, and stderr points to errors.txt.

fprintf writes formatted text to the output stream you specify.

printf is equivalent to writing fprintf(stdout, ...) and writes formatted text to wherever the standard output stream is currently pointing.

sprintf writes formatted text to an array of char, as opposed to a stream.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

CSS get height of screen resolution

In order to get screen resolution you can also use . This link help you very much to resolve.

Double precision - decimal places

IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.

An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.

Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.

Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.

ASP.NET MVC View Engine Comparison

I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.

Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How to add a where clause in a MySQL Insert statement?

UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Just make sure that your Dates are compatible or can be run properly in your database manager(e.g. SQL Server Management Studio). For example, the DateTime.Now C# function is invalid in SQL server meaning your query has to include valid functions like GETDATE() for SQL Server.

This change has worked perfectly for me.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

How to make GREP select only numeric values?

grep will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Like this:

echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'

C#: New line and tab characters in strings

sb.AppendLine();

or

sb.Append( "\n" );

And

sb.Append( "\t" );

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;
    ...

    public static function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
            $error->handleError();
        }
        return $result;
    }
 ....

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }
}

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count(q.id) as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = d.id ';
        $sql .='GROUP BY d.id';
        return self::find_by_sql($sql);
    }

    ....
}

I hope this example helps you create a good structure.

C# send a simple SSH command

For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170

Google Android USB Driver and ADB

Answer 1 worked perfectly for me. I tested it on a new MID 10' tablet. Here are the lines I added in the .inf file and it installed without a problem:

;Google MID
%SingleAdbInterface%        = USB_INSTALL, USB\Vid_18d1&Pid_0003&MI_01
%CompositeAdbInterface%     = USB_INSTALL, USB\Vid_18d1&Pid_0003&Rev_0230&MI_01 

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.

What are all the common ways to read a file in Ruby?

Be wary of "slurping" files. That's when you read the entire file into memory at once.

The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.

Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.

I like to use:

IO.foreach("testfile") {|x| print "GOT ", x }

or

File.foreach('testfile') {|x| print "GOT", x }

File inherits from IO, and foreach is in IO, so you can use either.

I have some benchmarks showing the impact of trying to read big files via read vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".

SQL Server 2000: How to exit a stored procedure?

Unless you specify a severity of 20 or higher, raiserror will not stop execution. See the MSDN documentation.

The normal workaround is to include a return after every raiserror:

if @whoops = 1
    begin
    raiserror('Whoops!', 18, 1)
    return -1
    end

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

After viewing and changed the properties to DocumentFormat.OpenXml, I also had to change the Specific Version to false.

JavaScript + Unicode regexes

You can also use:

function myFunction() {
  var str = "xq234"; 
  var allowChars = "^[a-zA-ZÀ-ÿ]+$";
  var res = str.match(allowChars);
  if(!str.match(allowChars)){
    res="true";
  }
  else {
    res="false";
  }
  document.getElementById("demo").innerHTML = res;

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

How to create EditText with cross(x) button at end of it?

Just put close cross like drawableEnd in your EditText:

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

and use extension to handle click (or use OnTouchListener directly on your EditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}

extension usage:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}

Disabling SSL Certificate Validation in Spring RestTemplate

Security: disable https/TLS certificate hostname check,the following code worked in spring boot rest template

*HttpsURLConnection.setDefaultHostnameVerifier(
        //SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
        // * @deprecated (4.4) Use {@link org.apache.http.conn.ssl.NoopHostnameVerifier}
        new NoopHostnameVerifier()
);*

Pass a PHP string to a JavaScript variable (and escape newlines)

You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.

What is the symbol for whitespace in C?

The ASCII value of Space is 32. So you can compare your char to the octal value of 32 which is 40 or its hexadecimal value which is 20.

if(c == '\40') { ... }

or

if(c == '\x20') { ... }

Any number after the \ is assumed to be octal, if the character just after \ is not x, in which case it is considered to be a hexadecimal.

Reverse ip, find domain names on ip address

You can use ping -a <ip> or nbtstat -A <ip>

Initialising mock objects - MockIto

A little example for JUnit 5 Jupiter, the "RunWith" was removed you now need to use the Extensions using the "@ExtendWith" Annotation.

@ExtendWith(MockitoExtension.class)
class FooTest {

  @InjectMocks
  ClassUnderTest test = new ClassUnderTest();

  @Spy
  SomeInject bla = new SomeInject();
}

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

With Java 8 there is this API method to accomplish your requirement.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

Specify sudo password for Ansible

Just an addendum, so nobody else goes through the annoyance I recently did:

AFAIK, the best solution is one along the general lines of toast38coza's above. If it makes sense to tie your password files and your playbook together statically, then follow his template with vars_files (or include_vars). If you want to keep them separate, you can supply the vault contents on the command line like so:

ansible-playbook --ask-vault-pass -e@<PATH_TO_VAULT_FILE> <PLAYBOOK_FILE>

That's obvious in retrospect, but here are the gotchas:

  1. That bloody @ sign. If you leave it out, parsing will fail silently, and ansible-playbook will proceed as though you'd never specified the file in the first place.

  2. You must explicitly import the contents of the vault, either with a command-line --extra-vars/-e or within your YAML code. The --ask-vault-pass flag doesn't do anything by itself (besides prompt you for a value which may or may not be used later).

May you include your "@"s and save an hour.

How to check if a user is logged in (how to properly use user.is_authenticated)?

Django 1.10+

Use an attribute, not a method:

if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticated

The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.


Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs. For example, I had a view that returned JSON

return HttpResponse(json.dumps({
    "is_authenticated": request.user.is_authenticated()
}), content_type='application/json') 

that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable. The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

return JsonResponse({
    "is_authenticated": request.user.is_authenticated
})

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

MSBUILD : error MSB1008: Only one project can be specified

In vs2012 just try to create a Build definition "Test Build" using the default TFS template "DefaultTemplate....xaml" (usually a copy of it)

It will fail with the usual self-explaining-error: "MSBUILD : error MSB1008: Only one project can be specified.Switch: Activities"

Off course somewhere in the default TFS template some " are missing so msbuild will receive as parameter a non escaped directory containing spaces so will result in multiple projects(?!)

So NEVER use spaces in you TFS Build Definition names, pretty sad and simple at the same time

How to deal with certificates using Selenium?

I was able to do this on .net c# with PhantomJSDriver with selenium web driver 3.1

 [TestMethod]
    public void headless()
    {


        var driverService = PhantomJSDriverService.CreateDefaultService(@"C:\Driver\phantomjs\");
        driverService.SuppressInitialDiagnosticInformation = true;
        driverService.AddArgument("--web-security=no");
        driverService.AddArgument("--ignore-ssl-errors=yes");
        driver = new PhantomJSDriver(driverService);

        driver.Navigate().GoToUrl("XXXXXX.aspx");

        Thread.Sleep(6000);
    }

Get paragraph text inside an element

Do you use jQuery? A good option would be

text = $('p').text();

Excel VBA function to print an array to the workbook

As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:

  1. Convert your 1D array into a 2D array first, then print it on sheet (as a Range).
  2. Convert your 1D array into a string and print it in a single cell (as a String).

Here is an example depicting both options:

Sub PrintArrayIn1Cell(myArr As Variant, cell As Range)
    cell = Join(myArr, ",")
End Sub
Sub PrintArrayAsRange(myArr As Variant, cell As Range)
    cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr
End Sub
Sub TestPrintArrayIntoSheet()  '2dArrayToSheet
    Dim arr As Variant
    arr = Split("a  b  c", "  ")

    'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c):
    PrintArrayIn1Cell arr, [A1]

    'Printing in SEPARATE-CELLS: To print array-elements in separate cells:
    Dim arr2D As Variant
    arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array
    PrintArrayAsRange arr2D, Range("B1:B3")
End Sub

Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.

HTH

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

How to style a select tag's option element?

I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.

_x000D_
_x000D_
$('select.potentially_red').on('change', function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});
_x000D_
.option_red {_x000D_
    background-color: #cc0000; _x000D_
    font-weight: bold; _x000D_
    font-size: 12px; _x000D_
    color: white;_x000D_
}
_x000D_
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
    <option value="red">Red</option>_x000D_
    <option value="white">White</option>_x000D_
    <option value="blue">Blue</option>_x000D_
    <option value="green">Green</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that the js is in two parts, the each part for initializing everything on the page correctly, the .on('change', ... part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

How to make Bootstrap 4 cards the same height in card-columns?

You can either put the classes on the "row" or the "column"? Won't be visible on the cards (border) if you use it on the row. https://v4-alpha.getbootstrap.com/utilities/flexbox/#align-items

<div class="container">
    <div class="row">
          <div class="col-lg-4 d-flex align-items-stretch">

Some of the other answers here seem 'wacky'. Why would use a min-height or even worse a fixed height?

I thought this issue (equal heights) was part of the reason for progression away from floating block divs?

What key shortcuts are to comment and uncomment code?

From your screenshot it appears you have ReSharper installed.

Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.

Excel: Searching for multiple terms in a cell

In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH), using named ranges and the EVALUATE function as I found from this link.

For example, I put the following terms as text in a cell, $G$1:

"PRB", "utilization", "alignment", "spectrum"

Then, I defined a named range named search_terms for that cell as described in the link above and shown in the figure below:

Named range definition

In the Refers to: field I put the following:

=EVALUATE("{" & TDoc_List!$G$1 & "}")

The above EVALUATE expression is simple used to emulate the literal string

{"PRB", "utilization", "alignment", "spectrum"}

to be used as input to the SEARCH function: using a direct reference to the SINGLE cell $G$1 (augmented with the curly braces in that case) inside SEARCH does not work, hence the use of named ranges and EVALUATE.

The trick now consists in replacing the direct reference to $G$1 by the EVALUATE-augmented named range search_terms.

The formula

It really works, and shows once more how powerful Excel really is!

It really works!

Hope this helps.

How can I trigger an onchange event manually?

For those using jQuery there's a convenient method: http://api.jquery.com/change/

What's the regular expression that matches a square bracket?

Are you escaping it with \?

/\[/

Here's a helpful resource to get started with Regular Expressions:

Regular-Expressions.info

How do I get the object if it exists, or None if it does not exist?

I think it isn't bad idea to use get_object_or_404()

from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)

This example is equivalent to:

from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")

You can read more about get_object_or_404() in django online documentation.

IBOutlet and IBAction

The traditional way to flag a method so that it will appear in Interface Builder, and you can drag a connection to it, has been to make the method return type IBAction. However, if you make your method void, instead (IBAction is #define'd to be void), and provide an (id) argument, the method is still visible. This provides extra flexibility, al

All 3 of these are visible from Interface Builder:

-(void) someMethod1:(id) sender; 
-(IBAction) someMethod2; 
-(IBAction) someMethod3:(id) sender;

See Apple's Interface Builder User Guide for details, particularly the section entitled Xcode Integration.

How to fix missing dependency warning when using useEffect React Hook?

You can set it directly as the useEffect callback:

useEffect(fetchBusinesses, [])

It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...)


Edit 02/21/2020

Just for completeness:

1. Use function as useEffect callback (as above)

useEffect(fetchBusinesses, [])

2. Declare function inside useEffect()

useEffect(() => {
  function fetchBusinesses() {
    ...
  }
  fetchBusinesses()
}, [])

3. Memoize with useCallback()

In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(fetchBusinesses, []).

const fetchBusinesses = useCallback(() => {
  ...
}, [])
useEffect(() => {
  fetchBusinesses()
}, [fetchBusinesses])

4. Disable eslint's warning

useEffect(() => {
  fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps

How to invoke bash, run commands inside the new shell, and then give control back to user?

$ bash --init-file <(echo 'some_command')
$ bash --rcfile <(echo 'some_command')

In case you can't or don't want to use process substitution:

$ cat script
some_command
$ bash --init-file script

Another way:

$ bash -c 'some_command; exec bash'
$ sh -c 'some_command; exec sh'

sh-only way (dash, busybox):

$ ENV=script sh

jQuery event to trigger action when a div is made visible

There is a jQuery plugin available for watching change in DOM attributes,

https://github.com/darcyclarke/jQuery-Watch-Plugin

The plugin wraps All you need do is bind MutationObserver

You can then use it to watch the div using:

$("#selector").watch('css', function() {
    console.log("Visibility: " + this.style.display == 'none'?'hidden':'shown'));
    //or any random events
});

What is the difference between angular-route and angular-ui-router?

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

https://github.com/angular-ui/ui-router

Have nginx access_log and error_log log to STDOUT and STDERR of master process

When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.

In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Wrap with and make invisible. Work in Chrome, Safari && FF.

_x000D_
_x000D_
label { _x000D_
  padding: 5px;_x000D_
  background: silver;_x000D_
}_x000D_
label > input[type=file] {_x000D_
    display: none;_x000D_
}
_x000D_
<label>_x000D_
  <input type="file">_x000D_
  select file_x000D_
</label>
_x000D_
_x000D_
_x000D_

How do I cancel a build that is in progress in Visual Studio?

I was hit by an unresponsive build and absolutely nothing would allow me to either kill or cancel the build. Even trying to end the task would trigger a user input window, saying that it could not be ended while the build is still going on (quite ironic because that was precisely the intention, to leave that broken state).

The build was taken care of by MSBuild, so the one way I found is to end its task. When forcing MSBuild.exe to end, VS will wake up and finally see the build as cancelled, allowing you to work again.

Hope this helps someone in the same situation.

Android/Eclipse: how can I add an image in the res/drawable folder?

When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.

MYSQL Truncated incorrect DOUBLE value

I was getting this exception not because of AND instead of comma, in fact I was having this exception just because I was not using apostrophes in where clause.

Like my query was

update table set coulmn1='something' where column2 in (00012121);

when I changed where clause to where column2 in ('00012121'); then the query worked fine for me.

Converting Decimal to Binary Java

import java.util.*;

public class BinaryNumber 
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = scan.nextInt();
        int rem;
        int num =n; 
        String str="";
        while(num>0)
        {
            rem = num%2;
            str = rem + str;
            num=num/2;
        }
        System.out.println("the bunary number for "+n+" is : "+str);
    }
}

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

How to enable Bootstrap tooltip on disabled button?

You can wrap the disabled button and put the tooltip on the wrapper:

<div class="tooltip-wrapper" data-title="Dieser Link führt zu Google">
  <button class="btn btn-default" disabled>button disabled</button>
</div>

If the wrapper has display:inline then the tooltip doesn't seem to work. Using display:block and display:inline-block seem to work fine. It also appears to work fine with a floated wrapper.

UPDATE Here's an updated JSFiddle that works with the latest Bootstrap (3.3.6). Thanks to @JohnLehmann for suggesting pointer-events: none; for the disabled button.

http://jsfiddle.net/cSSUA/209/

How can I specify a local gem in my Gemfile?

In addition to specifying the path (as Jimmy mentioned) you can also force Bundler to use a local gem for your environment only by using the following configuration option:

$ bundle config local.GEM_NAME /path/to/local/git/repository

This is extremely helpful if you're developing two gems or a gem and a rails app side-by-side.

Note though, that this only works when you're already using git for your dependency, for example:

# In Gemfile
gem 'rack', :github => 'rack/rack', :branch => 'master'

# In your terminal
$ bundle config local.rack ~/Work/git/rack

As seen on the docs.

One liner for If string is not null or empty else

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

PHP json_decode() returns NULL with valid JSON?

Here is here I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode() to return null

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to use a keypress event in AngularJS?

you can use ng-keydown , ng-keyup , ng-press such as this .

to triger a function :

   <input type="text" ng-keypress="function()"/>

or if you have one condion such as when he press escape (27 is the key code for escape)

 <form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>

Iterate over each line in a string in PHP

I would like to propose a significantly faster (and memory efficient) alternative: strtok rather than preg_split.

$separator = "\r\n";
$line = strtok($subject, $separator);

while ($line !== false) {
    # do something with $line
    $line = strtok( $separator );
}

Testing the performance, I iterated 100 times over a test file with 17 thousand lines: preg_split took 27.7 seconds, whereas strtok took 1.4 seconds.

Note that though the $separator is defined as "\r\n", strtok will separate on either character - and as of PHP4.1.0, skip empty lines/tokens.

See the strtok manual entry: http://php.net/strtok

How to make a page redirect using JavaScript?

You can achieve this using the location object.

location.href = "http://someurl"; 

How can I read large text files in Python, line by line, without loading it into memory?

The best solution I found regarding this, and I tried it on 330 MB file.

lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
    file.seek(lineno * (line_length + 2))
    print(file.readline(), end='')

Where line_length is the number of characters in a single line. For example "abcd" has line length 4.

I have added 2 in line length to skip the '\n' character and move to the next character.

SQLite UPSERT / UPDATE OR INSERT

Option 1: Insert -> Update

If you like to avoid both changes()=0 and INSERT OR IGNORE even if you cannot afford deleting the row - You can use this logic;

First, insert (if not exists) and then update by filtering with the unique key.

Example

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);

-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players 
SET age=20 
WHERE user_name='johnny';

Regarding Triggers

Notice: I haven't tested it to see the which triggers are being called, but I assume the following:

if row does not exists

  • BEFORE INSERT
  • INSERT using INSTEAD OF
  • AFTER INSERT
  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

if row does exists

  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

Option 2: Insert or replace - keep your own ID

in this way you can have a single SQL command

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Single command to insert or update
INSERT OR REPLACE INTO players 
(id, user_name, age) 
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
        'johnny',
        20);

Edit: added option 2.

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

Cleanest way to reset forms

    //Declare the jquery param on top after import
declare var $: any;
declare var jQuery: any;

clearForm() {
    $('#contactForm')[0].reset();
}

Can I use git diff on untracked files?

I believe you can diff against files in your index and untracked files by simply supplying the path to both files.

git diff --no-index tracked_file untracked_file

Where does Anaconda Python install on Windows?

The given answers work if you're in a context where conda is in your PATH environment variable, e.g. if you set it up that way during installation, or if you're running the "Anaconda Prompt".

If that's not the case, e.g. if you're trying to locate conda for use in a script, you should be able to pick up its installation location by probing HKCU\Software\Python for available Python installations. For example:

>for /F "tokens=2,*" %a in ('reg query HKCU\Software\Python /f InstallPath /s /k /ve ^| findstr Default') do @echo %b
C:\Users\<username>\Miniconda3
C:\Users\<username>\Miniconda3

Convert negative data into positive data in SQL Server

Use the absolute value function ABS. The syntax is

ABS ( numeric_expression )

Is there a Visual Basic 6 decompiler?

I have used VB Decompiler Lite (http://www.vb-decompiler.org/) in the past, and although it does not give you the original source code, it does give you a lot of information such as method names, some variable strings, etc. With more knowledge (or with the full version) it might be possible to get even more than this.

How to concat string + i?

For versions prior to R2014a...

One easy non-loop approach would be to use genvarname to create a cell array of strings:

>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')

f = 

    'f1'    'f2'    'f3'    'f4'    'f5'

For newer versions...

The function genvarname has been deprecated, so matlab.lang.makeUniqueStrings can be used instead in the following way to get the same output:

>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')

 f =
   1×5 cell array

     'f1'    'f2'    'f3'    'f4'    'f5'

How can I one hot encode in Python?

Try this:

!pip install category_encoders
import category_encoders as ce

categorical_columns = [...the list of names of the columns you want to one-hot-encode ...]
encoder = ce.OneHotEncoder(cols=categorical_columns, use_cat_names=True)
df_train_encoded = encoder.fit_transform(df_train_small)

df_encoded.head()

The resulting dataframe df_train_encoded is the same as the original, but the categorical features are now replaced with their one-hot-encoded versions.

More information on category_encoders here.

Disable Enable Trigger SQL server for a table

As Mark mentioned, the previous statement should be ended in semi-colon. So you can use:

; DISABLE TRIGGER dbo.tr_name ON dbo.table_name

Generate random integers between 0 and 9

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

MySQL combine two columns and add into a new column

SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE

LOAD DATA INFILE Error Code : 13

Error 13 is nothing but the permission issues. Even i had the same issue and was unable to load data to mysql table and then resolved the issue myself.

Here's the solution:

Bydefault the

--local-infile is set to value 0

, inorder to use LOAD DATA LOCAL INFILE it must be enabled.

So Start mySQL like this :

mysql -u username -p --local-infile

This will make LOCAL INFILE enabled during startup and thus there wont be any issues using it !

How do you read scanf until EOF in C?

I guess best way to do this is ...

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

http://msdn.microsoft.com/en-us/library/ms186862.aspx

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

String date to xmlgregoriancalendar conversion

GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

How to get the instance id from within an ec2 instance?

Run this:

curl http://169.254.169.254/latest/meta-data/

You will be able to see different types of attributes which are provided by aws.

Use this link to view more

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

The response is a bit late - but in case anyone has the issue in the future...

From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.

Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data

JQuery - Storing ajax response into global variable

     function get(a){
            bodyContent = $.ajax({
                  url: "/rpc.php",
                  global: false,
                  type: "POST",
                  data: a,
                  dataType: "html",
                  async:false
               } 
            ).responseText;
            return bodyContent;

  }

How to send a POST request from node.js Express?

in your server side the code looks like:

var request = require('request');

app.post('/add', function(req, res){
  console.log(req.body);
  request.post(
    {
    url:'http://localhost:6001/add',
    json: {
      unit_name:req.body.unit_name,
      unit_price:req.body.unit_price
        },
    headers: {
        'Content-Type': 'application/json'
    }
    },
  function(error, response, body){
    // console.log(error);
    // console.log(response);
    console.log(body);
    res.send(body);
  });
  // res.send("body");
});

in receiving end server code looks like:

app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});

Schema is just two properties unit_name and unit_price.

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

Custom sort function in ng-repeat

The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.

e.g. Given the following assignment:

$scope.cards = {
  "card2": {
    values: {
      opt1: 9,
      opt2: 12
    }
  },
  "card1": {
    values: {
      opt1: 9,
      opt2: 11
    }
  }
};

and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.

To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.

myApp.filter('orderByValue', function () {
  // custom value function for sorting
  function myValueFunction(card) {
    return card.values.opt1 + card.values.opt2;
  }

  return function (obj) {
    var array = [];
    Object.keys(obj).forEach(function (key) {
      // inject key into each object so we can refer to it from the template
      obj[key].name = key;
      array.push(obj[key]);
    });
    // apply a custom sorting function
    array.sort(function (a, b) {
      return myValueFunction(b) - myValueFunction(a);
    });
    return array;
  };
});

We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.

<ul ng-repeat="card in cards | orderByValue">
    <li>{{card.name}} {{value(card)}}</li>
</ul>

Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/

Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332

Case statement in MySQL

Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html

Invariably, I first use one when I want the other.

Java HashMap: How to get a key and value by index?

HashMaps are not ordered, unless you use a LinkedHashMap or SortedMap. In this case, you may want a LinkedHashMap. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be

int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
    String key = e.getKey();
    ArrayList<String> val = e.getValue();
    index++;
}

There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap is a special case that keeps the order.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

Spring JPA and persistence.xml

I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.

I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.

I don't get the magic in your save() method either. How is the data saved?

In production I configure spring like this:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />

along with the reference in web.xml

For unit testing I do this:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
    p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
    p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>

How do I get logs/details of ansible-playbook module executions?

Ansible command-line help, such as ansible-playbook --help shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.