Programs & Examples On #Jboss messaging

JBoss Messaging is the default JMS provider in JBoss Enterprise Application Platform and JBoss SOA Platform and JBoss Application Server version.

matching query does not exist Error in Django

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()

What is the meaning of {...this.props} in Reactjs

It will compile to this:

React.createElement('div', this.props, 'Content Here');

As you can see above, it passes all it's props to the div.

How to sort with a lambda?

To much code, you can use it like this:

#include<array>
#include<functional>

int main()
{
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

    std::sort(std::begin(vec), 
              std::end(vec), 
              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;
}

Replace "vec" with your class and that's it.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Select All as default value for Multivalue parameter

It works better

CREATE TABLE [dbo].[T_Status](
   [Status] [nvarchar](20) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO

DECLARE @GetStatus nvarchar(20) = null
--DECLARE @GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE  [Status] = CASE WHEN (isnull(@GetStatus, '')='') THEN [Status]
ELSE @GetStatus END

How do I find a list of Homebrew's installable packages?

brew help will show you the list of commands that are available.

brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

brew info <package name> will display some basic information about the package in question.

You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

How to get random value out of an array?

$rand = rand(1,4);

or, for arrays specifically:

$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same error and I solved it with MultiDex, like described on this link : https://developer.android.com/studio/build/multidex.html


Sometimes it is not enough just to enable MultiDex.

If any class that's required during startup is not provided in the primary DEX file, then your app crashes with the error java.lang.NoClassDefFoundError. https://developer.android.com/studio/build/multidex#keep

FirebaseInitProvider is required during startup.

So you must manually specify FirebaseInitProvider as required in the primary DEX file.

build.gradle file

android {
    buildTypes {
        release {
            multiDexKeepFile file('multidex-config.txt')
            ...
        }
    }
}

multidex-config.txt (in the same directory as the build.gradle file)

com/google/firebase/provider/FirebaseInitProvider.class

How to update a value, given a key in a hashmap?

There are misleading answers to this question here that imply Hashtable put method will replace the existing value if the key exists, this is not true for Hashtable but rather for HashMap. See Javadoc for HashMap http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

javac: file not found: first.java Usage: javac <options> <source files>

Sometimes this issue occurs, If you are creating a java file for the first time in your system. The Extension of your Java file gets saved as the text file.

e.g Example.java.txt (wrong extension)

You need to change the text file extension to java file.

It should be like:

Example.java (right extension)

I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

What is the difference between #include <filename> and #include "filename"?

Form 1 - #include < xxx >

First, looks for the presence of header file in the current directory from where directive is invoked. If not found, then it searches in the preconfigured list of standard system directories.

Form 2 - #include "xxx"

This looks for the presence of header file in the current directory from where directive is invoked.


The exact search directory list depends on the target system, how GCC is configured, and where it is installed. You can find the search directory list of your GCC compiler by running it with -v option.

You can add additional directories to the search path by using - Idir, which causes dir to be searched after the current directory (for the quote form of the directive) and ahead of the standard system directories.


Basically, the form "xxx" is nothing but search in current directory; if not found falling back the form

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

Android Studio-No Module

Other path is " tool menu-->android-->sync proyect with gradle File"

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

Detecting iOS / Android Operating system

Using the cordova-device-plugin, you can detect

device.platform

will be "Android" for android, and "windows" for windows. Works on device, and when simulating on browser. Here is a toast that will display the device values:

    window.plugins.toast.showLongTop(
    'Cordova:     ' + device.cordova + '\n' +
    'Model:       ' + device.model + '\n' +
    'Platform:    ' + device.platform + '\n' +
    'UUID:        ' + '\n' +
                      device.uuid + '\n' +
    'Version:     ' + device.version + '\n' +
    'Manufacturer ' + device.manufacturer + '\n' +
    'isVirtual    ' + device.isVirtual + '\n' +
    'Serial       ' + device.serial);

Adding a new value to an existing ENUM Type

Disclaimer: I haven't tried this solution, so it might not work ;-)

You should be looking at pg_enum. If you only want to change the label of an existing ENUM, a simple UPDATE will do it.

To add a new ENUM values:

  • First insert the new value into pg_enum. If the new value has to be the last, you're done.
  • If not (you need to a new ENUM value in between existing ones), you'll have to update each distinct value in your table, going from the uppermost to the lowest...
  • Then you'll just have to rename them in pg_enum in the opposite order.

Illustration
You have the following set of labels:

ENUM ('enum1', 'enum2', 'enum3')

and you want to obtain:

ENUM ('enum1', 'enum1b', 'enum2', 'enum3')

then:

INSERT INTO pg_enum (OID, 'newenum3');
UPDATE TABLE SET enumvalue TO 'newenum3' WHERE enumvalue='enum3';
UPDATE TABLE SET enumvalue TO 'enum3' WHERE enumvalue='enum2';

then:

UPDATE TABLE pg_enum SET name='enum1b' WHERE name='enum2' AND enumtypid=OID;

And so on...

pthread function from a class

My first answer ever in the hope that it'll be usefull to someone : I now this is an old question but I encountered exactly the same error as the above question as I'm writing a TcpServer class and I was trying to use pthreads. I found this question and I understand now why it was happening. I ended up doing this:

#include <thread>

method to run threaded -> void* TcpServer::sockethandler(void* lp) {/*code here*/}

and I call it with a lambda -> std::thread( [=] { sockethandler((void*)csock); } ).detach();

that seems a clean approach to me.

Java String split removed empty values

From String.split() API Doc:

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Overloaded String.split(regex, int) is more appropriate for your case.

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Extract the first word of a string in a SQL Server query

I wanted to do something like this without making a separate function, and came up with this simple one-line approach:

DECLARE @test NVARCHAR(255)
SET @test = 'First Second'

SELECT SUBSTRING(@test,1,(CHARINDEX(' ',@test + ' ')-1))

This would return the result "First"

It's short, just not as robust, as it assumes your string doesn't start with a space. It will handle one-word inputs, multi-word inputs, and empty string or NULL inputs.

How to center body on a page?

    body
    {
        width:80%;
        margin-left:auto;
        margin-right:auto;
    }

This will work on most browsers, including IE.

Express.js req.body undefined

This issue may be because you have not use body-parser (link)

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

var app = express();
app.use(bodyParser.json());

Why do people hate SQL cursors so much?

You could have probably concluded your question after the second paragraph, rather than calling people "insane" simply because they have a different viewpoint than you do and otherwise trying to mock professionals who may have a very good reason for feeling the way that they do.

As to your question, while there are certainly situations where a cursor may be called for, in my experience developers decide that a cursor "must" be used FAR more often than is actually the case. The chance of someone erring on the side of too much use of cursors vs. not using them when they should is MUCH higher in my opinion.

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

new DateTime() vs default(DateTime)

No, they are identical.

default(), for any value type (DateTime is a value type) will always call the parameterless constructor.

How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

Clicking a button within a form causes page refresh

You can keep <button type="submit">, but must remove the attribute action="" of <form>.

How to make ConstraintLayout work with percentage values?

Try this code. You can change the height and width percentages with app:layout_constraintHeight_percent and app:layout_constraintWidth_percent.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF00FF"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".6"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".4"></LinearLayout>

</android.support.constraint.ConstraintLayout>

Gradle:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Make sure that both the chromedriver and google-chrome executable have execute permissions

sudo chmod -x "/usr/bin/chromedriver"

sudo chmod -x "/usr/bin/google-chrome"

How to apply slide animation between two activities in Android?

Here is a Slide Animation for you.

enter image description here

Let's say you have two activities.

  1. MovieDetailActivity
  2. AllCastActivity

And on click of a Button, this happens.

enter image description here

You can achieve this in 3 simple steps

1) Enable Content Transition

Go to your style.xml and add this line to enable the content transition.

<item name="android:windowContentTransitions">true</item>

2) Write Default Enter and Exit Transition for your AllCastActivity

public void setAnimation()
{
    if(Build.VERSION.SDK_INT>20) {
        Slide slide = new Slide();
        slide.setSlideEdge(Gravity.LEFT);
        slide.setDuration(400);
        slide.setInterpolator(new AccelerateDecelerateInterpolator());
        getWindow().setExitTransition(slide);
        getWindow().setEnterTransition(slide);
    }
}

3) Start Activity with Intent

Write this method in Your MovieDetailActivity to start AllCastActivity

public void startActivity(){

Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());

  if(Build.VERSION.SDK_INT>20)
   {
       ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
       startActivity(i,options.toBundle());
   }
   else {
       startActivity(i);
   }
}

Most important!

put your setAnimation()method before setContentView() method otherwise the animation will not work.
So your AllCastActivity.javashould look like this

 class AllCastActivity extends AppcompatActivity {

   @Override
   protected void onCreate(Bundle savedInstaceState)
   {
      super.onCreate(savedInstaceState);

      setAnimation();

      setContentView(R.layout.all_cast_activity);

      .......
   }

   private void setAnimation(){

      if(Build.VERSION.SDK_INT>20) {
      Slide slide = new Slide();
      slide.setSlideEdge(Gravity.LEFT);
      ..........
  }
}

How can I connect to MySQL in Python 3 on Windows?

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3

"rm -rf" equivalent for Windows?

USE AT YOUR OWN RISK. INFORMATION PROVIDED 'AS IS'. NOT TESTED EXTENSIVELY.

Right-click Windows icon (usually bottom left) > click "Windows PowerShell (Admin)" > use this command (with due care, you can easily delete all your files if you're not careful):

rd -r -include *.* -force somedir

Where somedir is the non-empty directory you want to remove.

Note that with external attached disks, or disks with issues, Windows sometimes behaves odd - it does not error in the delete (or any copy attempt), yet the directory is not deleted (or not copied) as instructed. (I found that in this case, at least for me, the command given by @n_y in his answer will produce errors like 'get-childitem : The file or directory is corrupted and unreadable.' as a result in PowerShell)

Bootstrap - 5 column layout

Why not using grid?

.container {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  grid-column-gap: 20px
}

MD5 hashing in Android

The androidsnippets.com code does not work reliably because 0's seem to be cut out of the resulting hash.

A better implementation is here.

public static String MD5_Hash(String s) {
    MessageDigest m = null;

    try {
            m = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
    }

    m.update(s.getBytes(),0,s.length());
    String hash = new BigInteger(1, m.digest()).toString(16);
    return hash;
}

How to set custom favicon in Express?

Install express-favicon middleware:

npm install express-favicon --save

Use it like this:

const favicon = require('express-favicon');
app.use(favicon(__dirname + 'favicon.ico'));

In Javascript, how to conditionally add a member to an object?

I would do this

var a = someCondition ? { b: 5 } : {};

Edited with one line code version

How to cancel an $http request in AngularJS?

If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:

// in service

                var deferred = $q.defer();
                var scope = this;
                $http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
                    //do something
                    deferred.resolve(dataUsage);
                }).error(function(){
                    deferred.reject();
                });
                return deferred.promise;

// in UIrouter config

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    //To cancel pending request when change state
       angular.forEach($http.pendingRequests, function(request) {
          if (request.cancel && request.timeout) {
             request.cancel.resolve();
          }
       });
    });

How to declare or mark a Java method as deprecated?

Use @Deprecated on method. Don't forget about clarifying javadoc field:

/**
 * Does some thing in old style.
 *
 * @deprecated use {@link #new()} instead.  
 */
@Deprecated
public void old() {
// ...
}

What is the difference between res.end() and res.send()?

I would like to make a little bit more emphasis on some key differences between res.end() & res.send() with respect to response headers and why they are important.

1. res.send() will check the structure of your output and set header information accordingly.


    app.get('/',(req,res)=>{
       res.send('<b>hello</b>');
    });

enter image description here


     app.get('/',(req,res)=>{
         res.send({msg:'hello'});
     });

enter image description here

Where with res.end() you can only respond with text and it will not set "Content-Type"

      app.get('/',(req,res)=>{
           res.end('<b>hello</b>');
      }); 

enter image description here

2. res.send() will set "ETag" attribute in the response header

      app.get('/',(req,res)=>{
            res.send('<b>hello</b>');
      });

enter image description here

¿Why is this tag important?
The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed.

res.end() will NOT set this header attribute

How to use opencv in using Gradle?

These are the steps necessary to use OpenCV with Android Studio 1.2:

  • Download OpenCV and extract the archive
  • Open your app project in Android Studio
  • Go to File -> New -> Import Module...
  • Select sdk/java in the directory you extracted before
  • Set Module name to opencv
  • Press Next then Finish
  • Open build.gradle under imported OpenCV module and update compileSdkVersion and buildToolsVersion to versions you have on your machine
  • Add compile project(':opencv') to your app build.gradle

    dependencies {
        ...
        compile project(':opencv')
    }
    
  • Press Sync Project with Gradle Files

How to get to a particular element in a List in java?

At this point:

for (String[] s : myEntries) {
   System.out.println("Next item: " + s);
}

You need to join the array of Strings in a line. Check this post: A method to reverse effect of java String.split()?

Found shared references to a collection org.hibernate.HibernateException

Posting here because it's taken me over 2 weeks to get to the bottom of this, and I still haven't fully resolved it.

There is a chance, that you're also just running into this bug which has been around since 2017 and hasn't been addressed.

I honestly have no clue how to get around this bug. I'm posting here for my sanity and hopefully to shave a couple weeks of your googling. I'd love any input anyone may have, but my particular "answer" to this problem was not listed in any of the above answers.

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

@HostBinding and @HostListener: what do they do and what are they for?

// begginers
@Component({
  selector: 'custom-comp',
  template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
})
export class CustomComp {
  onClick = () => console.log('click event');
}

// pros
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
})
export class CustomComp {
  @HostBinding('class') class = 'my-class';
  @HostListener('click') onClick = () => console.log('click event');
}

// experts
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
  host: {
    class: 'my-class',
    '(click)': 'onClick()',
  },
})
export class CustomComp {}

------------------------------------------------
The 1st way will result in:
<custom-comp>
   <div class="my-class" (click)="onClick()">
      CLICK ME
   <div>
</custom-comp>

The last 2 ways will result in:
<custom-comp class="my-class" (click)="onClick()">
   CLICK ME
</custom-comp>

How to set margin of ImageView using code, not xml

Here is an example to add 8px Margin on left, top, right, bottom.


ImageView imageView = new ImageView(getApplicationContext());

ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
    ViewGroup.MarginLayoutParams.MATCH_PARENT,
    ViewGroup.MarginLayoutParams.WRAP_CONTENT
);

marginLayoutParams.setMargins(8, 8, 8, 8);

imageView.setLayoutParams(marginLayoutParams);

conversion from string to json object android

Remove the slashes:

String json = {"phonetype":"N95","cat":"WP"};

try {

    JSONObject obj = new JSONObject(json);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

How can I implement the Iterable interface?

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

So I would at least change it to:

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

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

    ...

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

and this should work:

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

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

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

This is a pretty obscure corner case of Java generics.

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

A generic list of anonymous class

Here is the answer.

string result = String.Empty;

var list = new[]
{ 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
}.ToList();

foreach (var item in list)
{
    result += String.Format("Name={0}, Number={1}\n", item.Name, item.Number);
}

MessageBox.Show(result);

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

Kotlin Android start new Activity

From activity to activity

val intent = Intent(this, YourActivity::class.java)
startActivity(intent)

From fragment to activity

val intent = Intent(activity, YourActivity::class.java)
startActivity(intent)

Do something if screen width is less than 960 px

// Adds and removes body class depending on screen width.
function screenClass() {
    if($(window).innerWidth() > 960) {
        $('body').addClass('big-screen').removeClass('small-screen');
    } else {
        $('body').addClass('small-screen').removeClass('big-screen');
    }
}

// Fire.
screenClass();

// And recheck when window gets resized.
$(window).bind('resize',function(){
    screenClass();
});

git push rejected: error: failed to push some refs

for me following worked, just ran these command one by one

git pull -r origin master

git push -f origin your_branch

How to print a string in C++

#include <iostream>
std::cout << someString << "\n";

or

printf("%s\n",someString.c_str());

Cloning specific branch

a git repository has several branches. Each branch follows a development line, and it has its origin in another branch at some point in time (except the first branch, typically called master, that it starts as the default branch until someone changes, what almost never happens)

If you are new with git, remember those 2 fundamentals. Now, you just need to clone the repository, and it will be in some branch. if the branch is the one you are looking for, awesome. If not, you just need to change to the other branch - this is called checkout. Just type git checkout <branch-name>

In some cases you want to get updates for a specific branch. Just do git pull origin <branch-name> and it will 'download' the new commits (changes). If you didn't do any changes, it should go easy. If you also introduced changes on that branches, conflicts may appear. let me know if you need more info on this case also

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

set define off;

Alternatively, hacky:

update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

What is the simplest method of inter-process communication between 2 C# processes?

I would suggest using the Windows Communication Foundation:

http://en.wikipedia.org/wiki/Windows_Communication_Foundation

You can pass objects back and forth, use a variety of different protocols. I would suggest using the binary tcp protocol.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Just Add AjaxControlToolkit.dll to your Reference folder.

On your Project Solution

Right Click on Reference Folder  > Add Reference > browse  AjaxControlToolkit.dll .

Then build.

Regards

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

Is it possible to change the speed of HTML's <marquee> tag?

         <body>
         <marquee direction="left" behavior=scroll scrollamount="2">This is basic example of marquee</marquee>
         <marquee direction="up">The direction of text will be from bottom to top.</marquee>
         </body>

use scrollamount to control speed..

How do I create an average from a Ruby array?

This method can be helpful.

def avg(arr)
  val = 0.0

  arr.each do |n|
    val += n
  end

  len = arr.length

  val / len 
end

p avg([0,4,8,2,5,0,2,6])

Redirect to Action in another controller

This should work

return RedirectToAction("actionName", "controllerName", null);

How do you deploy Angular apps?

You get the smallest and quickest loading production bundle by compiling with the Ahead of Time compiler, and tree-shake/minify with rollup as shown in the angular AOT cookbook here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

This is also available with the Angular-CLI as said in previous answers, but if you haven't made your app using the CLI you should follow the cookbook.

I also have a working example with materials and SVG charts (backed by Angular2) that it includes a bundle created with the AOT cookbook. You also find all the config and scripts needed to create the bundle. Check it out here: https://github.com/fintechneo/angular2-templates/

I made a quick video demonstrating the difference between number of files and size of an AoT compiled build vs a development environment. It shows the project from the github repository above. You can see it here: https://youtu.be/ZoZDCgQwnmQ

How to bring back "Browser mode" in IE11?

Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:

  • Internet Explorer 6
  • Internet Explorer 7
  • Internet Explorer 11 /!\ Unsupported Version (can't use it; big whoop, I have the browser)

Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.

Firefox used to be supported, but I don't see it now. Might be hiding.

I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.

I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.

Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.

Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.

How do I convert a pandas Series or index to a Numpy array?

A more recent way to do this is to use the .to_numpy() function.

If I have a dataframe with a column 'price', I can convert it as follows:

priceArray = df['price'].to_numpy()

You can also pass the data type, such as float or object, as an argument of the function

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

Line Break in XML formatting?

Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:

// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
    return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}

For XML you should probably edit that to replace with <br/> instead.

Example of its use in a function (additional calls removed for clarity):

// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
    return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}

...and a further example:

textView.setText(getStyledTextFromHtml(someString));

In Python, how do I loop through the dictionary and change the value if it equals something?

for k, v in mydict.iteritems():
    if v is None:
        mydict[k] = ''

In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.

In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.

Refer to this post.

Android: Storing username and password?

The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.

I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

Node.js - EJS - including a partial

With Express 3.0:

<%- include myview.ejs %>

the path is relative from the caller who includes the file, not from the views directory set with app.set("views", "path/to/views").

EJS includes

(Update: the newest syntax for ejs v3.0.1 is <%- include('myview.ejs') %>)

How to display default text "--Select Team --" in combo box on pageload in WPF?

IceForge's answer was pretty close, and is AFAIK the easiest solution to this problem. But it missed something, as it wasn't working (at least for me, it never actually displays the text).

In the end, you can't just set the "Visibility" property of the TextBlock to "Hidden" in order for it to be hidden when the combo box's selected item isn't null; you have to SET it that way by default (since you can't check not null in triggers, by using a Setter in XAML at the same place as the Triggers.

Here's the actual solution based on his, the missing Setter being placed just before the Triggers:

<ComboBox x:Name="combo"/>
<TextBlock Text="--Select Team--" IsHitTestVisible="False">
    <TextBlock.Style>
        <Style TargetType="TextBlock">

            <Style.Setters>
                <Setter Property="Visibility" Value="Hidden"/>
            </Style.Setters>

            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=combo,Path=SelectedItem}" Value="{x:Null}">
                    <Setter Property="Visibility" Value="Visible"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

What is a superfast way to read large files line-by-line in VBA?

My take on it...obviously, you've got to do something with the data you read in. If it involves writing it to the sheet, that'll be deadly slow with a normal For Loop. I came up with the following based upon a rehash of some of the items there, plus some help from the Chip Pearson website.

Reading in the text file (assuming you don't know the length of the range it will create, so only the startingCell is given):

Public Sub ReadInPlainText(startCell As Range, Optional textfilename As Variant)

   If IsMissing(textfilename) Then textfilename = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Text File to Read")
   If textfilename = "" Then Exit Sub

   Dim filelength As Long
   Dim filenumber As Integer
   filenumber = FreeFile
   filelength = filelen(textfilename)
   Dim text As String
   Dim textlines As Variant

   Open textfilename For Binary Access Read As filenumber

   text = Space(filelength)
   Get #filenumber, , text

   'split the file with vbcrlf
   textlines = Split(text, vbCrLf) 

   'output to range
   Dim outputRange As Range
   Set outputRange = startCell
   Set outputRange = outputRange.Resize(UBound(textlines), 1)
   outputRange.Value = Application.Transpose(textlines)

   Close filenumber
 End Sub

Conversely, if you need to write out a range to a text file, this does it quickly in one print statement (note: the file 'Open' type here is in text mode, not binary..unlike the read routine above).

Public Sub WriteRangeAsPlainText(ExportRange As Range, Optional textfilename As Variant)
   If IsMissing(textfilename) Then textfilename = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
   If textfilename = "" Then Exit Sub

   Dim filenumber As Integer
   filenumber = FreeFile
   Open textfilename For Output As filenumber

   Dim textlines() As Variant, outputvar As Variant

   textlines = Application.Transpose(ExportRange.Value)
   outputvar = Join(textlines, vbCrLf)
   Print #filenumber, outputvar
   Close filenumber
End Sub

How do I wrap text in a pre tag?

I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.

 <div style="white-space: pre-wrap;">content</div>

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Android - save/restore fragment state

Try this :

@Override
protected void onPause() {
    super.onPause();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}

@Override
protected void onResume() {
    super.onResume();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}

Hope this will help.

Also you can write this to activity tag in menifest file :

  android:configChanges="orientation|screenSize"

Good luck !!!

Get IP address of visitors using Flask for Python

The below code always gives the public IP of the client (and not a private IP behind a proxy).

from flask import request

if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
    print(request.environ['REMOTE_ADDR'])
else:
    print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy

Is there a "do ... while" loop in Ruby?

Like this:

people = []

begin
  info = gets.chomp
  people += [Person.new(info)] if not info.empty?
end while not info.empty?

Reference: Ruby's Hidden do {} while () Loop

Create a new Ruby on Rails application using MySQL instead of SQLite

If you are using rails 3 or greater version

rails new your_project_name -d mysql

if you have earlier version

rails new -d mysql your_project_name

So before you create your project you need to find the rails version. that you can find by

rails -v

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You are using datetimepicker when it should be datepicker. As per the docs. Try this and it should work.

<script type="text/javascript">
  $(function () {
    $('#datetimepicker9').datepicker({
      viewMode: 'years'
    });
  });
 </script>

Laravel 5 How to switch from Production mode

Laravel 5 gets its enviroment related variables from the .env file located in the root of your project. You just need to set APP_ENV to whatever you want, for example:

APP_ENV=development

This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:

APP_DEBUG=true

The role of the .env file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env file settings would be different from your local development enviroment.

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

Numpy - add row to array

import numpy as np
array_ = np.array([[1,2,3]])
add_row = np.array([[4,5,6]])

array_ = np.concatenate((array_, add_row), axis=0)

Get child Node of another Node, given node name

Check if the Node is a Dom Element, cast, and call getElementsByTagName()

Node doc = docs.item(i);
if(doc instanceof Element) {
    Element docElement = (Element)doc;
    ...
    cell = doc.getElementsByTagName("aoo").item(0);
}

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation. You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

What does flex: 1 mean?

BE CAREFUL

In some browsers:

flex:1; does not equal flex:1 1 0;

flex:1; = flex:1 1 0n; (where n is a length unit).

  • flex-grow: A number specifying how much the item will grow relative to the rest of the flexible items.
  • flex-shrink A number specifying how much the item will shrink relative to the rest of the flexible items
  • flex-basis The length of the item. Legal values: "auto", "inherit", or a number followed by "%", "px", "em" or any other length unit.

The key point here is that flex-basis requires a length unit.

In Chrome for example flex:1 and flex:1 1 0 produce different results. In most circumstances it may appear that flex:1 1 0; is working but let's examine what really happens:

EXAMPLE

Flex basis is ignored and only flex-grow and flex-shrink are applied.

flex:1 1 0; = flex:1 1; = flex:1;

This may at first glance appear ok however if the applied unit of the container is nested; expect the unexpected!

Try this example in CHROME

_x000D_
_x000D_
.Wrap{_x000D_
  padding:10px;_x000D_
  background: #333;_x000D_
}_x000D_
.Flex110x, .Flex1, .Flex110, .Wrap {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-direction: column;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.Flex110 {_x000D_
  -webkit-flex: 1 1 0;_x000D_
  flex: 1 1 0;_x000D_
}_x000D_
.Flex1 {_x000D_
  -webkit-flex: 1;_x000D_
  flex: 1;_x000D_
}_x000D_
.Flex110x{_x000D_
  -webkit-flex: 1 1 0%;_x000D_
  flex: 1 1 0%;_x000D_
}
_x000D_
FLEX 1 1 0_x000D_
<div class="Wrap">_x000D_
  <div class="Flex110">_x000D_
    <input type="submit" name="test1" value="TEST 1">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
FLEX 1_x000D_
<div class="Wrap">_x000D_
  <div class="Flex1">_x000D_
    <input type="submit" name="test2" value="TEST 2">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
FLEX 1 1 0%_x000D_
<div class="Wrap">_x000D_
  <div class="Flex110x">_x000D_
    <input type="submit" name="test3" value="TEST 3">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

COMPATIBILITY

It should be noted that this fails because some browsers have failed to adhere to the specification.

Browsers that use the full flex specification:

  • Firefox - ?
  • Edge - ? (I know, I was shocked too.)
  • Chrome - x
  • Brave - x
  • Opera - x
  • IE - (lol, it works without length unit but not with one.)

UPDATE 2019

Latest versions of Chrome seem to have finally rectified this issue but other browsers still have not.

Tested and working in Chrome Ver 74.

JavaScript unit test tools for TDD

YUI has a testing framework as well. This video from Yahoo! Theater is a nice introduction, although there are a lot of basics about TDD up front.

This framework is generic and can be run against any JavaScript or JS library.

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

this post was made a while ago, but it provides an answer that did not solve the problem regarding reaching the limit of requests in an iteration for me, so I publish this, to help who else has not served.

My environment happened in Ionic 3.

Instead of making a "pause" in the iteration, I ocurred the idea of ??iterating with a timer, this timer has the particularity of executing the code that would go in the iteration, but will run every so often until it is reached the maximum count of the "Array" in which we want to iterate.

In other words, we will consult the Google API in a certain time so that it does not exceed the limit allowed in milliseconds.

// Code to start the timer
    this.count= 0;
    let loading = this.loadingCtrl.create({
      content: 'Buscando los mejores servicios...'
    });
    loading.present();
    this.interval = setInterval(() => this.getDistancias(loading), 40);
// Function that runs the timer, that is, query Google API
  getDistancias(loading){
    if(this.count>= this.datos.length){
      clearInterval(this.interval);
    } else {
      var sucursal = this.datos[this.count];
      this.calcularDistancia(this.posicion, new LatLng(parseFloat(sucursal.position.latitude),parseFloat(sucursal.position.longitude)),sucursal.codigo).then(distancia => {
    }).catch(error => {
      console.log('error');
      console.log(error);
    });
    }
    this.count += 1;
  }
  calcularDistancia(miPosicion, markerPosicion, codigo){
    return new Promise(async (resolve,reject) => {
      var service = new google.maps.DistanceMatrixService;
      var distance;
      var duration;
      service.getDistanceMatrix({
        origins: [miPosicion, 'salida'],
        destinations: [markerPosicion, 'llegada'],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status){
        if (status == 'OK') {
          var originList = response.originAddresses;
          var destinationList = response.destinationAddresses;
          try{
            if(response != null && response != undefined){
              distance = response.rows[0].elements[0].distance.value;
              duration = response.rows[0].elements[0].duration.text;
              resolve(distance);
            }
          }catch(error){
            console.log("ERROR GOOGLE");
            console.log(status);
          }
        }
      });
    });
  }

I hope this helps!

I'm sorry for my English, I hope it's not an inconvenience, I had to use the Google translator.

Regards, Leandro.

How to trigger an event in input text after I stop typing/writing?

Use the attribute onkeyup="myFunction()" in the <input> of your html.

Set CFLAGS and CXXFLAGS options using CMake

The easiest solution working fine for me is this:

export CFLAGS=-ggdb
export CXXFLAGS=-ggdb

CMake will append them to all configurations' flags. Just make sure to clear CMake cache.

How to get city name from latitude and longitude coordinates in Google Maps?

Try this

var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);

geocoder.geocode(
{'latLng': latlng}, 
function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var add= results[0].formatted_address ;
                var  value=add.split(",");

                count=value.length;
                country=value[count-1];
                state=value[count-2];
                city=value[count-3];
                alert("city name is: " + city);
            }
            else  {
                alert("address not found");
            }
    }
     else {
        alert("Geocoder failed due to: " + status);
    }
}

);

Capturing image from webcam in java?

I have used JMF on a videoconference application and it worked well on two laptops: one with integrated webcam and another with an old USB webcam. It requires JMF being installed and configured before-hand, but once you're done you can access the hardware via Java code fairly easily.

Entity Framework is Too Slow. What are my options?

From my experience, the problem not with EF, but with ORM approach itself.

In general all ORMs suffers from N+1 problem not optimized queries and etc. My best guess would be to track down queries that causes performance degradation and try to tune-up ORM tool, or rewrite that parts with SPROC.

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Handling a Menu Item Click Event - Android

This code is work for me

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

Where are the Android icon drawables within the SDK?

In android.R.drawable, read more here : http://docs.since2006.com/android/2.1-drawables.php


Simple resource usage :

android:icon="@android:drawable/ic_menu_save"

Simple Java usage :

myMenuItem.setIcon(android.R.drawable.ic_menu_save);

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

WITH CHECK is indeed the default behaviour however it is good practice to include within your coding.

The alternative behaviour is of course to use WITH NOCHECK, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.

How to run SQL in shell script

You can use a heredoc. e.g. from a prompt:

$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

so sqlplus will consume everything up to the EOF marker as stdin.

Casting LinkedHashMap to Complex Object

You can use ObjectMapper.convertValue(), either value by value or even for the whole list. But you need to know the type to convert to:

POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });

this is functionally same as if you did:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);

but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.

How to format date in angularjs

ng-bind="reviewData.dateValue.replace('/Date(','').replace(')/','') | date:'MM/dd/yyyy'"

Use this should work well. :) The reviewData and dateValue fields can be changes as per your parameter rest can be left same

Firebug-like debugger for Google Chrome

Just adding some talking points as someone who uses Firebug / Chrome Inspector every day:

  1. At the time of writing, there's only Google DOM inspector and no it doesn't have all the features of Firebug

  2. Inspector is a 'lite' version of Firebug: The interface is not as good IMO, element inspection in both recent versions is now clunky, but Firebug is still better; I find myself trying to find the love for Chrome (since it's a better, faster browser experience), but for development work, it still just sucks for me.

  3. Live preview / modification of DOM / CSS is still way better in Firebug; calculated CSS and box model view are better in Firebug;

  4. Somehow it's just easier to read/use Firebug maybe because of the ease of navigating, manipulating/modifying the document in several key areas? Who knows. I'm used to the interface and I think Chrome Inspector is not as good although this is a subjective thing I admit.

  5. The Cookies/Net tab are extremely useful to me in Firebug. Maybe Chrome Inspector has this now? Last time I checked it did not, because Chrome updates itself in the background without your intervention (gets your consent by default like all good overlords).

  6. Last point: The day that Google Chrome gets a fully-featured Firebug is the day Firefox basically dies for developers because Firefox had 3 years to make Firefox's layout engine Gecko as fast as WebKit and they didn't. Sorry to put it so bluntly but it's the truth.

You see, now everyone wants to move away from Flash in lieu of jQuery motivated by mobile accessibility and interactivity (iPhone, iPad, Android) and JavaScript is 'suddenly' a big deal (that's sarcasm), so that ship has sailed, Firefox. And that makes me sad, as a Mozilla fanperson. Chrome is simply a better browser until Firefox upgrades their JavaScript engine.

running php script (php function) in linux bash

There are two ways you can do this. One is the one already mentioned, i.e.:

php -f filename.php

The second option is making the script executable (chmod +x filename.php) and adding the following line to the top of your .php file:

#!/path/to/php

I'm not sure though if a webserver likes this, so if you also want to use the .php file in a website, that might not be the best idea. Still, if you're just writing some kind of script, it is easier to type ./path/to/phpfile.php than having to type php -f /path/to/phpfile.php every time.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

To get multiple stats, collapse the index, and retain column names:

df = df.groupby(['col1','col2']).agg(['mean', 'count'])
df.columns = [ ' '.join(str(i) for i in col) for col in df.columns]
df.reset_index(inplace=True)
df

Produces:

**enter image description here**

mkdir's "-p" option

Note that -p is an argument to the mkdir command specifically, not the whole of Unix. Every command can have whatever arguments it needs.

In this case it means "parents", meaning mkdir will create a directory and any parents that don't already exist.

How can I center text (horizontally and vertically) inside a div block?

This works for me (tested OK!):

HTML:

<div class="mydiv">
    <p>Item to be centered!</p>
</div>

CSS:

.mydiv {
    height: 100%; /* Or other */
    position: relative;
}

.mydiv p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%); /* To compensate own width and height */
}

You can choose other values than 50%. For example, 25% to center at 25% of parent.

How to bind bootstrap popover on dynamic elements

This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.

HTML:

<div rel="this-should-be-the-target">
</div>

JQuery:

$(function() {
    var targetElement = 'rel="this-should-be-the-target"';
    initPopover(targetElement, "Test Popover Content");

    // use this line if you want it to show by default
    $(targetElement).popover('show');
    
    function initPopover(target, popOverContent) {
        $(target).each(function(i, obj) {
            $(this).popover({
                placement : 'auto',
                trigger : 'hover',
                "html": true,
                content: popOverContent
            });
         });
     }
});

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

Could not find or load main class

I had almost the same problem, but with the following variation:

  1. I've imported a ready-to-use maven project into Eclipse IDE from PC1 (project was working there perfectly) to another PC2
  2. when was trying to run the project on PC 2 got the same error "Could not find or load main class"
  3. I've checked PATH variable (it had many values in my case) and added JAVA_HOME variable (in my case it was JAVA_HOME = C:\Program Files\Java\jdk1.7.0_03) After restarting Ecplise it still didn't work
  4. I've tried to run simple HelloWorld.java on PC2 (in another project) - it worked
  5. So I've added HelloWorld class to the imported recently project, executed it there and - huh - my main class in that project started to run normally also.

That's quite odd behavour, I cannot completely understand it. Hope It'll help somebody. too.

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

Matplotlib - global legend and title aside subplots

For legend labels can use something like below. Legendlabels are the plot lines saved. modFreq are where the name of the actual labels corresponding to the plot lines. Then the third parameter is the location of the legend. Lastly, you can pass in any arguments as I've down here but mainly need the first three. Also, you are supposed to if you set the labels correctly in the plot command. To just call legend with the location parameter and it finds the labels in each of the lines. I have had better luck making my own legend as below. Seems to work in all cases where have never seemed to get the other way going properly. If you don't understand let me know:

legendLabels = []
for i in range(modSize):
    legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]       
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)

You can also use the leg to change fontsizes or nearly any parameter of the legend.

Global title as stated in the above comment can be done with adding text per the link provided: http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html

f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
       verticalalignment='top')

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

Eclipse - Unable to install breakpoint due to missing line number attributes

I ran into this problem as well. I am using an ant build script. I am working on a legacy application so I am using jdk version 1.4.2. This used to work so I started looking around. I noticed that under the Debug configuration on the JRE tab the version of Java had been set to 1.7. Once I changed it back to 1.4 it worked.

I hope this helps.

CSS submit button weird rendering on iPad/iPhone

Add this code into the css file:

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

This will help.

Number of days in particular month of particular year?

This worked fine for me.

This is a Sample Output

import java.util.*;

public class DaysInMonth { 

    public static void main(String args []) { 

        Scanner input = new Scanner(System.in); 
        System.out.print("Enter a year:"); 

        int year = input.nextInt(); //Moved here to get input after the question is asked 

        System.out.print("Enter a month:"); 
        int month = input.nextInt(); //Moved here to get input after the question is asked 

        int days = 0; //changed so that it just initializes the variable to zero
        boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); 

        switch (month) { 
            case 1: 
                days = 31; 
                break; 
            case 2: 
                if (isLeapYear) 
                    days = 29; 
                else 
                    days = 28; 
                break; 
            case 3: 
                days = 31; 
                break; 
            case 4: 
                days = 30; 
                break; 
            case 5: 
                days = 31; 
                break; 
            case 6: 
                days = 30; 
                break; 
            case 7: 
                days = 31; 
                break; 
            case 8: 
                days = 31; 
                break; 
            case 9: 
                days = 30; 
                break; 
            case 10: 
                days = 31; 
                break; 
            case 11: 
                days = 30; 
                break; 
            case 12: 
                days = 31; 
                break; 
            default: 
                String response = "Have a Look at what you've done and try again";
                System.out.println(response); 
                System.exit(0); 
        } 

        String response = "There are " + days + " Days in Month " + month + " of Year " + year + ".\n"; 
        System.out.println(response); // new line to show the result to the screen. 
    } 
} //[email protected]

"detached entity passed to persist error" with JPA/EJB code

if you use to generate the id = GenerationType.AUTO strategy in your entity.

Replaces user.setId (1) by user.setId (null), and the problem is solved.

Could not find any resources appropriate for the specified culture or the neutral culture

Yet another cause: if your namespace has a hyphen ("-"), then it will build and run correctly, but the resource won't be accessible. Namespaces (identifiers) aren't supposed to have hyphens, but this doesn't appear to be enforced anywhere except in loading resources. This has burned me twice over the decade.

Setting the character encoding in form submit for Internet Explorer

I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.

Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.

<form accept-charset="ISO-8859-15">
  ...
</form>

So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.

Including JavaScript class definition from another file in Node.js

You can simply do this:

user.js

class User {
    //...
}

module.exports = User

server.js

const User = require('./user.js')

// Instantiate User:
let user = new User()

This is called CommonJS module.

Export multiple values

Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:

user.js

class User {}

exports.User = User //  Spot the difference

server.js

const {User} = require('./user.js') //  Destructure on import

// Instantiate User:
let user = new User()

ES Modules

Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.

?? Don't use globals, it creates potential conflicts with the future code.

Python: how can I check whether an object is of type datetime.date?

right way is

import datetime
isinstance(x, datetime.date)

When I try this on my machine it works fine. You need to look into why datetime.date is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?

Import and Export Excel - What is the best library?

I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

UITableView Separator line

Swift 3/4

Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell):

let separatorLine = UIView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2))
separatorLine.backgroundColor = .blue
addSubview(separatorLine)

in viewDidLoad method:

tableView.separatorStyle = .none

SQL SERVER DATETIME FORMAT

This is my favorite use of 112 and 114

select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate() 

112 + 114 or YYYYMMDDHHMMSSMSS'

Result:

Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS

20171016083349100

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

If you have content with height unknown but you know the height the of container. The following solution works extremely well.

HTML

<div class="center-test">
    <span></span><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
    Nesciunt obcaecati maiores nulla praesentium amet explicabo ex iste asperiores 
    nisi porro sequi eaque rerum necessitatibus molestias architecto eum velit 
    recusandae ratione.</p>
</div>

CSS

.center-test { 
   width: 300px; 
   height: 300px; 
   text-align: 
   center; 
   background-color: #333; 
}
.center-test span { 
   height: 300px; 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
 }
.center-test p { 
   display: inline-block; 
   zoom: 1; 
   *display: inline; 
   vertical-align: middle; 
   color: #fff; 
 }

EXAMPLE http://jsfiddle.net/thenewconfection/eYtVN/

One gotcha for newby's to display: inline-block; [span] and [p] have no html white space so that the span then doesn't take up any space. Also I've added in the CSS hack for display inline-block for IE. Hope this helps someone!

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also try this.

consider today's date '28 Dec 2018'(for example)

 this.date = new Date().toISOString().slice(0,10); 

new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)

toISOString will convert to : 2018-12-28T06:15:27.479Z

slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.

Android TextView Text not getting wrapped

For my case removing input type did the trick, i was using android:inputType="textPostalAddress" due to that my textview was sticked to one line and was not wrapping, removing this fixed the issue.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Convert List to IEnumerable or Iquerable, add using System.LINQ.Dynamic namespace, then u can mention the property names in comma seperated string to OrderBy Method which comes by default from System.LINQ.Dynamic.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

If you have web.xml then

HTML/JSP

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
</form>

web.xml

<servlet>
        <display-name>Servlet Name</display-name>
        <servlet-name>myservlet</servlet-name>
        <servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/myservlet</url-pattern>
</servlet-mapping>

Java SomeController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Write your code below");
}

What is the difference between <html lang="en"> and <html lang="en-US">?

Well, the first question is easy. There are many ens (Englishes) but (mostly) only one US English. One would guess there are en-CN, en-GB, en-AU. Guess there might even be Austrian English but that's more yes you can than yes there is.

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

SQL Server remove milliseconds from datetime

There's more than one way to do it:

select 1 where datediff(second, '2010-07-20 03:21:52', '2010-07-20 03:21:52.577') >= 0

or

select *
from table
where datediff(second, '2010-07-20 03:21:52', date) >= 0 

one less function call, but you have to be beware of overflowing the max integer if the dates are too far apart.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

I had this issue once. It turned out to be database query issue. After re-create tables and index it has been fixed.

Although it says proxy error, when you look at server log, it shows execute query timeout. This is what I had before and how I solved it.

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

What is the App_Data folder used for in Visual Studio?

in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.

How to stop VBA code running?

How about Application.EnableCancelKey - Use the Esc button

On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000    ' Do something 1,000,000 times (long!)
    ' do something here
Next x

handleCancel:
If Err = 18 Then
    MsgBox "You cancelled"
End If

Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx

Is there any way to prevent input type="number" getting negative values?

This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.

Markup:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

Javascript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

How to monitor the memory usage of Node.js?

Also, if you'd like to know global memory rather than node process':

var os = require('os');

os.freemem();
os.totalmem();

See documentation

Browser Caching of CSS files

To the first part of your question - yes, browsers cache css files (if this is not disabled by browser's configuration). Many browsers have key combination to reload a page without a cache. If you made changes to css and want users to see them immediately instead of waiting next time when browser reloads the files without caching, you can change the way CSS ir served by adding some parameters to the url like this:

/style.css?modified=20012009

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Convert number to varchar in SQL with formatting

declare @t  tinyint
set @t =3
select right(replicate('0', 2) + cast(@t as varchar),2)

Ditto: on the cripping effect for numbers > 99

If you want to cater for 1-255 then you could use

select right(replicate('0', 2) + cast(@t as varchar),3)

But this would give you 001, 010, 100 etc

Set cURL to use local virtual hosts

For setting up virtual hosts on Apache http-servers that are not yet connected via DNS, I like to use:

curl -s --connect-to ::host-name: http://project1.loc/post.json

Where host-name ist the IP address or the DNS name of the machine on which the web-server is running. This also works well for https-Sites.

Center an element in Bootstrap 4 Navbar

Why Not using bootstrap utilities. here is the code

    <nav class="navbar navbar-expand-md bg-light navbar-light fixed-top">
  <!-- Brand -->
  <a class="navbar-brand" href="#"><img src="your-logo"/></a>

  <!-- Toggler/collapsibe Button -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>

  <!-- Navbar links -->
  <div class="collapse navbar-collapse mx-auto justify-content-md-center" id="collapsibleNavbar" >
    <ul class="navbar-nav col-md-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li> 
    </ul>
  </div> 
</nav>

How to count the number of occurrences of a character in an Oracle varchar value?

Here you go:

select length('123-345-566') - length(replace('123-345-566','-',null)) 
from dual;

Technically, if the string you want to check contains only the character you want to count, the above query will return NULL; the following query will give the correct answer in all cases:

select coalesce(length('123-345-566') - length(replace('123-345-566','-',null)), length('123-345-566'), 0) 
from dual;

The final 0 in coalesce catches the case where you're counting in an empty string (i.e. NULL, because length(NULL) = NULL in ORACLE).

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

Bash write to file without echo?

Interestingly, I had this problem too...so I search and found this thread....I found that this worked well for me:

echo "Hello world" | grep "" > test.txt

However - When I had closed that terminal and opened a new one, I discovered that the problem went away! I wish I had kept that terminal open to compare the settings. My current terminal is a bash shell. Not sure what caused that issue to begin with - anyone?

How can I delete a newline if it is the last character in a file?

gawk

   awk '{q=p;p=$0}NR>1{print q}END{ORS = ""; print p}' file

Set a DateTime database field to "Now"

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

node.js require all files in a folder?

Require all files from routes folder and apply as middleware. No external modules needed.

// require
const path = require("path");
const { readdirSync } = require("fs");

// apply as middleware
readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

ng serve not detecting file changes automatically

I discovered that the dist/ folder in the project was owned by root. That is why sudo ng serve does see the changes when ng serve does not.

I removed the dist/ folder sudo rm -R dist/ and rebuild it as current user by starting the dev server ng serve and all worked again.

How to remove all white spaces in java

Cant you just use String.replace(" ", "");

Sqlite primary key on multiple columns

PRIMARY KEY (id, name) didn't work for me. Adding a constraint did the job instead.

CREATE TABLE IF NOT EXISTS customer (
    id INTEGER, name TEXT,
    user INTEGER,
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

Localhost not working in chrome and firefox

In case the browser LAN proxy setting solution doesn't work for you:

As mentioned in this similar Q&A How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Simply changing the port number of your web project can be a quick fix.

enter image description here

Send multipart/form-data files with angular using $http

Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

Java Initialize an int array in a constructor

You could either do:

public class Data {
    private int[] data;

    public Data() {
        data = new int[]{0, 0, 0};
    }
}

Which initializes data in the constructor, or:

public class Data {
    private int[] data = new int[]{0, 0, 0};

    public Data() {
        // data already initialised
    }
}

Which initializes data before the code in the constructor is executed.

How to execute raw SQL in Flask-SQLAlchemy app

You can get the results of SELECT SQL queries using from_statement() and text() as shown here. You don't have to deal with tuples this way. As an example for a class User having the table name users you can try,

from sqlalchemy.sql import text

user = session.query(User).from_statement(
    text("""SELECT * FROM users where name=:name""")
).params(name="ed").all()

return user

Batch file to move files to another directory

/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting

Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get

Try:

move files\*.txt \ 

Edit: Try:

move \files\*.txt \ 

Edit 2:

move C:\files\*.txt C:\txt

Get only records created today in laravel

Laravel ^5.6 - Query Scopes

For readability purposes i use query scope, makes my code more declarative.

scope query

namespace App\Models;

use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    // ...

    /**
     * Scope a query to only include today's entries.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCreatedToday($query)
    {
        return $query->where('created_at', '>=', Carbon::today());
    }

    // ...
}

example of usage

MyModel::createdToday()->get()

SQL generated

Sql      : select * from "my_models" where "created_at" >= ?

Bindings : ["2019-10-22T00:00:00.000000Z"]

How do I remove javascript validation from my eclipse project?

I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.

That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.

  1. Right-click your project.
  2. Navigate to: Properties ? JavaScript ? Include Path
  3. Select Source tab. (It looks identical to Java Build Path Source tab.)
  4. Expand JavaScript source folder.
  5. Highlight Excluded pattern.
  6. Press the Edit button.
  7. Press the Add button next to Exclusion patterns box.
  8. You may either type Ant-style wildcard pattern, or click Browse button to mention the JavaScript source by name.

The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope file. Do not forget to add it to your SCM.

Here is how configuration looks with jQuery files removed from validation:

Eclipse - Project Properties - JavaScript - Include Path

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How do you get the current time of day?

I think this code will solve your problem

DateTime.Now.ToString("HH:mm")

Objective-C: Calling selectors with multiple arguments

In Objective-C, a selector's signature consists of:

  1. The name of the method (in this case it would be 'myTest') (required)
  2. A ':' (colon) following the method name if the method has an input.
  3. A name and ':' for every additional input.

Selectors have no knowledge of:

  1. The input types
  2. The method's return type.

Here's a class implementation where performMethodsViaSelectors method performs the other class methods by way of selectors:

@implementation ClassForSelectors
- (void) fooNoInputs {
    NSLog(@"Does nothing");
}
- (void) fooOneIput:(NSString*) first {
    NSLog(@"Logs %@", first);
}
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
    NSLog(@"Logs %@ then %@", first, second);
}
- (void) performMethodsViaSelectors {
    [self performSelector:@selector(fooNoInputs)];
    [self performSelector:@selector(fooOneInput:) withObject:@"first"];
    [self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"];
}
@end

The method you want to create a selector for has a single input, so you would create a selector for it like so:

SEL myTestSelector = @selector(myTest:);

#ifdef replacement in the Swift language

XCODE 9 AND ABOVE

#if DEVELOP
    //
#elseif PRODCTN
    //
#else
    //
#endif

How can I find a specific file from a Linux terminal?

Try this (via a shell):

update db
locate index.html

Or:

find /var -iname "index.html"

Replace /var with your best guess as to the directory it is in but avoid starting from /

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How To Remove Outline Border From Input Button

Removing the outline is an accessibility nightmare. People tabbing using keyboards will never know what item they're on.

Best to leave it, as most clicked buttons will take you somewhere anyway, or if you HAVE to remove the outline then isolate it a specific class name.

.no-outline {
  outline: none;
}

Then you can apply that class whenever you need to.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.

For the case anybody likes to use the refactored/modernized code I put it back into the community here.

/// <summary>
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// </summary>
public class NetworkConfigurator
{
    /// <summary>
    /// Set's a new IP Address and it's Submask of the local machine
    /// </summary>
    /// <param name="ipAddress">The IP Address</param>
    /// <param name="subnetMask">The Submask IP Address</param>
    /// <param name="gateway">The gateway.</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public void SetIP(string ipAddress, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
                        {
                            if (!String.IsNullOrEmpty(ipAddress))
                            {
                                newIP["IPAddress"] = new[] { ipAddress };
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = new[] { subnetMask };
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Set's the DNS Server of the local machine
    /// </summary>
    /// <param name="nic">NIC address</param>
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public void SetNameservers(string nic, string dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}

How can I check for "undefined" in JavaScript?

You can use typeof, like this:

if (typeof something != "undefined") {
    // ...
}

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.

Sublime Text 2 Code Formatting

I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)

There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

Repeat string to certain length

How about string * (length / len(string)) + string[0:(length % len(string))]

Console app arguments, how arguments are passed to Main method

you can pass also by making function and then in this function you call main method and pass argument to main method

static int Main(string[] args)
    {


        foreach (string b in args)
            Console.WriteLine(b+"   ");

        Console.ReadKey();
        aa();
        return 0;

    }
    public static void aa()
    {
        string []aaa={"Adil"};

        Console.WriteLine(Main(aaa));
    }

Running multiple commands in one line in shell

You are using | (pipe) to direct the output of a command into another command. What you are looking for is && operator to execute the next command only if the previous one succeeded:

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Or

cp /templates/apple /templates/used && mv /templates/apple /templates/inuse

To summarize (non-exhaustively) bash's command operators/separators:

  • | pipes (pipelines) the standard output (stdout) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen to be.
  • |&pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
  • && executes the right-hand command of && only if the previous one succeeded.
  • || executes the right-hand command of || only it the previous one failed.
  • ; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How to call a C# function from JavaScript?

If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

I know this is late to the game, but I wanted to share in case it helps someone.

Your exact situation may not apply, however I had a similar situation and setting the File attribute helped.

Try to set the File attribute to Normal:

var path = Server.MapPath("~/App_Data/file.txt");
File.SetAttributes(path, FileAttributes.Normal);
System.IO.File.WriteAllText(path, "Hello World");

I hope this helps someone.

Show diff between commits

To see the difference between:

Your working copy and staging area:

% git diff

Staging area and the latest commit:

% git diff --staged

Your working copy and commit 4ac0a6733:

% git diff 4ac0a6733

Commit 4ac0a6733 and the latest commit:

% git diff 4ac0a6733 HEAD

Commit 4ac0a6733 and commit 826793951

% git diff 4ac0a6733 826793951

For more explanation see the official documentation.

How to open my files in data_folder with pandas using relative path?

Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:

pd.read_csv('../../../data_folder/data.csv')

Will go 3 levels up and then into a data_folder (assuming it's there) Or

pd.read_csv('data_folder/data.csv')

assuming your data_folder is in the same directory as your .py file.

How to query for Xml values and attributes from table in SQL Server?

I don't understand why some people are suggesting using cross apply or outer apply to convert the xml into a table of values. For me, that just brought back way too much data.

Here's my example of how you'd create an xml object, then turn it into a table.

(I've added spaces in my xml string, just to make it easier to read.)

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

replace String with another in java

The replace method is what you're looking for.

For example:

String replacedString = someString.replace("HelloBrother", "Brother");

What is the strict aliasing rule?

Strict aliasing is not allowing different pointer types to the same data.

This article should help you understand the issue in full detail.

Eclipse: The declared package does not match the expected package

I happened to have the same problem just now. However, the first few answers don't work for me.I propose a solution:change the .classpath file.For example,you can define the classpathentry node's path like this: path="src/prefix1/java" or path="src/prefix1/resources". Hope it can help.

How to check if a file exists before creating a new file

I just saw this test:

bool getFileExists(const TCHAR *file)
{ 
  return (GetFileAttributes(file) != 0xFFFFFFFF);
}