Programs & Examples On #Browser scrollbars

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

python list in sql query as parameter

For example, if you want the sql query:

select name from studens where id in (1, 5, 8)

What about:

my_list = [1, 5, 8]
cur.execute("select name from studens where id in %s" % repr(my_list).replace('[','(').replace(']',')') )

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
            enabled: true,
                  mode: 'single',
                  callbacks: {
                    label: function(tooltipItems, data) { 
                      return data.datasets[tooltipItems.datasetIndex].label+": "+tooltipItems.yLabel;
                    }
                  }
                }

Getting Index of an item in an arraylist;

I think a for-loop should be a valid solution :

    public int getIndexByname(String pName)
    {
        for(AuctionItem _item : *yourArray*)
        {
            if(_item.getName().equals(pName))
                return *yourarray*.indexOf(_item)
        }
        return -1;
    }

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.

References:

https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet

Deleting DataFrame row in Pandas based on column value

If you want to delete rows based on multiple values of the column, you could use:

df[(df.line_race != 0) & (df.line_race != 10)]

To drop all rows with values 0 and 10 for line_race.

ReflectionException: Class ClassName does not exist - Laravel

composer update 

Above command worked for me.

Whenever you make new migration in la-ravel you need to refresh classmap in composer.json file .

Is there a Wikipedia API?

JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia

http://code.google.com/p/jwpl/

Replacing blank values (white space) with NaN in pandas

I will did this:

df = df.apply(lambda x: x.str.strip()).replace('', np.nan)

or

df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)

You can strip all str, then replace empty str with np.nan.

How can I use an http proxy with node.js http.Client?

As @Renat here already mentioned, proxied HTTP traffic comes in pretty normal HTTP requests. Make the request against the proxy, passing the full URL of the destination as the path.

var http = require ('http');

http.get ({
    host: 'my.proxy.com',
    port: 8080,
    path: 'http://nodejs.org/'
}, function (response) {
    console.log (response);
});

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

How does inline Javascript (in HTML) work?

using javascript:

here input element is used

<input type="text" id="fname" onkeyup="javascript:console.log(window.event.key)">

if you want to use multiline code use curly braces after javascript:

<input type="text" id="fname" onkeyup="javascript:{ console.log(window.event.key); alert('hello'); }">

How to allow Cross domain request in apache2

put the following in the site's .htaccess file (in the /var/www/XXX):

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

instead of the .conf file.

You'll also want to use

AllowOverride All

in your .conf file for the domain so Apache looks at it.

How to test enum types?

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

How to get host name with port from a http or https request

If you use the load balancer & Nginx, config them without modify code.

Nginx:

proxy_set_header       Host $host;  
proxy_set_header  X-Real-IP  $remote_addr;  
proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;  
proxy_set_header X-Forwarded-Proto  $scheme;  

Tomcat's server.xml Engine:

<Valve className="org.apache.catalina.valves.RemoteIpValve"  
remoteIpHeader="X-Forwarded-For"  
protocolHeader="X-Forwarded-Proto"  
protocolHeaderHttpsValue="https"/> 

If only modify Nginx config file, the java code should be:

String XForwardedProto = request.getHeader("X-Forwarded-Proto");

Pandas index column title or name

The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:

df.index.names gives the names of a multi-index (as a Frozenlist).

Which ORM should I use for Node.js and MySQL?

I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

Set the space between Elements in Row Flutter

Row(
 children: <Widget>[
  Flexible(
   child: TextFormField()),
  Container(width: 20, height: 20),
  Flexible(
   child: TextFormField())
 ])

This works for me, there are 3 widgets inside row: Flexible, Container, Flexible

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

SLF4J: Class path contains multiple SLF4J bindings

1.Finding the conflicting jar

If it's not possible to identify the dependency from the warning, then you can use the following command to identify the conflicting jar

mvn dependency:tree

This will display the dependency tree for the project and dependencies who have pulled in another binding with the slf4j-log4j12 JAR.

  1. Resolution

Now that we know the offending dependency, all that we need to do is exclude the slf4j-log4j12 JAR from that dependency.

Ex - if spring-security dependency has also pulled in another binding with the slf4j-log4j12 JAR, Then we need to exclude the slf4j-log4j12 JAR from the spring-security dependency.

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
           <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
    </dependency>

Note - In some cases multiple dependencies have pulled in binding with the slf4j-log4j12 JAR and you don't need to add exclude for each and every dependency who has pulled in. You just have to do that add exclude dependency with the dependency which has been placed at first.

Ex -

<dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

</dependencies>

Append TimeStamp to a File Name

Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.

Create Directory When Writing To File In Node.js

Same answer as above, but with async await and ready to use!

const fs = require('fs/promises');
const path = require('path');

async function isExists(path) {
  try {
    await fs.access(path);
    return true;
  } catch {
    return false;
  }
};

async function writeFile(filePath, data) {
  try {
    const dirname = path.dirname(filePath);
    const exist = await isExists(dirname);
    if (!exist) {
      await fs.mkdir(dirname, {recursive: true});
    }
    
    await fs.writeFile(filePath, data, 'utf8');
  } catch (err) {
    throw new Error(err);
  }
}

Example:

(async () {
  const data = 'Hello, World!';
  await writeFile('dist/posts/hello-world.html', data);
})();

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

In my case the servlet name defined in the web.xml was not same as the sevlet name in the servlet mapping tag. I have corrected this and the WAR was deployed successfully.

How to programmatically empty browser cache?

You can now use Cache.delete()

Example:

let id = "your-cache-id";
// you can find the id by going to 
// application>storage>cache storage 
// (minus the page url at the end)
// in your chrome developer console 

caches.open(id)
.then(cache => cache.keys()
  .then(keys => {
    for (let key of keys) {
      cache.delete(key)
    }
  }));

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.

How to get all options in a drop-down list by Selenium WebDriver using C#?

 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

How do I get the localhost name in PowerShell?

Don't forget that all your old console utilities work just fine in PowerShell:

PS> hostname
KEITH1

How to retrieve a user environment variable in CMake (Windows)

Getting variables into your CMake script

You can pass a variable on the line with the cmake invocation:

FOO=1 cmake

or by exporting a variable in BASH:

export FOO=1

Then you can pick it up in a cmake script using:

$ENV{FOO}

android:layout_height 50% of the screen size

best way is use

layout_height="0dp" layout_weight="0.5"

for example

<WebView
    android:id="@+id/wvHelp"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.5" />

<TextView
    android:id="@+id/txtTEMP"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.5"
    android:text="TextView" />

WebView,TextView have 50% of the screen height

How to load URL in UIWebView in Swift?

You can load a page like this :

let url: URL = URL(string:"https://google.com")!
webView.loadRequest(URLRequest.init(url: url))

Or the one-line approach :

webView.loadRequest(URLRequest.init(url: URL(string: "https://google.com")!))

webView is your outlet var.

Kotlin Ternary Conditional Operator

You could define your own Boolean extension function that returns null when the Boolean is false to provide a structure similar to the ternary operator:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

This would make an a ? b : c expression translate to a then b ?: c, like so:

println(condition then "yes" ?: "no")

Update: But to do some more Java-like conditional switch you will need something like that

infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null

println(condition then { "yes" } ?: "no") pay attention on the lambda. its content calculation should be postponed until we make sure condition is true

This one looks clumsy, that is why there is high demanded request exist to port Java ternary operator into Kotlin

How to calculate growth with a positive and negative number?

Formula should be this one:

=(thisYear+IF(LastYear<0,ABS(LastYear),0))/ABS(LastYear)-100%

The IF value if < 0 is added to your Thisyear value to generate the real difference.

If > 0, the LastYear value is 0

Seems to work in different scenarios checked

How to set an image's width and height without stretching it?

You can use as below :

_x000D_
_x000D_
.width100 {_x000D_
  max-width: 100px;_x000D_
  height: 100px;_x000D_
  width: auto;_x000D_
  border: solid red;_x000D_
}
_x000D_
<img src="https://www.gravatar.com/avatar/dc48e9b92e4210d7a3131b3ef46eb8b1?s=512&d=identicon&r=PG" class="width100" />
_x000D_
_x000D_
_x000D_

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Using Python's os.path, how do I go up one directory?

Personally, I'd go for the function approach

def get_parent_dir(directory):
    import os
    return os.path.dirname(directory)

current_dirs_parent = get_parent_dir(os.getcwd())

Activating Anaconda Environment in VsCode

As I was not able to solve my problem by suggested ways, I will share how I fixed it.

First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs directory.

So I created a new anaconda environment using Anaconda prompt, a new folder named same as your given environment name will be created in the envs folder.

Next, I activated that environment in Anaconda prompt. Installed python with conda install python command.

Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu. Launched vscode through Anaconda navigator.

Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P keyboard shortcut. Searched and selected Python: Select Interpreter

If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\ . So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe

Next time onwards the interpreter will be automatically listed among other interpreters.

Now you might see your selected conda environment at bottom left side in vscode.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

ReCaptcha API v2 Styling

With the integration of the invisible reCAPTCHA you can do the following:

To enable the Invisible reCAPTCHA, rather than put the parameters in a div, you can add them directly to an html button.

a. data-callback=””. This works just like the checkbox captcha, but is required for invisible.

b. data-badge: This allows you to reposition the reCAPTCHA badge (i.e. logo and ‘protected by reCAPTCHA’ text) . Valid options as ‘bottomright’ (the default), ‘bottomleft’ or ‘inline’ which will put the badge directly above the button. If you make the badge inline, you can control the CSS of the badge directly.

How do I iterate and modify Java Sets?

Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.

It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet implementation of java.util.Set interface satisfies your rather special requirements.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html

cat, grep and cut - translated to python

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

How to trigger an event after using event.preventDefault()

Just don't perform e.preventDefault();, or perform it conditionally.

You certainly can't alter when the original event action occurs.

If you want to "recreate" the original UI event some time later (say, in the callback for an AJAX request) then you'll just have to fake it some other way (like in vzwick's answer)... though I'd question the usability of such an approach.

Eclipse IDE for Java - Full Dark Theme

If the purpose of a dark theme is to make your eyes comfortable, you can enable High Contrast settings of your Operating System. For example in Windows 8.1 you can turn on - off High Contrast by pressing ALT + left SHIFT + PRINT SCREEN

This will make entire OS in dark mode, not only eclipse. Below is a sample screenshot of Eclipse with High Contrast enabled

enter image description here

Kill a postgresql session/connection

There is no need to drop it. Just delete and recreate the public schema. In most cases this have exactly the same effect.

namespace :db do

desc 'Clear the database'
task :clear_db => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.tables.each do |table|
    next if table == 'schema_migrations'
    ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
  end
end

desc 'Delete all tables (but not the database)'
task :drop_schema => :environment do |t,args|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection.execute("DROP SCHEMA public CASCADE")
  ActiveRecord::Base.connection.execute("CREATE SCHEMA public")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO postgres")
  ActiveRecord::Base.connection.execute("GRANT ALL ON SCHEMA public TO public")
  ActiveRecord::Base.connection.execute("COMMENT ON SCHEMA public IS 'standard public schema'")
end

desc 'Recreate the database and seed'
task :redo_db => :environment do |t,args|
  # Executes the dependencies, but only once
  Rake::Task["db:drop_schema"].invoke
  Rake::Task["db:migrate"].invoke
  Rake::Task["db:migrate:status"].invoke 
  Rake::Task["db:structure:dump"].invoke
  Rake::Task["db:seed"].invoke
end

end

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

Best way to initialize (empty) array in PHP

Initializing a simple array :

<?php $array1=array(10,20,30,40,50); ?>

Initializing array within array :

<?php  $array2=array(6,"santosh","rahul",array("x","y","z")); ?>

Source : Sorce for the code

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

How do I make text bold in HTML?

In Html use:

  • Some <b>text</b> that I want emboldened.
  • Some <strong>text</strong> that I want emboldened.

In CSS use:

  • Some <span style="font-weight:bold">text</span> that I want emboldened.

SQL Server using wildcard within IN

I had a similar goal - and came to this solution:

select *
from jobdetails as JD
where not exists ( select code from table_of_codes as TC 
                      where JD.job_no like TC.code ) 

I'm assuming that your various codes ('0711%', '0712%', etc), including the %, are stored in a table, which I'm calling *table_of_codes*, with field code.

If the % is not stored in the table of codes, just concatenate the '%'. For example:

select *
from jobdetails as JD
where not exists ( select code from table_of_codes as TC 
                      where JD.job_no like concat(TC.code, '%') ) 

The concat() function may vary depending on the particular database, as far as I know.

I hope that it helps. I adapted it from:

http://us.generation-nt.com/answer/subquery-wildcards-help-199505721.html

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

Split Div Into 2 Columns Using CSS

Another way to do this is to add overflow:hidden; to the parent element of the floated elements.

overflow:hidden will make the element grow to fit in floated elements.

This way, it can all be done in css rather than adding another html element.

"The system cannot find the file specified" when running C++ program

This is a first step for somebody that is a beginner. Same thing happened to me:

Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp file there. You can do the same by looking the .cpp file where the .sln file for the project is stored. If there is not one, then you will get that error.

When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp file to the project.

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

I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)

applicantListToExport: function (query, callback) {
  this
   .find(query).select({'advtId': 0})
   .populate({
      path: 'influId',
      model: 'influencer',
      select: { '_id': 1,'user':1},
      populate: {
        path: 'userid',
        model: 'User'
      }
   })
 .populate('campaignId',{'campaignTitle':1})
 .exec(callback);
}

How do I convert from int to Long in Java?

Note that there is a difference between a cast to long and a cast to Long. If you cast to long (a primitive value) then it should be automatically boxed to a Long (the reference type that wraps it).

You could alternatively use new to create an instance of Long, initializing it with the int value.

Hibernate Criteria for Dates

By using this way you can get the list of selected records.

GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();

All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()) of criteria to get the records.

Change Placeholder Text using jQuery

$(document).ready(function(){ 
  $('form').find("input[type=textarea], input[type=password], textarea").each(function(ev)
  {
      if(!$(this).val()) { 
     $(this).attr("placeholder", "Type your answer here");
  }
  });
});

Copy and paste this code in your js file, this will change all placeholder text from whole site.

mysql query result into php array

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

Excluding directory when creating a .tar.gz file

Try moving the --exclude to before the include.

tar -pczf MyBackup.tar.gz --exclude "/home/user/public_html/tmp/" /home/user/public_html/ 

Rewrite all requests to index.php with nginx

Using nginx $is_args instead of ? For GET query Strings

location / { try_files $uri $uri/ /index.php$is_args$args; }

How can I get the UUID of my Android phone in an application?

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

CSS div element - how to show horizontal scroll bars only?

CSS3 has the overflow-x property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll policy and work your widths and heights not to mess them up.

How to trigger jQuery change event in code

Use That :

$(selector).trigger("change");

OR

$('#id').trigger("click");

OR

$('.class').trigger(event);

Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.

importing jar libraries into android-studio

If the code for your jar library is on GitHub then importing into Android Studio is easy with JitPack.

Your will just need to add the repository to build.gradle:

allprojects{
 repositories {
    jcenter()
    maven { url "https://jitpack.io" }
 }
}

and then the library's GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.YourUsername:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used like Maven Central. The nice thing is that you don't have to upload the jar manually. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore it works only if the repo has a build file in it (build.gradle).

There is also a guide on how to prepare an Android project.

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

PHP - Debugging Curl

Output debug info to STDERR:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify debug option
     */
    CURLOPT_VERBOSE => true,
]);

curl_exec($curlHandler);

curl_close($curlHandler);

Output debug info to file:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify debug option.
     */
    CURLOPT_VERBOSE => true,

    /**
     * Specify log file.
     * Make sure that the folder is writable.
     */
    CURLOPT_STDERR => fopen('./curl.log', 'w+'),
]);

curl_exec($curlHandler);

curl_close($curlHandler);

See https://github.com/andriichuk/php-curl-cookbook#debug-request

Excel VBA to Export Selected Sheets to PDF

this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)

' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir

Sub luxation2()
    Dim Filename As String
    Filename = "temp201"



Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"


    ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False

End Sub

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

when I run mockito test occurs WrongTypeOfReturnValue Exception

I recently encountered this issue while mocking a function in a Kotlin data class. For some unknown reason one of my test runs ended up in a frozen state. When I ran the tests again some of my tests that had previously passed started to fail with the WrongTypeOfReturnValue exception.

I ensured I was using org.mockito:mockito-inline to avoid the issues with final classes (mentioned by Arvidaa), but the problem remained. What solved it for me was to kill the process and restart Android Studio. This terminated my frozen test run and the following test runs passed without issues.

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

How to stop mongo DB in one command

in the terminal window on your mac, press control+c

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import

java.util.List;

instead of

java.awt.List;

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

Spring @PropertySource using YAML

There is no need to add like YamlPropertyLoaderFactory or YamlFileApplicationContextInitializer. You should convert your idea. just like common spring project. You know, not using Java config. Just *.xml

Follow these steps:

Just add applicationContext.xml like

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
       default-autowire="byName">

    <context:property-placeholder location="classpath*:*.yml"/>
</beans>

then add

@ImportResource({"classpath:applicationContext.xml"})

to your ApplicationMainClass.

This can help scan your application-test.yml

db:
  url: jdbc:oracle:thin:@pathToMyDb
  username: someUser
  password: fakePassword

tmux set -g mouse-mode on doesn't work

As @Graham42 said, from version 2.1 mouse options has been renamed but you can use the mouse with any version of tmux adding this to your ~/.tmux.conf:

Bash shells:

is_pre_2_1="[[ $(tmux -V | cut -d' ' -f2) < 2.1 ]] && echo true || echo false"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Sh (Bourne shell) shells:

is_pre_2_1="tmux -V | cut -d' ' -f2 | awk '{print ($0 < 2.1) ? "true" : "false"}'"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Hope this helps

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

How can I trim beginning and ending double quotes from a string?

Also with Apache StringUtils.strip():

 StringUtils.strip(null, *)          = null
 StringUtils.strip("", *)            = ""
 StringUtils.strip("abc", null)      = "abc"
 StringUtils.strip("  abc", null)    = "abc"
 StringUtils.strip("abc  ", null)    = "abc"
 StringUtils.strip(" abc ", null)    = "abc"
 StringUtils.strip("  abcyx", "xyz") = "  abc"

So,

final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more

This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).

PHP: HTML: send HTML select option attribute in POST

You will have to use JavaScript. The browser will only send the value of the selected option (so its not PHP's fault).

What your JS should do is hook into the form's submit event and create a hidden field with the value of the selected option's stud_name value. This hidden field will then get sent to the server.

That being said ... you shouldn't relay on the client to provide the correct data. You already know what stud_name should be for a given value on the server (since you are outputting it). So just apply the same logic when you are processing the form.

jQuery UI DatePicker - Change Date Format

getDate function returns a JavaScript date. Use the following code to format this date:

var dateObject = $("#datepicker").datepicker("getDate");
var dateString = $.datepicker.formatDate("dd-mm-yy", dateObject);

It uses a utility function which is built into datepicker:

$.datepicker.formatDate( format, date, settings ) - Format a date into a string value with a specified format.

The full list of format specifiers is available here.

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I had a similar situation, and the following process worked for me:

  1. In the terminal, type

    vi ~/.profile
    
  2. Then add this line in the file, and save

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
    

    where version is the one on your computer, such as 1.7.0_25

  3. Exit the editor, then type the following command make it become effective

    source ~/.profile 
    

Then type java -version to check the result

    java -version 

What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

Floating point comparison functions for C#

From Bruce Dawson's paper on comparing floats, you can also compare floats as integers. Closeness is determined by least significant bits.

public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits ) 
{
    int aInt = BitConverter.ToInt32( BitConverter.GetBytes( a ), 0 );
    if ( aInt <  0 )
        aInt = Int32.MinValue - aInt;  // Int32.MinValue = 0x80000000

    int bInt = BitConverter.ToInt32( BitConverter.GetBytes( b ), 0 );
    if ( bInt < 0 )
        bInt = Int32.MinValue - bInt;

    int intDiff = Math.Abs( aInt - bInt );
    return intDiff <= ( 1 << maxDeltaBits );
}

EDIT: BitConverter is relatively slow. If you're willing to use unsafe code, then here is a very fast version:

    public static unsafe int FloatToInt32Bits( float f )
    {
        return *( (int*)&f );
    }

    public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits )
    {
        int aInt = FloatToInt32Bits( a );
        if ( aInt < 0 )
            aInt = Int32.MinValue - aInt;

        int bInt = FloatToInt32Bits( b );
        if ( bInt < 0 )
            bInt = Int32.MinValue - bInt;

        int intDiff = Math.Abs( aInt - bInt );
        return intDiff <= ( 1 << maxDeltaBits );
    }

AngularJS: How do I manually set input to $valid in controller?

You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.

What you should do is to set the validity of the input element. Like so;

addItem.capabilities.$setValidity("youAreFat", false);

Now the input (and so the form) is invalid. You can also see which error causes invalidation.

addItem.capabilities.errors.youAreFat == true;

Query to get the names of all tables in SQL Server 2008 Database

In a single database - yes:

USE your_database
SELECT name FROM sys.tables

Getting all tables across all databases - only with a hack.... see this SO question for several approaches how to do that: How do I list all tables in all databases in SQL Server in a single result set?

500 Internal Server Error for php file not for html

Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.

Another possible cause of 500 error is syntax error in header(...) function, like this one:

header($_SERVER['SERVER_PROTOCOL'] . '200 OK');

Be aware there should be space between server protocol and status code, so it should be:

header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');

So I suggest check your http header call if you have it in your code.

Apache 13 permission denied in user's home directory

Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.

If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:

sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html

See if one of those gives you the "permission denied" error.

How to make external HTTP requests with Node.js

You can use node.js http module to do that. You could check the documentation at Node.js HTTP.

You would need to pass the query string as well to the other HTTP Server. You should have that in ServerRequest.url.

Once you have those info, you could pass in the backend HTTP Server and port in the options that you will provide in the http.request()

How to implement the factory method pattern in C++ correctly

This is my c++11 style solution. parameter 'base' is for base class of all sub-classes. creators, are std::function objects to create sub-class instances, might be a binding to your sub-class' static member function 'create(some args)'. This maybe not perfect but works for me. And it is kinda 'general' solution.

template <class base, class... params> class factory {
public:
  factory() {}
  factory(const factory &) = delete;
  factory &operator=(const factory &) = delete;

  auto create(const std::string name, params... args) {
    auto key = your_hash_func(name.c_str(), name.size());
    return std::move(create(key, args...));
  }

  auto create(key_t key, params... args) {
    std::unique_ptr<base> obj{creators_[key](args...)};
    return obj;
  }

  void register_creator(const std::string name,
                        std::function<base *(params...)> &&creator) {
    auto key = your_hash_func(name.c_str(), name.size());
    creators_[key] = std::move(creator);
  }

protected:
  std::unordered_map<key_t, std::function<base *(params...)>> creators_;
};

An example on usage.

class base {
public:
  base(int val) : val_(val) {}

  virtual ~base() { std::cout << "base destroyed\n"; }

protected:
  int val_ = 0;
};

class foo : public base {
public:
  foo(int val) : base(val) { std::cout << "foo " << val << " \n"; }

  static foo *create(int val) { return new foo(val); }

  virtual ~foo() { std::cout << "foo destroyed\n"; }
};

class bar : public base {
public:
  bar(int val) : base(val) { std::cout << "bar " << val << "\n"; }

  static bar *create(int val) { return new bar(val); }

  virtual ~bar() { std::cout << "bar destroyed\n"; }
};

int main() {
  common::factory<base, int> factory;

  auto foo_creator = std::bind(&foo::create, std::placeholders::_1);
  auto bar_creator = std::bind(&bar::create, std::placeholders::_1);

  factory.register_creator("foo", foo_creator);
  factory.register_creator("bar", bar_creator);

  {
    auto foo_obj = std::move(factory.create("foo", 80));
    foo_obj.reset();
  }

  {
    auto bar_obj = std::move(factory.create("bar", 90));
    bar_obj.reset();
  }
}

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

Renaming a branch in GitHub

On GitHub side, you can use the new (Jan. 2021) "Support for renaming an existing branch"

Follow this tutorial: https://docs.github.com/en/github/administering-a-repository/renaming-a-branch

rename branch dialog -- https://i2.wp.com/user-images.githubusercontent.com/2503052/105069955-a231fa80-5a50-11eb-982c-a114c9c44c57.png?ssl=1

See "How do I rename branch on the GitHub website?".

This is a better approach, because renaming a branch that way (on github.com) will (source):

  • Re-target any open pull requests
  • Update any draft releases based on the branch
  • Move any branch protection rules that explicitly reference the old name
  • Update the branch used to build GitHub Pages, if applicable
  • Show a notice to repository contributors, maintainers, and admins on the repository homepage with instructions to update local copies of the repository
  • Show a notice to contributors who git push to the old branch
  • Redirect web requests for the old branch name to the new branch name
  • Return a "Moved Permanently" response in API requests for the old branch name

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

TypeError: not all arguments converted during string formatting python

In addition to the other two answers, I think the indentations are also incorrect in the last two conditions. The conditions are that one name is longer than the other and they need to start with 'elif' and with no indentations. If you put it within the first condition (by giving it four indentations from the margin), it ends up being contradictory because the lengths of the names cannot be equal and different at the same time.

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

Change Image of ImageView programmatically in Android

That happens because you're setting the src of the ImageView instead of the background.

Use this instead:

qImageView.setBackgroundResource(R.drawable.thumbs_down);

Here's a thread that talks about the differences between the two methods.

How to Implement DOM Data Binding in JavaScript

It is very simple two way data binding in vanilla javascript....

<input type="text" id="inp" onkeyup="document.getElementById('name').innerHTML=document.getElementById('inp').value;">

<div id="name">

</div>

How do I extract value from Json

    JSONArray ja = new JSONArray(json);
    JSONObject ob = ja.getJSONObject(0);
    String nh = ob.getString("status");

[ { "status" : "true" } ]

where 'json' is a String and status is the key from which i will get value

Handling warning for possible multiple enumeration of IEnumerable

First off, that warning does not always mean so much. I usually disabled it after making sure it's not a performance bottle neck. It just means the IEnumerable is evaluated twice, wich is usually not a problem unless the evaluation itself takes a long time. Even if it does take a long time, in this case your only using one element the first time around.

In this scenario you could also exploit the powerful linq extension methods even more.

var firstObject = objects.First();
return DoSomeThing(firstObject).Concat(DoSomeThingElse(objects).ToList();

It is possible to only evaluate the IEnumerable once in this case with some hassle, but profile first and see if it's really a problem.

how to do "press enter to exit" in batch

@echo off
echo Press any key to exit . . .
pause>nul

Handle Button click inside a row in RecyclerView

Just put an override method named getItemId Get it by right click>generate>override methods>getItemId Put this method in the Adapter class

How to set proper codeigniter base url?

If you leave it blank the framework will try to autodetect it since version 2.0.0.

But not in 3.0.0, see here: config.php

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

How can I match on an attribute that contains a certain string?

I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:

div[@class~'atag']

Count of "Defined" Array Elements

An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

var a = [];
a[23] = 'foo';
a.length;  // 24

Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

List of Java class file format major version numbers?

These come from the class version. If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49. Or something like that.

See here in byte offset 7 for more info.

Additional info can also be found here.

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I just ran the command with sudo:

sudo pip install numpy

Bear in mind that you will be asked for the user's password. This was tested on macOS High Sierra (10.13)

How do you create a Swift Date object?

Swift has its own Date type. No need to use NSDate.

Creating a Date and Time in Swift

In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you the current date and time:

let currentDateTime = Date()

For creating other date-times, you can use one of the following methods.

Method 1

If you know the number of seconds before or after the 2001 reference date, you can use that.

let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

Method 2

Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)

Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.

Method 3

The most succinct way (but not necessarily the best) could be to use DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

The Unicode technical standards show other formats that DateFormatter supports.

Notes

See my full answer for how to display the date and time in a readable format. Also read these excellent articles:

CSS: On hover show and hide different div's at the same time?

if the other div is sibling/child, or any combination of, of the parent yes

_x000D_
_x000D_
    .showme{ _x000D_
        display: none;_x000D_
    }_x000D_
    .showhim:hover .showme{_x000D_
        display : block;_x000D_
    }_x000D_
    .showhim:hover .hideme{_x000D_
        display : none;_x000D_
    }_x000D_
    .showhim:hover ~ .hideme2{ _x000D_
        display:none;_x000D_
    }
_x000D_
    <div class="showhim">_x000D_
        HOVER ME_x000D_
        <div class="showme">hai</div> _x000D_
        <div class="hideme">bye</div>_x000D_
    </div>_x000D_
    <div class="hideme2">bye bye</div>
_x000D_
_x000D_
_x000D_

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.

Merge or combine by rownames

you can wrap -Andrie answer into a generic function

mbind<-function(...){
 Reduce( function(x,y){cbind(x,y[match(row.names(x),row.names(y)),])}, list(...) )
}

Here, you can bind multiple frames with rownames as key

How to compile C programming in Windows 7?

MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.

Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.


However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h, so most of the idealistic dedication just ends up being a waste of time.

Generic deep diff between two objects

I composed this for my own use-case (es5 environment), thought this might be useful for someone, so here it is:

function deepCompare(obj1, obj2) {
    var diffObj = Array.isArray(obj2) ? [] : {}
    Object.getOwnPropertyNames(obj2).forEach(function(prop) {
        if (typeof obj2[prop] === 'object') {
            diffObj[prop] = deepCompare(obj1[prop], obj2[prop])
            // if it's an array with only length property => empty array => delete
            // or if it's an object with no own properties => delete
            if (Array.isArray(diffObj[prop]) && Object.getOwnPropertyNames(diffObj[prop]).length === 1 || Object.getOwnPropertyNames(diffObj[prop]).length === 0) {
                delete diffObj[prop]
            }
        } else if(obj1[prop] !== obj2[prop]) {
            diffObj[prop] = obj2[prop]
        }
    });
    return diffObj
}

This might be not really efficient, but will output an object with only different props based on second Obj.

Change text (html) with .animate

If all you're looking to do is change the text you could do exactly as Kevin has said. But if you're trying to run an animation as well as change the text you could accomplish this by first changing the text then running your animation.

For Example:

$("#test").html('The text has now changed!');
$("#test").animate({left: '100px', top: '100px'},500);

Check out this fiddle for full example:

http://jsfiddle.net/Twig/3krLh/1/

Prevent Sequelize from outputting SQL to the console on execution of query?

I solved a lot of issues by using the following code. Issues were : -

  1. Not connecting with database
  2. Database connection Rejection issues
  3. Getting rid of logs in console (specific for this).
const sequelize = new Sequelize("test", "root", "root", {
  host: "127.0.0.1",
  dialect: "mysql",
  port: "8889",
  connectionLimit: 10,
  socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
  // It will disable logging
  logging: false
});

How might I find the largest number contained in a JavaScript array?

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

_x000D_
_x000D_
const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];_x000D_
const maxNumber = Math.max(...inputArray);_x000D_
console.log(maxNumber);
_x000D_
_x000D_
_x000D_

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

Make an HTTP request with android

For me, the easiest way is using library called Retrofit2

We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

    public interface MyService {

      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);

      @POST("users/new")
      Call<User> createUser(@Body User user);

      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first, 
                            @Field("last_name") String last);

      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo, 
                            @Part("description") RequestBody description);

      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);    

    }

And the best is, we can do it asynchronously easily using enqueue method

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

Compiling/Executing a C# Source File in Command Prompt

While it is definitely a good thing knowing how to build at the command line, for most work it might be easier to use an IDE. The C# express edition is free and very good for the money ;-p

Alternatively, things like snippy can be used to run fragments of C# code.

Finally - note that the command line is implementation specific; for MS, it is csc; for mono, it is gmcs and friends.... Likewise, to execute: it is just "exename" for the MS version, but typically "mono exename" for mono.

Finally, many projects are build with build script tools; MSBuild, NAnt, etc.

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Mun's answer didn't work for me so I made some changes to that answer to get it to work. Hope this helps someone. Using SQL Server 2012:

SELECT [VehicleID]
     , [Name]
     , STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City) 
         FROM [Location] 
         WHERE (VehicleID = Vehicle.VehicleID) 
         FOR XML PATH ('')), 1, 2, '') AS Locations
FROM [Vehicle]

Unable to begin a distributed transaction

OK, so services are started, there is an ethernet path between them, name resolution works, linked servers work, and you disabled transaction authentication.

My gut says firewall issue, but a few things come to mind...

  1. Are the machines in the same domain? (yeah, shouldn't matter with disabled authentication)
  2. Are firewalls running on the the machines? DTC can be a bit of pain for firewalls as it uses a range of ports, see http://support.microsoft.com/kb/306843 For the time being, I would disable firewalls for the sake of identifying the problem
  3. What does DTC ping say? http://www.microsoft.com/download/en/details.aspx?id=2868
  4. What account is the SQL Service running as ?

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

Powershell: convert string to number

Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.

  1. Replacing the "." character when value is a string

The string class offers a replace method for the string object you want to update:

Example:

$myString = $myString.replace(".","") 
  1. Converting the string value to an integer

The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.

Example:

[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)

I hope this addresses the issue you initially brought up in your question.

How do I drag and drop files into an application?

Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

How to remove trailing whitespace in code, using another script?

This is the sort of thing that sed is really good at: $ sed 's/[ \t]*$//'. Be aware the you will probably need to literally type a TAB character instead of \t for this to work.

Rotating x axis labels in R for barplot

Andre Silva's answer works great for me, with one caveat in the "barplot" line:

barplot(mtcars$qsec, col="grey50", 
    main="",
    ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
    xlab = "",
    xaxt = "n", 
    space=1)

Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Converting binary to decimal integer output

This is the full thing

binary = input('enter a number: ')
decimal = 0
for digit in binary:
decimal= decimal*2 + int(digit)

print (decimal)

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

jQuery: How to capture the TAB keypress within a Textbox

Suppose you have TextBox with Id txtName

$("[id*=txtName]").on('keydown', function(e) { 
  var keyCode = e.keyCode || e.which; 
  if (keyCode == 9) {
     e.preventDefault();
     alert('Tab Pressed');
 }
}); 

Increase permgen space

For tomcat you can increase the permGem space by using

 -XX:MaxPermSize=128m

For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat

How do I combine 2 select statements into one?

You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE clause, and then UNION them together:

select 
    'Test1', * 
from 
    TABLE 
Where 
    CCC='D' AND DDD='X' AND exists(select ...)
UNION
select 
    'Test2', * 
from 
    TABLE
Where
    CCC<>'D' AND DDD='X' AND exists(select ...)

This might be an issue, because you are going to effectively scan/seek on TABLE twice.

The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:

select 
    case 
        when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
        when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
    end,
    * 
from 
    TABLE 
Where 
    (CCC='D' AND DDD='X' AND exists(select ...)) or
    (CCC<>'D' AND DDD='X' AND exists(select ...))

The catch here being that you will have to duplicate the filter conditions in the CASE statement and the WHERE statement.

SQL Server String or binary data would be truncated

Please try the following code:

CREATE TABLE [dbo].[Department](
    [Department_name] char(10) NULL
)

INSERT INTO [dbo].[Department]([Department_name]) VALUES  ('Family Medicine')
--error will occur

 ALTER TABLE [Department] ALTER COLUMN [Department_name] char(50)

INSERT INTO [dbo].[Department]([Department_name]) VALUES  ('Family Medicine')

select * from [Department]

How to get Latitude and Longitude of the mobile device in android?

You can use FusedLocationProvider

For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   ...
   ...
   ...
   implementation 'com.google.android.gms:play-services-location:17.0.0'
}

Permissions in Manifest

Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.

ActivityCompat.requestPermissions(
    this,
    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
    PERMISSION_ID
)

Then you can use the FusedLocationProvider Client to get the updated location in your desired place.

    mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
        var location: Location? = task.result
        if (location == null) {
            requestNewLocationData()
        } else {
            findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
            findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
        }
    }

You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:

private fun requestNewLocationData() {
    var mLocationRequest = LocationRequest()
    mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    mLocationRequest.interval = 0
    mLocationRequest.fastestInterval = 0
    mLocationRequest.numUpdates = 1

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    mFusedLocationClient!!.requestLocationUpdates(
            mLocationRequest, mLocationCallback,
            Looper.myLooper()
    )
}

Copy all files with a certain extension from all subdirectories

I also had to do this myself. I did it via the --parents argument for cp:

find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;

How can I sharpen an image in OpenCV?

You can try a simple kernel and the filter2D function, e.g. in Python:

kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
im = cv2.filter2D(im, -1, kernel)

Wikipedia has a good overview of kernels with some more examples here - https://en.wikipedia.org/wiki/Kernel_(image_processing)

In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

how to know status of currently running jobs

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

check field execution_status

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

If you need the result of execution, check the field last_run_outcome

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

https://msdn.microsoft.com/en-us/library/ms186722.aspx

PostgreSQL: Drop PostgreSQL database through command line

You can run the dropdb command from the command line:

dropdb 'database name'

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name';

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname FORCE;

or

dropdb -f dbname

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

How to replace blank (null ) values with 0 for all records?

I would change the SQL statement above to be more generic. Using wildcards is never a bad idea when it comes to mass population to avoid nulls.

Try this:

Update Table Set * = 0 Where * Is Null; 

How to check if a String contains any of some strings

Well, there's always this:

public static bool ContainsAny(this string haystack, params string[] needles)
{
    foreach (string needle in needles)
    {
        if (haystack.Contains(needle))
            return true;
    }

    return false;
}

Usage:

bool anyLuck = s.ContainsAny("a", "b", "c");

Nothing's going to match the performance of your chain of || comparisons, however.

High CPU Utilization in java application - why?

Your first approach should be to find all references to Thread.sleep and check that:

  1. Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue would help.

  2. If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.

The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait for the occurrence.

The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.

Viewing unpushed Git commits

Similar: To view unmerged branches:

git branch --all --no-merged

Those can be suspect but I recommend the answer by cxreg

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Is there any sizeof-like method in Java?

You can do bit manipulations like below to obtain the size of primitives:

public int sizeofInt() {
    int i = 1, j = 0;
    while (i != 0) {
        i = (i<<1); j++;
    }
    return j;
}

public int sizeofChar() {
    char i = 1, j = 0;
    while (i != 0) {
        i = (char) (i<<1); j++;
    }
    return j;
}

JavaScript Nested function

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
}_x000D_
bar();
_x000D_
_x000D_
_x000D_
Will throw an error. Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
  bar();_x000D_
}
_x000D_
_x000D_
_x000D_

Get selected value of a dropdown's item using jQuery

try this

$("#yourDropdown option:selected").text();

Validate Dynamically Added Input fields

In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.

(function ($) {

    $.fn.initValidation = function () {

        $(this).removeData("validator");
        $(this).removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse(this);

        return this;
    };

}(jQuery));

This can be used like this:

$("#SomeForm").initValidation();

Understanding ibeacon distancing

I'm very thoroughly investigating the matter of accuracy/rssi/proximity with iBeacons and I really really think that all the resources in the Internet (blogs, posts in StackOverflow) get it wrong.

davidgyoung (accepted answer, > 100 upvotes) says:

Note that the term "accuracy" here is iOS speak for distance in meters.

Actually, most people say this but I have no idea why! Documentation makes it very very clear that CLBeacon.proximity:

Indicates the one sigma horizontal accuracy in meters. Use this property to differentiate between beacons with the same proximity value. Do not use it to identify a precise location for the beacon. Accuracy values may fluctuate due to RF interference.

Let me repeat: one sigma accuracy in meters. All 10 top pages in google on the subject has term "one sigma" only in quotation from docs, but none of them analyses the term, which is core to understand this.

Very important is to explain what is actually one sigma accuracy. Following URLs to start with: http://en.wikipedia.org/wiki/Standard_error, http://en.wikipedia.org/wiki/Uncertainty

In physical world, when you make some measurement, you always get different results (because of noise, distortion, etc) and very often results form Gaussian distribution. There are two main parameters describing Gaussian curve:

  1. mean (which is easy to understand, it's value for which peak of the curve occurs).
  2. standard deviation, which says how wide or narrow the curve is. The narrower curve, the better accuracy, because all results are close to each other. If curve is wide and not steep, then it means that measurements of the same phenomenon differ very much from each other, so measurement has a bad quality.

one sigma is another way to describe how narrow/wide is gaussian curve.
It simply says that if mean of measurement is X, and one sigma is s, then 68% of all measurements will be between X - s and X + s.

Example. We measure distance and get a gaussian distribution as a result. The mean is 10m. If s is 4m, then it means that 68% of measurements were between 6m and 14m.

When we measure distance with beacons, we get RSSI and 1-meter calibration value, which allow us to measure distance in meters. But every measurement gives different values, which form gaussian curve. And one sigma (and accuracy) is accuracy of the measurement, not distance!

It may be misleading, because when we move beacon further away, one sigma actually increases because signal is worse. But with different beacon power-levels we can get totally different accuracy values without actually changing distance. The higher power, the less error.

There is a blog post which thoroughly analyses the matter: http://blog.shinetech.com/2014/02/17/the-beacon-experiments-low-energy-bluetooth-devices-in-action/

Author has a hypothesis that accuracy is actually distance. He claims that beacons from Kontakt.io are faulty beacuse when he increased power to the max value, accuracy value was very small for 1, 5 and even 15 meters. Before increasing power, accuracy was quite close to the distance values. I personally think that it's correct, because the higher power level, the less impact of interference. And it's strange why Estimote beacons don't behave this way.

I'm not saying I'm 100% right, but apart from being iOS developer I have degree in wireless electronics and I think that we shouldn't ignore "one sigma" term from docs and I would like to start discussion about it.

It may be possible that Apple's algorithm for accuracy just collects recent measurements and analyses the gaussian distribution of them. And that's how it sets accuracy. I wouldn't exclude possibility that they use info form accelerometer to detect whether user is moving (and how fast) in order to reset the previous distribution distance values because they have certainly changed.

Instantly detect client disconnection from server socket

This is in VB, but it seems to work well for me. It looks for a 0 byte return like the previous post.

Private Sub RecData(ByVal AR As IAsyncResult)
    Dim Socket As Socket = AR.AsyncState

    If Socket.Connected = False And Socket.Available = False Then
        Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
        Exit Sub
    End If
    Dim BytesRead As Int32 = Socket.EndReceive(AR)
    If BytesRead = 0 Then
        Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
        UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
        Socket.Close()
        Exit Sub
    End If
    Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
    Erase ByteData
    ReDim ByteData(1024)
    ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
    UpdateText(msg)
End Sub

ASP.NET - How to write some html in the page? With Response.Write?

ASPX file:

<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>

ASPX.CS file:

ltNotify.Text = "Alert!";

MySQL query String contains

Mine is using LOCATE in mysql:

LOCATE(substr,str), LOCATE(substr,str,pos)

This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.

In your case:

mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");

How to use RANK() in SQL Server

RANK() is good, but it assigns the same rank for equal or similar values. And if you need unique rank, then ROW_NUMBER() solves this problem

ROW_NUMBER() OVER (ORDER BY totals DESC) AS xRank

Node.js: what is ENOSPC error and how to solve?

If you encounter this error during trying to run ember server command please rm -rf tmp directory. Then run ember s again. It helped me.

Border length smaller than div width?

div{
    font-size: 25px;
    line-height: 27px;
    display:inline-block;
    width:200px;
    text-align:center;
}

div::after {
    background: #f1991b none repeat scroll 0 0;
    content: "";
    display: block;
    height: 3px;
    margin-top: 15px;
    width: 100px;
    margin:auto;
}

Add table row in jQuery

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

will add a new row to the first TBODY of the table, without depending of any THEAD or TFOOT present. (I didn't find information from which version of jQuery .append() this behavior is present.)

You may try it in these examples:

<table class="t"> <!-- table with THEAD, TBODY and TFOOT -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t"> <!-- table with two TBODYs -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tbody>
  <tr><td>3</td><td>4</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t">  <!-- table without TBODY -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
</table><br>

<table class="t">  <!-- table with TR not in TBODY  -->
  <tr><td>1</td><td>2</td></tr>
</table>
<br>
<table class="t">
</table>

<script>
$('.t').append('<tr><td>a</td><td>a</td></tr>');
</script>

In which example a b row is inserted after 1 2, not after 3 4 in second example. If the table were empty, jQuery creates TBODY for a new row.

How can strings be concatenated?

More efficient ways of concatenating strings are:

join():

Very efficent, but a bit hard to read.

>>> Section = 'C_type'  
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings 
>>> print new_str 
>>> 'Sec_C_type'

String formatting:

Easy to read and in most cases faster than '+' concatenating

>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

How to remove all options from a dropdown using jQuery / JavaScript

You can either use .remove() on option elements:

.remove() : Remove the set of matched elements from the DOM.

 $('#models option').remove(); or $('#models').remove('option');

or use .empty() on select:

.empty() : Remove all child nodes of the set of matched elements from the DOM.

 $('#models').empty();

however to repopulate deleted options, you need to store the option while deleting.

You can also achieve the same using show/hide:

$("#models option").hide();

and later on to show them:

$("#models option").show();

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

HTML Image not displaying, while the src url works

You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension In your case, j3evn.jpg.

Constructor overload in TypeScript

I use the following alternative to get default/optional params and "kind-of-overloaded" constructors with variable number of params:

private x?: number;
private y?: number;

constructor({x = 10, y}: {x?: number, y?: number}) {
 this.x = x;
 this.y = y;
}

I know it's not the prettiest code ever, but one gets used to it. No need for the additional Interface and it allows private members, which is not possible when using the Interface.

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How to swap two variables in JavaScript

Swap using Bitwise

let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;

Single line Swap "using Array"

[a, b] = [b, a]

correct PHP headers for pdf file download

There are some things to be considered in your code.

First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.

The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.

Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.

In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)

All that being said, your code should look more like this:

<?php

    $filename = './pdf/jobs/pdffile.pdf';

    $fileinfo = pathinfo($filename);
    $sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);

    header('Content-Type: application/pdf');
    header("Content-Disposition: attachment; filename=\"$sendname\"");
    header('Content-Length: ' . filesize($filename));
    readfile($filename);

Content-Length is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.

How do you UDP multicast in Python?

To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the IP_MULTICAST_TTL socket option as an unsigned char. Otherwise you will get an error. This worked for me on Solaris 10 and 11:

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

Removing border from table cells

If none of the solutions on this page work and you are having the below issue:

enter image description here

You can simply use this snippet of CSS:

td {
   padding: 0;
}

Where does linux store my syslog?

Logging is very configurable in Linux, and you might want to look into your /etc/syslog.conf (or perhaps under /etc/rsyslog.d/). Details depend upon the logging subsystem, and the distribution.

Look also into files under /var/log/ (and perhaps run dmesg for kernel logs).

Why do I need to do `--set-upstream` all the time?

For those looking for an alias that works with git pull, this is what I use:

alias up="git branch | awk '/^\\* / { print \$2 }' | xargs -I {} git branch --set-upstream-to=origin/{} {}"

Now whenever you get:

$ git pull
There is no tracking information for the current branch.
...

Just run:

$ up
Branch my_branch set up to track remote branch my_branch from origin.
$ git pull

And you're good to go

Insert entire DataTable into database at once instead of row by row?

Since you have a DataTable already, and since I am assuming you are using SQL Server 2008 or better, this is probably the most straightforward way. First, in your database, create the following two objects:

CREATE TYPE dbo.MyDataTable -- you can be more speciifc here
AS TABLE
(
  col1 INT,
  col2 DATETIME
  -- etc etc. The columns you have in your data table.
);
GO

CREATE PROCEDURE dbo.InsertMyDataTable
  @dt AS dbo.MyDataTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.RealTable(column list) SELECT column list FROM @dt;
END
GO

Now in your C# code:

DataTable tvp = new DataTable();
// define / populate DataTable

using (connectionObject)
{
    SqlCommand cmd = new SqlCommand("dbo.InsertMyDataTable", connectionObject);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
    tvparam.SqlDbType = SqlDbType.Structured;
    cmd.ExecuteNonQuery();
}

If you had given more specific details in your question, I would have given a more specific answer.

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

Splitting strings in PHP and get last part

Since explode() returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.

$email = '[email protected]';
$provider = explode('@', $email)[1];
echo $provider; // example.com

Or another way is list():

$email = '[email protected]';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com

If you don't know the position:

$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four

How To Set Text In An EditText

Solution in Android Java:

  1. Start your EditText, the ID is come to your xml id.

    EditText myText = (EditText)findViewById(R.id.my_text_id);
    
  2. in your OnCreate Method, just set the text by the name defined.

    String text = "here put the text that you want"
    
  3. use setText method from your editText.

    myText.setText(text); //variable from point 2
    

Specifying maxlength for multiline textbox

$("textarea[maxlength]").on("keydown paste", function (evt) {
            if ($(this).val().length > $(this).prop("maxlength")) {
                if (evt.type == "paste") {
                    $(this).val($(this).val().substr(0, $(this).prop("maxlength")));
                } else {
                    if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
                        evt.returnValue = false;
                        evt.preventDefault();
                    }
                }
            }
        });

How to capture the "virtual keyboard show/hide" event in Android?

2020 Update

This is now possible:

On Android 11, you can do

view.setWindowInsetsAnimationCallback(object : WindowInsetsAnimation.Callback {
    override fun onEnd(animation: WindowInsetsAnimation) {
        super.onEnd(animation)
        val showingKeyboard = view.rootWindowInsets.isVisible(WindowInsets.Type.ime())
        // now use the boolean for something
    }
})

You can also listen to the animation of showing/hiding the keyboard and do a corresponding transition.

I recommend reading Android 11 preview and the corresponding documentation

Before Android 11

However, this work has not been made available in a Compat version, so you need to resort to hacks.

You can get the window insets and if the bottom insets are bigger than some value you find to be reasonably good (by experimentation), you can consider that to be showing the keyboard. This is not great and can fail in some cases, but there is no framework support for that.

This is a good answer on this exact question https://stackoverflow.com/a/36259261/372076. Alternatively, here's a page giving some different approaches to achieve this pre Android 11:

https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_android.meta/service_sdk_android/android_detecting_keyboard.htm


Note

This solution will not work for soft keyboards and onConfigurationChanged will not be called for soft (virtual) keyboards.


You've got to handle configuration changes yourself.

http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange

Sample:

// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    
    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}

Then just change the visibility of some views, update a field, and change your layout file.

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

Moving Panel in Visual Studio Code to right side

Hope this will help someone.

-> open to keyboard shortcut

-> search for "workbench.action.togglePanelPosition"

-> assign your desired shortcut

I've assigned keybinding "cmd+`"

{
  "key": "cmd+`",
  "command": "workbench.action.togglePanelPosition"
}

now I can toggle the terminal by pressing "cmd + `"

Request Monitoring in Chrome

You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.

https://developer.chrome.com/devtools

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

For setting java properties on Windows app server:

  • configure tomcat > run as admin
  • then add Java opts:

  • restart service.

The import com.google.android.gms cannot be resolved

Above solutions should solve your problem. If these do not, make sure you update your Android sdk using SDK manager and install the latest lib project and then repeat the above steps again.

XSL if: test with multiple test conditions

Just for completeness and those unaware XSL 1 has choose for multiple conditions.

<xsl:choose>
 <xsl:when test="expression">
  ... some output ...
 </xsl:when>
 <xsl:when test="another-expression">
  ... some output ...
 </xsl:when>
 <xsl:otherwise>
   ... some output ....
 </xsl:otherwise>
</xsl:choose>

Example of Mockito's argumentCaptor

Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :

 public void login() {
    loginService = new LoginService();
    loginService.login(loginProvider, new LoginListener() {
        @Override
        public void onLoginSuccess() {
            loginService.getresult(true);
        }

        @Override
        public void onLoginFaliure() {
            loginService.getresult(false);

        }
    });
    System.out.print("@@##### get called");
}

I also put all the helper class here to make the example more clear: loginService class

public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){

    String username  = loginProvider.getUsername();
    String pwd  = loginProvider.getPassword();
    if(username != null && pwd != null){
        callback.onLoginSuccess();
    }else{
        callback.onLoginFaliure();
    }

}

@Override
public void getresult(boolean value) {
    System.out.print("login success"+value);
}}

and we have listener LoginListener as :

interface LoginListener {
void onLoginSuccess();

void onLoginFaliure();

}

now I just wanted to test the method login() of class Login

 @Test
public void loginTest() throws Exception {
    LoginService service = mock(LoginService.class);
    LoginProvider provider = mock(LoginProvider.class);
    whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
    whenNew(LoginService.class).withNoArguments().thenReturn(service);
    when(provider.getPassword()).thenReturn("pwd");
    when(provider.getUsername()).thenReturn("username");
    login.getLoginDetail("username","password");

    verify(provider).setPassword("password");
    verify(provider).setUsername("username");

    verify(service).login(eq(provider),captor.capture());

    LoginListener listener = captor.getValue();

    listener.onLoginSuccess();

    verify(service).getresult(true);

also dont forget to add annotation above the test class as

@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

How does an SSL certificate chain bundle work?

The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2

This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.

See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.

But I still don't know why they wrote the spec so that the order matters.

Android Split string

String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

You may want to remove the space to the second String:

separated[1] = separated[1].trim();

If you want to split the string with a special character like dot(.) you should use escape character \ before the dot

Example:

String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"

There are other ways to do it. For instance, you can use the StringTokenizer class (from java.util):

StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method

How to create a .NET DateTime from ISO 8601 format

This works fine in LINQPad4:

Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00Z"));
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00"));
Console.WriteLine(DateTime.Parse("2010-08-20 15:00:00"));