Programs & Examples On #Erp

Enterprise Resource Planning (ERP) intends to provide a complete view of business by integrating accounting, human resources, supply chain management, capacity planning, production scheduling, customer relationship management, sales planning and more.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How to setup virtual environment for Python in VS Code?

P.S:

  • I have been using vs code for a while now and found an another way to show virtual environments in vs code.

  • Go to the parent folder in which venv is there through command prompt.

  • Type code . and Enter. [Working on both windows and linux for me.]

  • That should also show the virtual environments present in that folder.

Original Answer

I almost run into same problem everytime I am working on VS-Code using venv. I follow below steps, hope it helps:

  1. Go to File > preferences > Settings.

  2. Click on Workspace settings.

  3. Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json , click on that.

  4. Update "python.pythonPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.pythonPath": "Your_venv_path/Scripts/python.exe" under workspace settings.

  5. Restart VSCode incase if it still doesn't show your venv.

Pylint "unresolved import" error in Visual Studio Code

That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.

The quick way to fix is it provide the interpreter path to the main folder.

Press Command + Shift + P (or Ctrl + Shift + P on most other systems).

Type Python interpreter

Select the path where you installed Python in from the options available.

HTTP Error 500.30 - ANCM In-Process Start Failure

Make sure that your *.deps.js json file copied correctly to the deployed location

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

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

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

Flutter - The method was called on null

You should declare your method first in void initState(), so when the first time pages has been loaded, it will init your method first, hope it can help

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I ran into this problem on NetBeans when working with a ready-made project from this Murach JSP book. The problem was caused by using the 5.1.23 Connector J with a MySQL 8.0.13 Database. I needed to replace the old driver with a new one. After downloading the Connector J, this took three steps.

How to replace NetBeans project Connector J:

  1. Download the current Connector J from here. Then copy it in your OS.

  2. In NetBeans, click on the Files tab which is next to the Projects tab. Find the mysql-connector-java-5.1.23.jar or whatever old connector you have. Delete this old connector. Paste in the new Connector.

  3. Click on the Projects tab. Navigate to the Libraries folder. Delete the old mysql connector. Right click on the Libraries folder. Select Add Jar / Folder. Navigate to the location where you put the new connector, and select open.

  4. In the Project tab, right click on the project. Select Resolve Data Sources on the bottom of the popup menu. Click on Add Connection. At this point NetBeans skips forward and assumes you want to use the old connector. Click the Back button to get back to the skipped window. Remove the old connector, and add the new connector. Click Next and Test Connection to make sure it works.

For video reference, I found this to be useful. For IntelliJ IDEA, I found this to be useful.

Pyspark: Filter dataframe based on multiple conditions

You can also write like below (without pyspark.sql.functions):

df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()

Result:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

setAllowUrlEncodedSlash(true) didn't work for me. Still internal method isNormalized return false when having double slash.

I replaced StrictHttpFirewall with DefaultHttpFirewall by having the following code only:

@Bean
public HttpFirewall defaultHttpFirewall() {
    return new DefaultHttpFirewall();
}

Working well for me.
Any risk by using DefaultHttpFirewall?

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Issue in installing php7.2-mcrypt

sudo apt-get install php-pear php7.x-dev

x is your php version like 7.2 the php7.2-dev

apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1 

then add "extension=mcrypt.so" in "/etc/php/7.2/apache2/php.ini"

here php.ini is depends on your php installatio and apache used php version.

db.collection is not a function when using MongoClient v3.0

For people on version 3.0 of the MongoDB native NodeJS driver:

(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)

In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:

MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});

According to the changelog for 3.0 you now get a client object containing the database object instead:

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});

The close() method has also been moved to the client. The code in the question can therefore be translated to:

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 

Exception : AAPT2 error: check logs for details

Seeing your logs :

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ... 1 more Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:454) at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:411) at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:332) at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)

I feel some PNG files are corrupted and were not parsed. Sometimes the images have an extension but are not real PNG.

You can check if the images in your project are real PNGs with the below command :

find . -type f -name "*.png" | xargs -L 1 -I{} file  -I {} | grep -v 'image/png; charset=binary$'

After getting the list use this site to convert them to PNG. Then check your build again.

No provider for HttpClient

You have not provided providers in your module:

<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [ HttpClientModule, ... ]
  // ...
})
export class MyModule { /* ... */ }

Using HttpClient in Tests

You will need to add the HttpClientTestingModule to the TestBed configuration when running ng test and getting the "No provider for HttpClient" error:

// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

describe('HttpClient testing', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    // Inject the http service and test controller for each test
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('works', () => {
  });
});

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

I had the same issue today. I solve this problem by removing any PATH in .bashrc for older rvm.

ERROR in ./node_modules/css-loader?

I tried both

npm rebuild node-sass

and

npm install --save node-sass

Later by seeing EACCESS, i checked the folder permission of /node_modules, which was not 777 permission

Then I gave

chmod -R 777 *

-R for recursively(setting the same permission not in the dir but also inside nested sub dir) * is for all files in current directory

What is file permission

To check for permission you can use

ls -l

If u don't know about it, first see here, then check the url

Every file and directory has permission of 'rwx'(read, write, execute). and if 'x' permission is not there, then you can not execture, if no 'w', you can not write into the file. if some thing is missiing it will show in place of r/w/x with '-'. So, if 'x' permission is not there, it will show like 'rw-'

And there will be 3 category of user Owner(who created the file/directory), Group(some people who shares same permission and user previlege), Others(general public)

So 1st letter is 'd'(if it is a directory) or '-'(if it is not a directory), followed by rwx for owner, followed by for group, followed by other

drwxrwxrwx

For example, for 'node_modules'directory I want to give permission to owner all permission and for rest only read, then it will be

drwxr--r--

And about the number assume for 'r/w/x' it is 1 and for '-' it is 0, 777, first 7 is for owner, followed by group, followed by other

Let's assume the permission is rwxr-xrw-

Now 'rwx' is like '111' and it's equivalent decimal is 1*2^2+1*2^1+1*2^0=7

Now 'r-x' is like '101' and it's equivalent decimal is 1*2^2+0*2^1+1*2^0=5

Now 'rw-' is like '110' and it's equivalent decimal is 1*2^2+1*2^1+0*2^0=6

So, it will be 756

webpack: Module not found: Error: Can't resolve (with relative path)

I met this problem with typescript but forgot to add ts and tsx suffix to resolve entry.

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
};

This does the job for me

VSCode cannot find module '@angular/core' or any other modules

The fix for me was to import the entire project. For those who have this problem in 2019 please check if you have imported the entire project not a part of the project.

React Router Pass Param to Component

Use render method:

<Route exact path="/details/:id" render={(props)=>{
    <DetailsPage id={props.match.params.id}/>
}} />

And you should be able to access the id using:

this.props.id

Inside the DetailsPage component

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Only on Firefox "Loading failed for the <script> with source"

Today I ran into the exact same problem while working on a progressive web app (PWA) page and deleting some cache and service worker data for that page from Firefox. The dev console reported that none of the 4 Javascript files on the page would load anymore. The problem persisted in Safe mode, so it was not an add-on issue. The same script files loaded fine from other web pages on the same website. No amount of clearing the Firefox cache or wiping web page data from Firefox would help, nor would rebooting the Windows 10 PC. Chrome all the time worked fine on the problem page. In the end I did a restore of the entire Firefox profile folder from a day-old backup, and the problem was immediately gone, so it was not a problem with my PWA app. Apparently something in Firefox got corrupted.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I had the same problem and which got resolved by using ./ before the directory name in my node.js app, i.e.

app.use(express.static('./public'));

Docker CE on RHEL - Requires: container-selinux >= 2.9

As with other answers, adding the "extras" subscribed channels to a CentOS 7 Spacewalk deployment solves this problem as well.

Angular 4 Pipe Filter

I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
    transform(array: Array<Object>, filter: Object): any {
        let notAllKeysUndefined = false;
        let newArray = [];

        if(array.length > 0) {
            for (let k in filter){
                if (filter.hasOwnProperty(k)) {
                    if(filter[k] != undefined && filter[k] != '') {
                        for (let i = 0; i < array.length; i++) {
                            let filterRule = filter[k];

                            if(typeof filterRule === 'object') {
                                for(let fkey in filterRule) {
                                    if (filter[k].hasOwnProperty(fkey)) {
                                        if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
                                            if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
                                                newArray.push(array[i]);
                                            }
                                            notAllKeysUndefined = true;
                                        }
                                    }
                                }
                            } else {
                                if(this.shouldPushInArray(array[i][k], filter[k])) {
                                    newArray.push(array[i]);
                                }
                                notAllKeysUndefined = true;
                            }
                        }
                    }
                }
            }
            if(notAllKeysUndefined) {
                return newArray;
            }
        }

        return array;
    }

    private shouldPushInArray(item, filter) {
        if(typeof filter !== 'string') {
            item = item.toString();
            filter = filter.toString();
        }

        // Filter main logic
        item = item.toLowerCase();
        filter = filter.toLowerCase();
        if(item.indexOf(filter) !== -1) {
            return true;
        }
        return false;
    }
}

How to completely uninstall python 2.7.13 on Ubuntu 16.04

This is what I have after doing purge of all the python versions and reinstalling only 3.6.

root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02) 
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.

Also the pip and pip3 commands are totally f up:

root@esp32:/# pip
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

root@esp32:/# pip3
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip._internal.cli.main import main
  File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.

More than one file was found with OS independent path 'META-INF/LICENSE'

I had a similar problem. i was getting the error message -

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

More than one file was found with OS independent path 'javax/annotation/WillCloseWhenClosed.java'

As stated in some of the answers above, using the below code works

'packagingOptions {
       exclude 'allclasses-frame.html'
    }'

But i was getting this error for 20 different files, so after excluding 20 files, i stopped and tried to find a decent solution. I had also encountered the

'Unable to execute dex: Multiple dex files' error.

I finally managed to solve this.

Firstly (as in my case WillCloseWhenClosed.java was the duplicate file), in android studio you have an option of 'search everywhere'. Write and search for the file there. There i found multiple instances of this file. So i clicked on both instances and saw their location by right clicking on the file and seeing its location when they opened in android studio.

Secondly, I figured out that i had some dependencies in gradle file. I was using the below code

dependencies {
    compile 'com.google.api-client:google-api-client:1.23.0'
}

and also i had their same zip packages in the location :\Users\user\AndroidStudioProjects\git\appname\app\libs\google-http-client-1.23!.

So this was redundant and thats why gradle is finding 2 files. So i deleted my zip packages and it solved the errors for me. Be carefull while doing this. You have to figure out which is the correct file or package to be deleted.

Thirdly, gradle also makes a zip of these bug files in this location (At least for me it made) - C:\Program Files\Android\Android Studio\gradle\m2repository\com\google\code\findbugs\jsr305\1.3.9\jsr305-1.3.9.jar!

so i went and deleted the jsr305-1.3.9.jar file from here also.

If you are still confused, just go the 'search everywhere' in android studio, find instances of your file there and you would have to delete one of them. Take your time and figure out which one.

Kubernetes service external ip pending

I created a single node k8s cluster using kubeadm. When i tried PortForward and kubectl proxy, it showed external IP as pending.

$ kubectl get svc -n argocd argocd-server
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
argocd-server   LoadBalancer   10.107.37.153   <pending>     80:30047/TCP,443:31307/TCP   110s

In my case I've patched the service like this:

kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'

After this, it started serving over the public IP

$ kubectl get svc argo-ui -n argo
NAME      TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE
argo-ui   LoadBalancer   10.103.219.8   172.31.71.218   80:30981/TCP   7m50s

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How to check if the docker engine and a docker container are running?

How I check in SSH.Run:

systemctl

If response: Failed to get D-Bus connection: Operation not permitted

Its a docker or WSL container.

Error: the entity type requires a primary key

The entity type 'DisplayFormatAttribute' requires a primary key to be defined.

In my case I figured out the problem was that I used properties like this:

public string LastName { get; set; }  //OK
public string Address { get; set; }   //OK 
public string State { get; set; }     //OK
public int? Zip { get; set; }         //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; }  // NOT OK

Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.

Running Tensorflow in Jupyter Notebook

I have found a fairly simple way to do this.

Initially, through your Anaconda Prompt, you can follow the steps in this official Tensorflow site - here. You have to follow the steps as is, no deviation.

Later, you open the Anaconda Navigator. In Anaconda Navigator, go to Applications On --- section. Select the drop down list, after following above steps you must see an entry - tensorflow into it. Select tensorflow and let the environment load.

Then, select Jupyter Notebook in this new context, and install it, let the installation get over.

After that you can run the Jupyter notebook like the regular notebook in tensorflow environment.

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

Visual Studio 2017 - Git failed with a fatal error

I opened Credential Manager in Windows (not Visual Studio), selected "Windows Credentials", found my git:https//stash....com Generic Credential, clicked the bubble arrow down to make visible the User name and Password fields with Edit button. Clicked Edit, and put in my correct password there. Then started work right after that, no need to close anything.

Switch php versions on commandline ubuntu 16.04

I think you should try this

From php5.6 to php7.1

sudo a2dismod php5.6
sudo a2enmod php7.1
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php7.1
sudo update-alternatives --set phar /usr/bin/phar7.1
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1

From php7.1 to php5.6

sudo a2dismod php7.1
sudo a2enmod php5.6
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6

Google API authentication: Not valid origin for the client

Clear your browser cache. Started getting this error in Chrome and then I created a new client id and was still getting the issue. Opened firefox and it worked, so I cleared the cache on Chrome and it started working.

The default XML namespace of the project must be the MSBuild XML namespace

If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017 Agent queue.

How does the "view" method work in PyTorch?

I really liked @Jadiel de Armas examples.

I would like to add a small insight to how elements are ordered for .view(...)

  • For a Tensor with shape (a,b,c), the order of it's elements are determined by a numbering system: where the first digit has a numbers, second digit has b numbers and third digit has c numbers.
  • The mapping of the elements in the new Tensor returned by .view(...) preserves this order of the original Tensor.

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Vue.js - How to properly watch for nested data

Tracking individual changed items in a list

If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      // NOTE: For mutated objects, newVal and oldVal will be identical.
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

If your list isn't populated straight away (like in the original question), you can move the logic out of created to wherever needed, e.g. inside the .then() block.

Watching a changing list

If your list itself updates to have new or removed items, I've developed a useful pattern that "shallow" watches the list itself, and dynamically watches/unwatches items as the list changes:

// NOTE: This example uses Lodash (_.differenceBy and _.pull) to compare lists
//       and remove list items. The same result could be achieved with lots of
//       list.indexOf(...) if you need to avoid external libraries.

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
    watchTracker: [],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      console.log(newVal);
    },
    updateWatchers () {
      // Helper function for comparing list items to the "watchTracker".
      const getItem = (val) => val.item || val;

      // Items that aren't already watched: watch and add to watched list.
      _.differenceBy(this.list, this.watchTracker, getItem).forEach((item) => {
        const unwatch = this.$watch(() => item, this.handleChange, {deep: true});
        this.watchTracker.push({ item: item, unwatch: unwatch });
        // Uncomment below if adding a new item to the list should count as a "change".
        // this.handleChange(item);
      });

      // Items that no longer exist: unwatch and remove from the watched list.
      _.differenceBy(this.watchTracker, this.list, getItem).forEach((watchObj) => {
        watchObj.unwatch();
        _.pull(this.watchTracker, watchObj);
        // Optionally add any further cleanup in here for when items are removed.
      });
    },
  },
  watch: {
    list () {
      return this.updateWatchers();
    },
  },
  created () {
    return this.updateWatchers();
  },
});

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case this error was specific to the hello-world docker image. I used the nginx image instead of the hello-world image and the error was resolved.

How Spring Security Filter Chain works

Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.

Sequence of execution in Spring Security

  1. WebAsyncManagerIntegrationFilter Provides integration between the SecurityContext and Spring Web's WebAsyncManager.

  2. SecurityContextPersistenceFilter This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
    Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.

  3. HeaderWriterFilter Filter implementation to add headers to the current response.

  4. LogoutFilter If request url is /logout(for default configuration) or if request url mathces RequestMatcher configured in LogoutConfigurer then

    • clears security context.
    • invalidates the session
    • deletes all the cookies with cookie names configured in LogoutConfigurer
    • Redirects to default logout success url / or logout success url configured or invokes logoutSuccessHandler configured.
  5. UsernamePasswordAuthenticationFilter

    • For any request url other than loginProcessingUrl this filter will not process further but filter chain just continues.
    • If requested URL is matches(must be HTTP POST) default /login or matches .loginProcessingUrl() configured in FormLoginConfigurer then UsernamePasswordAuthenticationFilter attempts authentication.
    • default login form parameters are username and password, can be overridden by usernameParameter(String), passwordParameter(String).
    • setting .loginPage() overrides defaults
    • While attempting authentication
      • an Authentication object(UsernamePasswordAuthenticationToken or any implementation of Authentication in case of your custom auth filter) is created.
      • and authenticationManager.authenticate(authToken) will be invoked
      • Note that we can configure any number of AuthenticationProvider authenticate method tries all auth providers and checks any of the auth provider supports authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException.
    • If authentication success session will be created and authenticationSuccessHandler will be invoked which redirects to the target url configured(default is /)
    • If authentication failed user becomes un-authenticated user and chain continues.
  6. SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  7. AnonymousAuthenticationFilter Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication object (AnonymousAuthenticationToken) with granted authority ROLE_ANONYMOUS. Here AnonymousAuthenticationToken facilitates identifying un-authenticated users subsequent requests.

Debug logs
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 
  1. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  2. FilterSecurityInterceptor
    There will be FilterSecurityInterceptor which comes almost last in the filter chain which gets Authentication object from SecurityContext and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers configured in HttpSecurityConfiguration.

Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain

  • Un authenticated user trying to access public resource - Allowed
  • Un authenticated user trying to access secured resource - 401-UnAuthorized
  • Authenticated user trying to access restricted resource(restricted for his role) - 403-Forbidden

Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter,RequestCacheAwareFilter,SessionManagementFilter ...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter it will become entirely different case.


Just For reference. Filters in spring-web and spring-security
Note: refer package name in pic, as there are some other filters from orm and my custom implemented filter.

enter image description here

From Documentation ordering of filters is given as

  • ChannelProcessingFilter
  • ConcurrentSessionFilter
  • SecurityContextPersistenceFilter
  • LogoutFilter
  • X509AuthenticationFilter
  • AbstractPreAuthenticatedProcessingFilter
  • CasAuthenticationFilter
  • UsernamePasswordAuthenticationFilter
  • ConcurrentSessionFilter
  • OpenIDAuthenticationFilter
  • DefaultLoginPageGeneratingFilter
  • DefaultLogoutPageGeneratingFilter
  • ConcurrentSessionFilter
  • DigestAuthenticationFilter
  • BearerTokenAuthenticationFilter
  • BasicAuthenticationFilter
  • RequestCacheAwareFilter
  • SecurityContextHolderAwareRequestFilter
  • JaasApiIntegrationFilter
  • RememberMeAuthenticationFilter
  • AnonymousAuthenticationFilter
  • SessionManagementFilter
  • ExceptionTranslationFilter
  • FilterSecurityInterceptor
  • SwitchUserFilter

You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?

Nested routes with react router v4 / v5

react-router v6

Update for 2021

The upcoming v6 will have nested Route components that Just Work™

See example code in this blog post

The question is about v4/v5, but when v6 ships the correct answer will be just use that if you can.


react-router v4 & v5

It's true that in order to nest Routes you need to place them in the child component of the Route.

However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render prop of the Route you want to nest under.

<BrowserRouter>

  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Backend} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />

</BrowserRouter>

If you're interested in why the render prop should be used, and not the component prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.

Note that the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div> instead.

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

What I did when faced this issue, was connect to DB and update the checksum field correspondent to the mistaken version, putting there the value resolved locally by FlyWay.

For the following error:

nested exception is org.flywaydb.core.api.FlywayException: Validate failed.
Migration Checksum mismatch for migration 1.12
    -> Applied to database : 1029320280
    -> Resolved locally    : -236187247

I simply did this:

UPDATE schema_version SET checksum = -236187247 WHERE version_rank = 12 AND checksum = 1029320280;

And problem solved..

NOTE: You have to be sure your schema is actually correct, check your tables and their structure, if everything is OK, then you can apply this solution; otherwise, you should repair your schema manually first using plain and native SQL.

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

Best check for this problem : (If you are behind proxy),(tested on ubuntu 18.04), (will work on other ubuntu also),(mostly error in : https_proxy="http://192.168.0.251:808/)

  1. Check these files:

    #sudo cat /etc/environment :
    http_proxy="http://192.168.0.251:808/"
    https_proxy="http://192.168.0.251:808/"
    ftp_proxy="ftp://192.168.0.251:808/"
    socks_proxy="socks://192.168.0.251:808/"
    #sudo cat /etc/apt/apt.conf :
    Acquire::http::proxy "http://192.168.0.251:808/";
    Acquire::https::proxy "http://192.168.0.251:808/";
    Acquire::ftp::proxy "ftp://192.168.0.251:808/";
    Acquire::socks::proxy "socks://192.168.0.251:808/";
    
  2. Add docker stable repo

    #sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" 
    
  3. Run apt-get update:

    #sudo apt-get update
    
  4. Check Docker CE

    #apt-cache policy docker-ce
    
  5. install Docker

    #sudo apt-get install docker-ce
    

How to determine previous page URL in Angular?

This simple solution worked for me.

import 'rxjs/add/operator/pairwise';
import { Router } from '@angular/router';

export class TempComponent {
    constructor(private router: Router) {
        this.router.events.pairwise().subscribe((event) => {
            console.log(event); // NavigationEnd will have last and current visit url
        });
    };
}

Windows- Pyinstaller Error "failed to execute script " When App Clicked

I got the same error and figured out that i wrote my script using Anaconda but pyinstaller tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.

How to know which is running in Jupyter notebook?

Creating a virtual environment for Jupyter Notebooks

A minimal Python install is

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

Then you can create and use the environment

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

You can make a kernel for Jupyter with

ipython3 kernel install --user --name=test

How to enable file upload on React's Material UI simple input?

Here an example:

return (
    <Box alignItems='center' display='flex' justifyContent='center' flexDirection='column'>
      <Box>
        <input accept="image/*" id="upload-company-logo" type='file' hidden />
        <label htmlFor="upload-company-logo">
          <Button component="span" >
            <Paper elevation={5}>
              <Avatar src={formik.values.logo} className={classes.avatar} variant='rounded' />
            </Paper>
          </Button>
        </label>
      </Box>
    </Box>
  )

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

If you use JDK 1.8.0_201 or latest try it with older JDK.

I have same issue with JDK1.8.0_201, however it works with JDK1.8.0_101 without any code change.

Correlation heatmap

If your data is in a Pandas DataFrame, you can use Seaborn's heatmap function to create your desired plot.

import seaborn as sns

Var_Corr = df.corr()
# plot the heatmap and annotation on it
sns.heatmap(Var_Corr, xticklabels=Var_Corr.columns, yticklabels=Var_Corr.columns, annot=True)

Correlation plot

From the question, it looks like the data is in a NumPy array. If that array has the name numpy_data, before you can use the step above, you would want to put it into a Pandas DataFrame using the following:

import pandas as pd
df = pd.DataFrame(numpy_data)

Updates were rejected because the tip of your current branch is behind its remote counterpart

It must be because of commit is ahead of your current push.

  1. git pull origin "name of branch you want to push"
  2. git rebase

If git rebase is successful, then good. Otherwise, you have resolve all merge conflicts locally and keep it continuing until rebase with remote is successful.

  1. git rebase --continue

@viewChild not working - cannot read property nativeElement of undefined

You'll also get this error if your target element is inside a hidden element. If this is your HTML:

<div *ngIf="false">
    <span #sp>Hello World</span>
</div>

Your @ViewChild('sp') sp will be undefined.

Solution

In such a case, then don't use *ngIf.

Instead use a class to show/hide your element being hidden.

<div [class.show]="shouldShow">...</div>

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

sudo: docker-compose: command not found

On Ubuntu 16.04

Here's how I fixed this issue: Refer Docker Compose documentation

  1. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

  2. sudo chmod +x /usr/local/bin/docker-compose

After you do the curl command , it'll put docker-compose into the

/usr/local/bin

which is not on the PATH. To fix it, create a symbolic link:

  1. sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

And now if you do: docker-compose --version

You'll see that docker-compose is now on the PATH

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

TL;DR

Just returning response()->json($promotion) won't solve the issue in this question. $promotion is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img property, which is a PHP stream resource, and cannot be encoded.

Details

Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString() magic method will be invoked to make the conversion.

Therefore, when you just return $promotion from your controller action, Laravel is going to call __toString() on it to convert it to a string to display.

On the Model, __toString() calls toJson(), which returns the result of json_encode. Therefore, json_encode is returning false, meaning it is running into an error.

Your dd shows that your img attribute is a stream resource. json_encode cannot encode a resource, so this is probably causing the failure. You should add your img attribute to the $hidden property to remove it from the json_encode.

class Promotion extends Model
{
    protected $hidden = ['img'];

    // rest of class
}

Angular 2 / 4 / 5 - Set base href dynamically

Here's what we ended up doing.

Add this to index.html. It should be the first thing in the <head> section

<base href="/">
<script>
  (function() {
    window['_app_base'] = '/' + window.location.pathname.split('/')[1];
  })();
</script>

Then in the app.module.ts file, add { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' } to the list of providers, like so:

import { NgModule, enableProdMode, provide } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';


import { AppComponent, routing, appRoutingProviders, environment } from './';

if (environment.production) {
  enableProdMode();
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
    routing],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' },
  ]
})
export class AppModule { }

Import error No module named skimage

As per the official installation page of skimage (skimage Installation) : python-skimage package depends on matplotlib, scipy, pil, numpy and six.

So install them first using

sudo apt-get install python-matplotlib python-numpy python-pil python-scipy

Apparently skimage is a part of Cython which in turn is a superset of python and hence you need to install Cython to be able to use skimage.

sudo apt-get install build-essential cython

Now install skimage package using

sudo apt-get install python-skimage

This solved the Import error for me.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Angular 2 TypeScript how to find element in Array

from TypeScript you can use native JS array filter() method:

let filteredElements=array.filter(element => element.field == filterValue);

it returns an array with only matching elements from the original array (0, 1 or more)

Reference: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

<img>: Unsafe value used in a resource URL context

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.

I have created the pipe SanitizeUrlPipe for this

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustResourceUrl(v);
    }
}

and this is how you can use

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

If you want to add HTML, then SanitizeHtmlPipe can help

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustHtml(v);
    }
}

Read more about angular security here.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you are finding the following screen and facing the problem of code signing required, then one of the following solutions may help you.

Image_1

Solution 1. As said before, sign in with an Apple ID. Then you will get options like this, if you enter correct bundle identifier. Then select the appropriate profile from the list.

Image_2_after_adding_apple_id

Solution 2. If you don't want to sign in with your Apple ID, then change a small flag in project.pbxproj file. Find the following text in the project file.

/* Begin PBXProject section */

Change flag ProvisioningStyle = Automatic; to ProvisioningStyle = Manual; Refer to the following image. After changing the flag, you will see the options to select appropriate profile from the list.

Enter image description here

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

TensorFlow, "'module' object has no attribute 'placeholder'"

Import the old version of tensorflow instead of the new version

[https://inneka.com/ml/tf/tensorflow-module-object-has-no-attribute-placeholder/][1]

import tensorflow.compat.v1 as tf tf.disable_v2_behavior()

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had the same problem what caused it was that I already had created a pod from the docker image via the .yml file, however I mistyped the name, i.e test-app:1.0.1 when I needed test-app:1.0.2 in my .yml file. So I did kubectl delete pods --all to remove the faulty pod then redid the kubectl create -f name_of_file.yml which solved my problem.

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 40vh;
object-fit: cover;
}

As shown above but when you add height i suggest using "vh" (Viewport Height units) for a more mobile-friendly experience.

Where does Anaconda Python install on Windows?

You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
enter image description here

As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.

Dynamic classname inside ngClass in angular 2

more elegant solution is to use && (using NgFor and its first, its free to use ur own matching tho):

    <div 
        *ngFor="let day of days;
                let first = first;"
        class="day"
        [ngClass]="first && ('day--' + day)"
    </div>

will turn out as:

class="day day--monday"

What are the pros and cons of parquet format compared to other formats?

I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.

Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.

Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.

While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.

To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.

In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!

Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!

But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.

(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).

One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!

And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC as 2A6B16C but ABCABCBCBCBCCCCCCCCCCCCCC wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.

So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.

Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.

But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.

Hope this helps answer at least part of your question!

How to label scatterplot points by name?

For all those who don't have the option in Excel (like me), there is a macro which works and is explained here: https://www.get-digital-help.com/2015/08/03/custom-data-labels-in-x-y-scatter-chart/ Very useful

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

That worked for me,

Right Click on project -> "Run as Maven Test". This will automatically download the missing plugins and than Right Click on project ->"Update Maven project" it removes the error.

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

As the official docs of redux suggest, better to export the unconnected component as well.

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:

import { connect } from 'react-redux'

// Use named export for unconnected component (for tests)
export class App extends Component { /* ... */ }
 
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)

Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:

// Note the curly braces: grab the named export instead of default export
import { App } from './App'

And if you need both:

import ConnectedApp, { App } from './App'

In the app itself, you would still import it normally:

import App from './App'

You would only use the named export for tests.

Angular2 Routing with Hashtag to page anchor

This one work for me !! This ngFor so it dynamically anchor tag, You need to wait them render

HTML:

<div #ngForComments *ngFor="let cm of Comments">
    <a id="Comment_{{cm.id}}" fragment="Comment_{{cm.id}}" (click)="jumpToId()">{{cm.namae}} Reply</a> Blah Blah
</div>

My ts file:

private fragment: string;
@ViewChildren('ngForComments') AnchorComments: QueryList<any>;

ngOnInit() {
      this.route.fragment.subscribe(fragment => { this.fragment = fragment; 
   });
}
ngAfterViewInit() {
    this.AnchorComments.changes.subscribe(t => {
      this.ngForRendred();
    })
}

ngForRendred() {
    this.jumpToId()
}

jumpToId() { 
    let x = document.querySelector("#" + this.fragment);
    console.log(x)
    if (x){
        x.scrollIntoView();
    }
}

Don't forget to import that ViewChildren, QueryList etc.. and add some constructor ActivatedRoute !!

Generating Request/Response XML from a WSDL

Since you are saying the webservice is not live right now, you can do it by creating mockservices which will create the sample response format.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.

How can I enable the MySQLi extension in PHP 7?

The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,

sudo apt-get install php-mysql

this will automatically update Apache and PHP 7.

How to edit default dark theme for Visual Studio Code?

As far as the themes, VS Code is every bit as editable as Sublime. You can edit any of the default themes that come with VS code. You just have to know where to find the theme files.

Side note: I love the Monokai theme. However, all I wanted to change about it was the background. I don't like the dark grayish background. Instead, I think the contrast is WAY better with a solid black background. The code pops out much more.

Anyways, I hunted for the theme file and found it (in windows) at:

c:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\theme-monokai\themes\

In that folder I found the Monokai.tmTheme file and modified the first background key as follows:

<key>background</key>
<string>#000000</string>

There are a few 'background' key in the theme file, make sure you edit the correct one. The one I edited was at the very top. Line 12 I think.

React-Native: Module AppRegistry is not a registered callable module

if you are facing this error in windows with android

open your root directory app folder and move into android folder .

     cd android 
     gradlew clean

start your app again react-native run-android

bhooom it works

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

android : Error converting byte to dex

Before:

compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.android.gms:play-services-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-messaging:10.2.0'

After:

compile 'com.google.android.gms:play-services-location:10.2.0'
compile 'com.google.android.gms:play-services-auth:10.2.0'
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-messaging:10.2.0'

Finally got resolved.

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

RecyclerView - Get view at particular position

You can use below

mRecyclerview.getChildAt(pos);

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

Plot a horizontal line using matplotlib

A nice and easy way for those people who always forget the command axhline is the following

plt.plot(x, [y]*len(x))

In your case xs = x and y = 40. If len(x) is large, then this becomes inefficient and you should really use axhline.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Just add the next nuget package to your project - Microsoft.CodeDom.Providers.DotNetCompilerPlatform.

Had the same problem.

The type or namespace name 'System' could not be found

i had to upgrade from visual studio 2017 to 2019. no other proposed solution here helped me, i installed and configured, rebooted every one here plus many other options from ms site.

my root cause was probably due to the fact the git repository developer used 2019 and i tried to clone the original git repo into ma 2017.

Can a website detect when you are using Selenium with chromedriver?

You can try to use the parameter "enable-automation"

var options = new ChromeOptions();

// hide selenium
options.AddExcludedArguments(new List<string>() { "enable-automation" });

var driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), options);

But, I want to warn that this ability was fixed in ChromeDriver 79.0.3945.16. So probably you should use older versions of chrome.

Also, as another option, you can try using InternetExplorerDriver instead of Chrome. As for me, IE does not block at all without any hacks.

And for more info try to take a look here:

Selenium webdriver: Modifying navigator.webdriver flag to prevent selenium detection

Unable to hide "Chrome is being controlled by automated software" infobar within Chrome v76

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

What version of Python is on my Mac?

Use below command to see all python installations :

which -a python

How do I force Kubernetes to re-pull an image?

Now, the command kubectl rollout restart deploy YOUR-DEPLOYMENT combined with a imagePullPolicy: Always policy will allow you to restart all your pods with a latest version of your image.

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around instead of justify-content: space-between;.

This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.

Why use Redux over Facebook Flux?

From a new react/redux adopter migrating from (a few years of) ExtJS in mid-2018:

After sliding backward down the redux learning curve I had the same question and thought pure flux would be simpler like OP.

I soon saw the benefits of redux over flux as noted in the answers above, and was working it into my first app.

While getting a grip on the boiler plate again, I tried out a few of the other state management libs, the best I found was rematch.

It was much more intuitive then vanilla redux, it cuts out 90% of the boilerplate and cut out 75% of the time I was spending on redux (something I think a library should be doing), I was able to get a couple enterprise apps going right away.

It also runs with the same redux tooling. This is a good article that covers some of the benefits.

So for anyone else who arrived to this SO post searching "simpler redux", I recommend trying it out as a simple alternative to redux with all the benefits and 1/4 of the boilerplate.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

  1. To closed ideas,
  2. To remove all folder and file C:/Users/UserName/.m2/org/*,
  3. Open ideas and update Maven project,(right click on project -> maven->update maven project)
  4. After that update the project.

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animations);
    getAllSongsFromSDCARD();

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Instance member cannot be used on type

It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).

You can make your instance variable a class variable by adding static/class attribute.

You instantiate an instance of your class and call the instance method on that variable.

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
      set_fact:
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.

Why do you use sudo? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user").

What do you get if you run this?

$ head -n1 /usr/local/bin/pip

This will show you which python binary pip is trying to use. If it's pointing /usr/local/opt/python/bin/python2.7, then try running this:

$ ls -al /usr/local/opt/python/bin/python2.7

If this says "No such file or directory", then pip is trying to use a python binary that has been removed.

Next, try this:

$ which python
$ which python2.7

To see the path of the python binary that's actually working.

Since it looks like pip was successfully installed somewhere, it could be that /usr/local/bin/pip is part of an older installation of pip that's higher up on the PATH. To test that, you may try moving the non-functioning pip binary out of the way like this (might require sudo):

$ mv /usr/local/bin/pip /usr/local/bin/pip.old

Then try running your pip --version command again. Hopefully it picks up the correct version and runs successfully.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I had a similar problem.

Problem in error code below:

int prevSize = messageListHistory.size();
// some insert
adapter.notifyItemRangeInserted(prevSize - 1, messageListHistory.size() -1);

Solution:

int prevSize = messageListHistory.size();
// some insert
adapter.notifyItemRangeInserted(prevSize, messageListHistory.size() -prevSize);

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

How to Resize image in Swift?

Swift 4 Version

extension UIImage {
    func resizeImage(_ newSize: CGSize) -> UIImage? {
        func isSameSize(_ newSize: CGSize) -> Bool {
            return size == newSize
        }

        func scaleImage(_ newSize: CGSize) -> UIImage? {
            func getScaledRect(_ newSize: CGSize) -> CGRect {
                let ratio   = max(newSize.width / size.width, newSize.height / size.height)
                let width   = size.width * ratio
                let height  = size.height * ratio
                return CGRect(x: 0, y: 0, width: width, height: height)
            }

            func _scaleImage(_ scaledRect: CGRect) -> UIImage? {
                UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
                draw(in: scaledRect)
                let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
                UIGraphicsEndImageContext()
                return image
            }
            return _scaleImage(getScaledRect(newSize))
        }

        return isSameSize(newSize) ? self : scaleImage(newSize)!
    }
}

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

Pretty Printing JSON with React

You'll need to either insert BR tag appropriately in the resulting string, or use for example a PRE tag so that the formatting of the stringify is retained:

var data = { a: 1, b: 2 };

var Hello = React.createClass({
    render: function() {
        return <div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Working example.

Update

class PrettyPrintJson extends React.Component {
    render() {
         // data could be a prop for example
         // const { data } = this.props;
         return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
    }
}

ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));

Example

Stateless Functional component, React .14 or higher

const PrettyPrintJson = ({data}) => {
    // (destructured) data could be a prop for example
    return (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}

Or, ...

const PrettyPrintJson = ({data}) => (<div><pre>{ 
    JSON.stringify(data, null, 2) }</pre></div>);

Working example

Memo / 16.6+

(You might even want to use a memo, 16.6+)

const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
    JSON.stringify(data, null, 2) }</pre></div>));

iOS9 Untrusted Enterprise Developer with no option to trust

Do it like this:

Enter image description here

Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.

but iOS10 has a little change,

Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.

enter image description here

Reference: iOS10AdaptationTips

How to loop through an array of objects in swift

The photos property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count property of the array):

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

How to store Configuration file and read it using React

In case you have a .properties file or a .ini file

Actually in case if you have any file that has key value pairs like this:

someKey=someValue
someOtherKey=someOtherValue

You can import that into webpack by a npm module called properties-reader

I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.

  1. Import that from dependencies section in package.json

"properties-reader": "0.0.16"

  1. Import this module into webpack.config.js on top

const PropertiesReader = require('properties-reader');

  1. Read the properties file

const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;

  1. Import this constant as config

externals: { 'Config': JSON.stringify(appProperties) }

  1. Use it as the same way as mentioned in the accepted answer

var Config = require('Config') fetchData(Config.serverUrl + '/Enterprises/...')

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same Maven connection timeout issue and resolved by disabling/whitelisting the anti-virus & firewall setting.

The issue got resolved immediately:

org.apache.maven.wagon.providers.http.httpclient.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

Elegant way to create empty pandas DataFrame with NaN of type float

Simply pass the desired value as first argument, like 0, math.inf or, here, np.nan. The constructor then initializes and fills the value array to the size specified by arguments index and columns:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])

>>> df.dtypes
A    float64
B    float64
dtype: object

>>> df.values
array([[nan, nan],
       [nan, nan],
       [nan, nan],
       [nan, nan]])

How to get local server host and port in Spring Boot?

I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

You need to add the maven dependency first:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

Then you can use the ApplicationInfoManager service in any of your Spring beans.

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();

The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

ES6 Class Multiple inheritance

I have been using a pattern like this to program complex multi inheritance things:

var mammal = {
    lungCapacity: 200,
    breath() {return 'Breathing with ' + this.lungCapacity + ' capacity.'}
}

var dog = {
    catchTime: 2,
    bark() {return 'woof'},
    playCatch() {return 'Catched the ball in ' + this.catchTime + ' seconds!'}
}

var robot = {
    beep() {return 'Boop'}
}


var robotDogProto = Object.assign({}, robot, dog, {catchTime: 0.1})
var robotDog = Object.create(robotDogProto)


var livingDogProto = Object.assign({}, mammal, dog)
var livingDog = Object.create(livingDogProto)

This method uses very little code, and allows for things like overwriting default properties (like I do with a custom catchTime in robotDogProto)

Drop rows containing empty cells from a pandas DataFrame

Pandas will recognise a value as null if it is a np.nan object, which will print as NaN in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan objects using replace(), and then call dropna()on your DataFrame to delete rows with null tenants.

To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants column:

>>> import pandas as pd
>>> import numpy as np
>>> 
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239         
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214         
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640         

Now we replace any empty strings in the Tenants column with np.nan objects, like so:

>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
1 -0.008562  0.725239      NaN
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
4  0.805304 -0.834214      NaN
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes
9  0.066946  0.375640      NaN

Now we can drop the null values:

>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df

          A         B   Tenant
0 -0.588412 -1.179306    Babar
2  0.282146  0.421721  Rataxes
3  0.627611 -0.661126    Babar
5 -0.514568  1.890647    Babar
6 -1.188436  0.294792  Rataxes
7  1.471766 -0.267807    Babar
8 -1.730745  1.358165  Rataxes

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

It used to work on swift 3 and swift 4 but now its not working.

like

self.tableView.register(MyTestTableViewCell.self, forCellReuseIdentifier: "cell")

So I have tried the most of the solutions mentioned above in swift 5 but did not get any luck.

Finally I tried this solution and it worked for me.

override func viewDidLoad() 
{

    tableView.register(UINib.init(nibName: "MyTestTableViewCell", bundle: nil), forCellReuseIdentifier: "myTestTableViewCell")
}

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.

Okay, I got it working using Android Developers guide.

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);

  // creating an OkHttpClient that uses our SSLSocketFactory
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter that uses this custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

Afaik, the .crt file is your public key and the .key file is your private key.

As I can see, you already have a .cert file, which is the same, so try to use it.


PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:

echo -n | openssl s_client -connect your.server.com:443 | \
  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt

Just replace the your.server.com and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.

Single selection in RecyclerView

So, after spending so many days over this, this is what I came up with which worked for me, and is good practice as well,

  1. Create an interface, name it some listener: SomeSelectedListener.
  2. Add a method which takes an integer:void onSelect(int position);
  3. Initialise the listener in the recycler adapter's constructor as : a) first declare globally as: private SomeSelectedListener listener b) then in constructor initialise as: this.listener = listener;
  4. Inside onClick() of checkbox inside onBindViewHolder(): update the method of the interface/listener by passing the position as: listener.onSelect(position)
  5. In the model, add a variable for deselect say, mSelectedConstant and initialise it there to 0. This represents the default state when nothing is selected.
  6. Add getter and setter for the mSelectedConstant in the same model.
  7. Now, go to your fragment/activity and implement the listener interface. Then override its method: onSelect(int position). Within this method, iterate through your list which you are passing to your adapter using a for loop and setSelectedConstant to 0 for all:

code

@Override
public void onTicketSelect(int position) {
for (ListType listName : list) {
    listName.setmSelectedConstant(0);
}

8. Outside this, make the selected position constant 1:

code

list.get(position).setmSelectedConstant(1);
  1. Notify this change by calling: adapter.notifyDataSetChanged(); immediately after this.
  2. Last step: go back to your adapter and update inside onBindViewHolder() after onClick() add the code to update the checkbox state,

code

if (listVarInAdapter.get(position).getmSelectedConstant() == 1) {
    holder.checkIcon.setChecked(true);
    selectedTicketType = dataSetList.get(position);} 
else {
    commonHolder.checkCircularIcon.setChecked(false);
}

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

PyCharm error: 'No Module' when trying to import own module (python script)

I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src and project/subproject2/thing/src and I had both of them marked as source root. When I renamed one of the "thing" folders to "thing1" (any unique name), it worked.

Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.

Spring boot - Not a managed type

I have moved my application class to parent package like :

Main class: com.job.application

Entity: com.job.application.entity

This way you don't have to add @EntityScan

'str' object has no attribute 'decode'. Python 3 error?

If you land here using jwt authentication after the PyJWT v2.0.0 release (22/12/2020), you might want to freeze your version of PyJWT to the previous release in your requirements.txt file.

PyJWT==1.7.1

docker run <IMAGE> <MULTIPLE COMMANDS>

For anyone else who came here looking to do the same with docker-compose you just need to prepend bash -c and enclose multiple commands in quotes, joined together with &&.

So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

Using (Ana)conda within PyCharm

I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.

The short answer

Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.

The long answer

Create a new Conda environment:

conda create --name foo pandas bokeh

This environment lives under conda_root/envs/foo. Your python interpreter is conda_root/envs/foo/bin/pythonX.X and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.

Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!

Now install more packages:

conda install scikit-learn

OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!

And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:

conda list

The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.

Conclusion

This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.

NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.

EDIT: PyCharm5 is out with Conda support! In the community edition too.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

Could not resolve '...' from state ''

This kind of error usually means that some parts of (JS) code were not loaded. That the state which is inside of ui-sref is missing.

There is a working example

I am not an expert in ionic, so this example should show that it would be working, but I used some more tricks (parent for tabs)

This is a bit adjusted state def:

.config(function($stateProvider, $urlRouterProvider){
  $urlRouterProvider.otherwise("/index.html");

    $stateProvider

    .state('app', {
      abstract: true,
      templateUrl: "tpl.menu.html",
    })

  $stateProvider.state('index', {
    url: '/',
    templateUrl: "tpl.index.html",
    parent: "app",
  });


  $stateProvider.state('register', {
    url: "/register",
    templateUrl: "tpl.register.html",
    parent: "app",
  });

  $urlRouterProvider.otherwise('/');
}) 

And here we have the parent view with tabs, and their content:

<ion-tabs class="tabs-icon-top">

  <ion-tab title="Index" icon="icon ion-home" ui-sref="index">
    <ion-nav-view name=""></ion-nav-view>
  </ion-tab>

  <ion-tab title="Register" icon="icon ion-person" ui-sref="register">
    <ion-nav-view name=""></ion-nav-view>
  </ion-tab>

</ion-tabs>

Take it more than an example of how to make it running and later use ionic framework the right way...Check that example here

Here is similar Q & A with an example using the named views (for sure better solution) ionic routing issue, shows blank page

Improved version with named views in a tab is here: http://plnkr.co/edit/Mj0rUxjLOXhHIelt249K?p=preview

  <ion-tab title="Index" icon="icon ion-home" ui-sref="index">
    <ion-nav-view name="index"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Register" icon="icon ion-person" ui-sref="register">
    <ion-nav-view name="register"></ion-nav-view>
  </ion-tab>

targeting named views:

  $stateProvider.state('index', {
    url: '/',
    views: { "index" : { templateUrl: "tpl.index.html" } },
    parent: "app",
  });


  $stateProvider.state('register', {
    url: "/register",
    views: { "register" : { templateUrl: "tpl.register.html", } },
    parent: "app",
  });

Determining if Swift dictionary contains key and obtaining any of its values

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

TypeError: 'list' object cannot be interpreted as an integer

You should do this instead:

for i in myList:
    # etc.

That is, remove the range() part. The range() function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.

Upload a file to Amazon S3 with NodeJS

Uploading a file to AWS s3 and sending the url in response for accessing the file.

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. check this npm module here.

When you are sending the request, make sure the headers, have Content-Type is multipart/form-data. We are sending the file location in the response, which will give the url, but if you want to access that url, make the bucket public or else you will not be able to access it.

upload.router.js

const express = require('express');
const router = express.Router();
const AWS = require('aws-sdk');
const multer = require('multer');
const storage = multer.memoryStorage()
const upload = multer({storage: storage});

const s3Client = new AWS.S3({
    accessKeyId: 'your_access_key_id',
    secretAccessKey: 'your_secret_access_id',
    region :'ur region'
});

const uploadParams = {
         Bucket: 'ur_bucket_name', 
         Key: '', // pass key
         Body: null, // pass file body
};


router.post('/api/file/upload', upload.single("file"),(req,res) => {
    const params = uploadParams;

    uploadParams.Key = req.file.originalname;
    uploadParams.Body = req.file.buffer;

    s3Client.upload(params, (err, data) => {
        if (err) {
            res.status(500).json({error:"Error -> " + err});
        }
        res.json({message: 'File uploaded successfully','filename': 
        req.file.originalname, 'location': data.Location});
    });
});

module.exports = router;

app.js

const express = require('express');
const app = express();

const router = require('./app/routers/upload.router.js');
app.use('/', router);

// Create a Server
  const server = app.listen(8080, () => {
  console.log("App listening at 8080"); 
})

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to stop INFO messages displaying on spark console?

Right after starting spark-shell type ;

sc.setLogLevel("ERROR")

In Spark 2.0 (Scala):

spark = SparkSession.builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

API Docs : https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.SparkSession

For Java:

spark = SparkSession.builder.getOrCreate();
spark.sparkContext().setLogLevel("ERROR");

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I want to add one thing with the answer given by Softcoder. I have seen some people couldn't give their debug.keystore path correctly on the command line. They see that they are doing the exact process accepted above, but it is not working. At that point try to drag the debug.keystore and drop it on the command line. It will help if the accepted answer is not working for you. Do the full process without any hesitation. It was a nice answer.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

I have also recieved this issue inside of InteliJ.

Go to the gradle/wrapper folder and modify distributionUrl inside of gradle-wrapper.properties to a correct version.

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

Calling a phone number in swift

For swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
else {
    print("Your device doesn't support this feature.")
}

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

How can I verify if an AD account is locked?

If you want to check via command line , then use command "net user username /DOMAIN"

enter image description here

Multipart File Upload Using Spring Rest Template + Spring Web MVC

A correct file upload would like this:

HTTP header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

Http body:

--ABCDEFGHIJKLMNOPQ

Content-Disposition: form-data; name="file"; filename="my.txt"

Content-Type: application/octet-stream

Content-Length: ...

<...file data in base 64...>

--ABCDEFGHIJKLMNOPQ--

and code is like this:

public void uploadFile(File file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/file/user/upload";
            HttpMethod requestMethod = HttpMethod.POST;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);


            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name("file")
                    .filename(file.getName())
                    .build();

            fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileEntity);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);

            System.out.println("file upload status code: " + response.getStatusCode());

        } catch (IOException e) {
            e.printStackTrace();
        }

}

What is the difference between compileSdkVersion and targetSdkVersion?

The Application settings of an Android project's properties in Visual Studio 2017 (15.8.5) has them combined:

enter image description here

Error in installation a R package

In my case, the installation of nlme package is in trouble:

mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme' 
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme': 
Permission denied

Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:

sudo R
install.packages('nlme')
q()

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Adding spring.jpa.database-platform=org.hibernate.dialect.MariaDB53Dialect to my properties file worked for me.

PS: i'm using MariaDB

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

I've just solved these exact errors myself. The key it seems is that your project.properties file in your appcompat library project should use whatever the highest version of the API that your particular appcompat project has been written for (in your case it looks like v21). Easiest way I've found to tell is to look for the highest 'values-v**' folder inside the res folder (eg. values-v21).

To clarify, in addition to the instructions at Support Library Setup, your appcompat/project.properties file should have in it: target=android-21 (mine came with 19 instead).

Also ensure that you have the 'SDK Platform' to match that version installed (eg for v21 install Android 5.0 SDK Platform).

See also appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Alternatively if you don't want to use the appcompat at all, (I think) all you need to do is right click your project > Properties > Android > Library > Remove the reference to the appcompat. The errors will still show up for the appcompat project, but shouldn't affect your project after that.

Android 5.0 - Add header/footer to a RecyclerView

I haven't tried this, but I would simply add 1 (or 2, if you want both a header and footer) to the integer returned by getItemCount in your adapter. You can then override getItemViewType in your adapter to return a different integer when i==0: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)

createViewHolder is then passed the integer you returned from getItemViewType, allowing you to create or configure the view holder differently for the header view: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#createViewHolder(android.view.ViewGroup, int)

Don't forget to subtract one from the position integer passed to bindViewHolder.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

Spring Boot, Spring Data JPA with multiple DataSources

I have written a complete article at Spring Boot JPA Multiple Data Sources Example. In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application. We will use Spring Boot 2.0.5, JPA, Hibernate 5, Thymeleaf and H2 database to build a simple Spring Boot multiple data sources web application.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

remove this work for me:

<filtering>true</filtering>

I guess it is caused by this filtering bug

The view didn't return an HttpResponse object. It returned None instead

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

above code can be changed to

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

You are trying to add a non-nullable field 'new_field' to userprofile without a default

You can use method from Django Doc from this page https://docs.djangoproject.com/en/1.8/ref/models/fields/#default

Create default and use it

def contact_default():
   return {"email": "[email protected]"}

contact_info = JSONField("ContactInfo", default=contact_default)

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

so that the entry is UNchecked then the software keyboard will be displayed once again.

Plotting a fast Fourier transform in Python

There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:

Adding the required modules:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal

Generating sample data:

N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise

Sorting the data set:

order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]

Resampling:

T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)

Plotting the data and resampled data:

plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")

Enter image description here

Now calculating the FFT:

Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]

plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)

Enter image description here

P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.

"Untrusted App Developer" message when installing enterprise iOS Application

You cannot avoid this unless you distribute an application via the App Store.

You get this message because the application is signed via an enterprise certificate that has not yet been trusted by the user. Apple force this prompt to appear because the application that is being installed hasn't gone through the App Store review process so is technically untrusted.

Once the user has accepted the prompt, the certificate will be marked as trusted and the application can be installed (along with any other future applications that you wish to install that have been signed with the same certificate)

Note: As pointed out in the comments, as of iOS 8, uninstalling all applications from a specific certificate will cause the prompt to be shown again once an application from said certificate is re-installed.

Here is the link to Apple website that confirms this info: https://support.apple.com/en-us/HT204460

OSError: [WinError 193] %1 is not a valid Win32 application

All above solution are logical and I think covers the root cause, but for me, none of the above worked. Hence putting it here as may be helpful for others.

My environment was messed up. As you can see from the traceback, there are two python environments involved here:

  1. C:\Users\example\AppData\Roaming\Python\Python37
  2. C:\Users\example\Anaconda3

I cleaned up the path and just deleted all the files from C:\Users\example\AppData\Roaming\Python\Python37.

Then it worked like the charm.

I hope others may find this helpful.

This link helped me to found the solution.

Format LocalDateTime with Timezone in Java8

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

The marked answer is the correct one. However, Pricey, you should follow up on this with your AD and desktop admin groups. They are misusing the IE11 Enterprise Mode site list. Microsoft does NOT intend it to be used for all intranet sites within an organization at all. That would be propagating the existing "render all intranet sites in compatibility mode" setting that is the bane of corporate website advancement the world over.

It's meant to implemented as a "Black list", with the handful of sites that actually require a legacy browser mode listed in the Enterprise Mode list with their rendering requirements specified. All other sites in your organization are then freed up to use Edge. The people in your organization who implemented it with all intranet sites included to start with have completely misunderstood how Enterprise Mode is meant to be implemented.

AngularJS ng-click to go to another page (with Ionic framework)

One think you should change is the call $state.go(). As described here:

The param passed should be the state name

$scope.create = function() {
  // instead of this
  //$state.go("/tab/newpost"); 

  // we should use this
  $state.go("tab.newpost"); 
};

Some cite from doc (the first parameter to of the [$state.go(to \[, toParams\] \[, options\]):

to

String Absolute State Name or Relative State Path

The name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.

Some examples:

$state.go('contact.detail') will go to the 'contact.detail' state
$state.go('^') will go to a parent state.
$state.go('^.sibling') will go to a sibling state.
$state.go('.child.grandchild') will go to a grandchild state.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

Old thread I know, but I lost a couple of hours of my life with this. You also need to set the DB info in the .env file. You don't have to specify the driver here because the default specified in database.php is used (I think). I was struggling because it had DB_CONNECTION=mysql in the .env file and I was using pgsql.

python 2.7: cannot pip on windows "bash: pip: command not found"

I had a similar problem running SciPy on my computer. There are two ways to fix this problem: 1. Yes you do need to cd into your python directory. 2. Sometimes you have to tell the computer explicitly what path to go through, you have to find the program you're using, open up the properties, and reroute the path it takes to run. 3. consult the manual: http://matplotlib.org/users/installing.html or http://www.scipy.org/install.html

the Scipy package is very finicky, and needs things spelled out in obnoxious detail.

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How to configure Glassfish Server in Eclipse manually

For Eclipse Mars use the similar approach as harshit.

1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse

In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.

During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.

Eclipse 4.5.0 Mars JDK : 1.8

How to turn off INFO logging in Spark?

I used this with Amazon EC2 with 1 master and 2 slaves and Spark 1.2.1.

# Step 1. Change config file on the master node
nano /root/ephemeral-hdfs/conf/log4j.properties

# Before
hadoop.root.logger=INFO,console
# After
hadoop.root.logger=WARN,console

# Step 2. Replicate this change to slaves
~/spark-ec2/copy-dir /root/ephemeral-hdfs/conf/

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

Gulp command not found after install

You need to do this npm install --global gulp. It works for me and i also had this problem. It because you didn't install globally this package.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Have you tried @Lazy loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource (until the JNDI vars have been setup).

N.B. I haven't had a chance to test this code yet!

@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    //bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

You may also need to add the @Lazy annotation wherever the DataSource is being used. e.g.

@Lazy
@Autowired
private DataSource dataSource;

git returns http error 407 from proxy after CONNECT

Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.

Export From Web Browser

Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))

In Git Bash

git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate

The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/

To add the proxy, like the other threads I used

git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080

Pycharm does not show plot

One property need to set for pycharm.

import matplotlib.pyplot as plt

plt.interactive(False)  #need to set to False

dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)

plt.show()

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Open firewall port on CentOS 7

If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.

#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent

#firewall-cmd --reload


And check the Port opened or not after reloading the firewall.


#firewall-cmd --list-port


For other configuration [Linuxwindo.com][1]

How to present popover properly in iOS 8

For those who wants to study!

I created an Open Source project for those who want to study and use Popover view for anypurpose. You can find the project here. https://github.com/tryWabbit/KTListPopup

KTListNewResize

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Regarding this error I've tried:

  • Cleaning and rebuilding the project
  • Unloading and reloading the project
  • Modifying the Target Framework
  • Modifying the Output path
  • Adding nuggets to the GAC
  • Deleting the packages uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform uninstall-package Microsoft.Net.Compilers and installing them again.

While these all seem to be valid solutions, I was only able to generate new errors and in the end, the error seems able to display when certain references/nugets are missing.

In my case, I had recently reinstalled Microsoft Office and was referencing assemblies like Microsoft.Office.Core. The new install didn't seem to include the required packages, which made it so my solution couldn't build correctly.

I was able to solve this issue by reworking my code to the point where I didn't need to reference Microsoft.Office, but could've solved it by looking up the required packages and installing them accordingly.

Seems like an unclear error message from Visual Studio.

Save string to the NSUserDefaults?

[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

Windows-1252 to UTF-8 encoding

There's no general way to tell if a file is encoded with a specific encoding. Remember that an encoding is nothing more but an "agreement" how the bits in a file should be mapped to characters.

If you don't know which of your files are actually already encoded in UTF-8 and which ones are encoded in windows-1252, you will have to inspect all files and find out yourself. In the worst case that could mean that you have to open every single one of them with either of the two encodings and see whether they "look" correct -- i.e., all characters are displayed correctly. Of course, you may use tool support in order to do that, for instance, if you know for sure that certain characters are contained in the files that have a different mapping in windows-1252 vs. UTF-8, you could grep for them after running the files through 'iconv' as mentioned by Seva Akekseyev.

Another lucky case for you would be, if you know that the files actually contain only characters that are encoded identically in both UTF-8 and windows-1252. In that case, of course, you're done already.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

How can I convert string to datetime with format specification in JavaScript?

No sophisticated date/time formatting routines exist in JavaScript.

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

For the input conversion, several suggestions have been made already. :)

What is an index in SQL?

INDEXES - to find data easily

UNIQUE INDEX - duplicate values are not allowed

Syntax for INDEX

CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

Syntax for UNIQUE INDEX

CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);

Pass path with spaces as parameter to bat file

@echo off
setlocal enableextensions enabledelayedexpansion

if %1=="" (     
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.     
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
                IF ERRORLEVEL ==2 GOTO CANCEL
                IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
        @echo !PWA_PATH! vs. %1
        goto end
    )
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1

As VardhanDotNet mentions, %1 is enough.

"%1%" would add quotes around quotes: ""c:\Program Files\xxx"" which means:

  • 'empty string' (""),
  • followed by 'c:\Program',
  • followed by the "unexpected here" 'Files\xxx',
  • followed by an empty string ("")

Note however that if you need to use PWA_PATH within your IF clause, you need to refer if as !PWA_PATH! (hence the enabledelayedexpansion as the beginning of the script)

Waiting for another flutter command to release the startup lock

Did most of the previous solutions but it didn't work for me so i just left the laptop connected to the internet with VS-code opened then i switched if off for a while and put it back on and it worked

How to get text of an input text box during onKeyPress?

<asp:TextBox ID="txtMobile" runat="server" CssClass="form-control" style="width:92%;  margin:0px 5px 0px 5px;" onkeypress="javascript:return isNumberKey(event);" MaxLength="12"></asp:TextBox>

<script>
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
</script>

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

How to add new activity to existing project in Android Studio?

In Android Studio, go to app --> src --> main --> res-->

File --> new --> Activity --> ActivityType [choose a acticity that you want]

Fill in the details of the New Android Activity and click Finish.

How to get Selected Text from select2 when using <input>

The correct way to do this as of v4 is:

$('.select2-chosen').select2('data')[0].text

It is undocumented so could break in the future without warning.

You will probably want to check if there is a selection first however:

var s = $('.select2-chosen');

if(s.select2('data') && !!s.select2('data')[0]){
    //do work
}

How to call a button click event from another method

For people wondering, this also works for button click. For example:

private void btn_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Test")
        }

private void txb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btn_Click(sender, e);
            }

When pressing Enter in the textfield(txb) in this case it will click the button which will active the MessageBox.

Increase days to php current Date()

a day is 86400 seconds.

$tomorrow = date('y:m:d', time() + 86400);

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

How to use breakpoints in Eclipse

Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-

http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/

SQL Server principal "dbo" does not exist,

In my case I got this error when trying to impersonate as another user. E.g.

EXEC AS USER = 'dbo';

And as the database was imported from another environment, some of its users did not match the SQL Server logins.

You can check if you have the same problem by running the (deprecated) sp_change_users_login (in "Report" mode), or use the following query:

select p.name,p.sid "sid in DB", (select serp.sid from sys.server_principals serp where serp.name = p.name) "sid in server"
from sys.database_principals p
where p.type in ('G','S','U')
and p.authentication_type = 1
and p.sid not in (select sid from sys.server_principals)

If in that list shows the user you are trying to impersonate, then you probably can fix it by assigning the DB user to the proper login in your server. For instance:

ALTER USER dbo WITH LOGIN = dbo;

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

from unix timestamp to datetime

Looks like you might want the ISO format so that you can retain the timezone.

var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

How to remove foreign key constraint in sql server?

Depending on the DB you are using there's a syntax or another.

If you're using Oracle you have to put what the other users told you:

ALTER TABLE table_name DROP CONSTRAINT fk_name;

But if you use MySQL then this will give you a syntax error, instead you can type:

ALTER TABLE table_name DROP INDEX fk_name;

how to empty recyclebin through command prompt?

i use these commands in a batch file to empty recycle bin:

del /q /s %systemdrive%\$Recycle.bin\*
for /d %%x in (%systemdrive%\$Recycle.bin\*) do @rd /s /q "%%x"

Cannot read property 'push' of undefined when combining arrays

Generally, Push method is used to add elements at the end of an array.

Here, you have used the push method to an object and not an array which is 'order'.

Steps to debug...

Change the object into an empty array,

var order = [], stack = [];

Now you can use the push method for this array as usual.

To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.

var order = [], stack = [];

for(var i = 0; i<a.length; i++){

   if(parseInt(a[i].daysleft) == 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) > 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) < 0){ 
     order.push(a[i]); 
   }
}

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

What is the difference between using constructor vs getInitialState in React / React Native?

OK, the big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React.

constructor is where your class get initialised...

Constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

A constructor can use the super keyword to call the constructor of a parent class.

In the React v16 document, they didn't mentioned any preference, but you need to getInitialState if you using createReactClass()...

Setting the Initial State

In ES6 classes, you can define the initial state by assigning this.state in the constructor:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

Visit here for more information.

Also created the image below to show few lifecycles of React Compoenents:

React lifecycle

Using Enum values as String literals

You could override the toString() method for each enum value.

Example:

public enum Country {

  DE {
    @Override
    public String toString() {
      return "Germany";
    }
  },
  IT {
    @Override
    public String toString() {
      return "Italy";
    }
  },
  US {
    @Override
    public String toString() {
      return "United States";
    }
  }

}

Usage:

public static void main(String[] args) {
  System.out.println(Country.DE); // Germany
  System.out.println(Country.IT); // Italy
  System.out.println(Country.US); // United States
}

JVM option -Xss - What does it do exactly?

If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.

Gunicorn worker timeout error

For me, it was because I forgot to setup firewall rule on database server for my Django.

ImportError: No Module Named bs4 (BeautifulSoup)

Activate the virtualenv, and then install BeautifulSoup4:

$ pip install BeautifulSoup4

When you installed bs4 with easy_install, you installed it system-wide. So your system python can import it, but not your virtualenv python. If you do not need bs4 to be installed in your system python path, uninstall it and keep it in your virtualenv.

For more information about virtualenvs, read this

Static Block in Java

Static block can be used to show that a program can run without main function also.

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

How to hide column of DataGridView when using custom DataSource?

I"m not sure if its too late, but the problem is that, you cannot set the columns in design mode if you are binding at runtime. So if you are binding at runtime, go ahead and remove the columns from the design mode and do it pragmatically

ex..

     if (dt.Rows.Count > 0)
    {
        dataGridViewProjects.DataSource = dt;
        dataGridViewProjects.Columns["Title"].Width = 300;
        dataGridViewProjects.Columns["ID"].Visible = false;
    }

C pass int array pointer as parameter into a function

In your new code,

int func(int *B){
    *B[0] = 5;
}

B is a pointer to int, thus B[0] is an int, and you can't dereference an int. Just remove the *,

int func(int *B){
    B[0] = 5;
}

and it works.

In the initialisation

int B[10] = {NULL};

you are initialising anint with a void* (NULL). Since there is a valid conversion from void* to int, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.

int B[10] = {0};

is the proper way to 0-initialise an int[10].

How can I loop through a List<T> and grab each item?

Just for completeness, there is also the LINQ/Lambda way:

myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));

vim - How to delete a large block of text without counting the lines?

Alongside with other motions that are already mentioned here, there is also /{pattern}<CR> motion, so if you know that you want to delete to line that contains foo, you could do dV/foo<CR>. V is here to force motion be line-wise because by default / is characterwise.

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

UICollectionView auto scroll to cell at IndexPath

As an alternative to mentioned above. Call after data load:

Swift

collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .right)

Command copy exited with code 4 when building - Visual Studio restart solves it

As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.

Angular 2 Cannot find control with unspecified name attribute on formArrays

This happened to me because I left a formControlName empty (formControlName=""). Since I didn't need that extra form control, I deleted it and the error was resolved.

Java: Check if enum contains a given string?

solution to check whether value is present as well get enum value in return :

protected TradeType getEnumType(String tradeType) {
    if (tradeType != null) {
        if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
            return TradeType.valueOf(tradeType);
        }
    }
    return null;
}

How to rebase local branch onto remote master

First fetch the new master from the upstream repository, then rebase your work branch on that:

git fetch origin            # Updates origin/master
git rebase origin/master    # Rebases current branch onto origin/master

Update: Please see Paul Draper's answer for a more concise way to do the same - recent Git versions provide a simpler way to do the equivalent of the above two commands.

Find something in column A then show the value of B for that row in Excel 2010

Assuming

source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1

Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

Most pythonic way to delete a file which may not exist

os.path.exists returns True for folders as well as files. Consider using os.path.isfile to check for whether the file exists instead.

Using Page_Load and Page_PreRender in ASP.Net

It depends on your requirements.

Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.

Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.

Reference: Control Execution Lifecycle MSDN

Try to read about

ASP.NET Page Life Cycle Overview ASP.NET

Control Execution Lifecycle

Regards

How to Load Ajax in Wordpress

I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.

Hopefully will help someone else.

Here is the corrected code from the question:

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
    wp_enqueue_script(
       'function',
       'http://host/blog/wp-content/themes/theme/js.js',
       array( 'jquery' ),
       '1.0',
       1
   );

   wp_localize_script(
      'function',
      'ajax_script',
      array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

$dirName = get_stylesheet_directory();  // use this to get child theme dir
require_once ($dirName."/ajax.php");  

add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php

add_action('template_redirect', 'add_ajax');  

Configuring Hibernate logging using Log4j XML config file?

You can configure your log4j file with the category tag like this (with a console appender for the example):

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss} %p %c - %m%n" />
    </layout>
</appender>
<category name="org.hibernate">
    <priority value="WARN" />
</category>
<root>
    <priority value="INFO" />
    <appender-ref ref="console" />
</root>

So every warning, error or fatal message from hibernate will be displayed, nothing more. Also, your code and library code will be in info level (so info, warn, error and fatal)

To change log level of a library, just add a category, for example, to desactive spring info log:

<category name="org.springframework">
    <priority value="WARN" />
</category>

Or with another appender, break the additivity (additivity default value is true)

<category name="org.springframework" additivity="false">
    <priority value="WARN" />
    <appender-ref ref="anotherAppender" />
</category>

And if you don't want that hibernate log every query, set the hibernate property show_sql to false.

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

Getting file size in Python?

Use os.path.getsize(path) which will

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

Or use os.stat(path).st_size

import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 

Or use Path(path).stat().st_size (Python 3.4+)

from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size

How to copy a huge table data into another table in SQL Server

If it's a 1 time import, the Import/Export utility in SSMS will probably work the easiest and fastest. SSIS also seems to work better for importing large data sets than a straight INSERT.

BULK INSERT or BCP can also be used to import large record sets.

Another option would be to temporarily remove all indexes and constraints on the table you're importing into and add them back once the import process completes. A straight INSERT that previously failed might work in those cases.

If you're dealing with timeouts or locking/blocking issues when going directly from one database to another, you might consider going from one db into TEMPDB and then going from TEMPDB into the other database as it minimizes the effects of locking and blocking processes on either side. TempDB won't block or lock the source and it won't hold up the destination.

Those are a few options to try.

-Eric Isaacs

ERROR 1148: The used command is not allowed with this MySQL version

I got this error while loading data when using docker[1]. The solution worked after I followed these next steps. Initially, I created the database and table datavault and fdata. When I tried to import the data[2], I got the error[3]. Then I did:

  • SET GLOBAL local_infile = 1;
  • Confirm using SHOW VARIABLES LIKE 'local_infile';
  • Then I restarted my mysql session: mysql -P 3306 -u required --local-infile=1 -p, see [4] for user creation.
  • I recreated my table as this solved my problem:
    • use datavault;
    • drop table fdata;
    • CREATE TABLE fdata (fID INT, NAME VARCHAR(64), LASTNAME VARCHAR(64), EMAIL VARCHAR(128), GENDER VARCHAR(12), IPADDRESS VARCHAR(40));
  • Finally I imported the data using [2].

For completeness, I would add I was running the mysql version inside the container via docker exec -it testdb sh. The mysql version was mysql Ver 8.0.17 for Linux on x86_64 (MySQL Community Server - GPL). This was also tested with mysql.exe Ver 14.14 Distrib 5.7.14, for Win64 (x86_64) which was another version of mysql from WAMP64. The associated commands used are listed in [5].


[1] docker run --name testdb -v //c/Users/C/Downloads/data/csv-data/:/var/data -p 3306 -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

[2] load data local infile '/var/data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n' IGNORE 1 ROWS;

[3] ERROR 1148 (42000): The used command is not allowed with this MySQL version

[4] The required client was created using:

  • CREATE USER 'required'@'%' IDENTIFIED BY 'password';
  • GRANT ALL PRIVILEGES ON * . * TO 'required'@'%';
  • FLUSH PRIVILEGES;
  • You might need this line ALTER USER 'required'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; if you run into this error: Authentication plugin ‘caching_sha2_password’ cannot be loaded

[5] Commands using mysql from WAMP64:

  • mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile=1 where the port is thee mapped port into the host as described by docker ps -a and the host ip was optained using docker-machine ip (This depends on OS and possibly Docker version).
  • Create database datavault2 and table fdata as described above
  • load data local infile 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n';
  • For my record, this other alternative to load the file worked after I have previously created datavault3 and fdata: mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile datavault3 -e "LOAD DATA LOCAL INFILE 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' REPLACE INTO TABLE fdata FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS" and it successfully loaded the data easily checked after running select * from fdata limit 10;.

Inner join with count() on three tables

As Frank pointed out, you need to use DISTINCT. Also, since you are using composite primary keys (which is perfectly fine, BTW) you need to make sure that you use the whole key in your joins:

SELECT
    P.pe_name,
    COUNT(DISTINCT O.ord_id) AS num_orders,
    COUNT(I.item_id) AS num_items
FROM
    People P
INNER JOIN Orders O ON
    O.pe_id = P.pe_id
INNER JOIN Items I ON
    I.ord_id = O.ord_id AND
    I.pe_id = O.pe_id
GROUP BY
    P.pe_name

Without I.ord_id = O.ord_id it was joining each item row to every order row for a person.

Java resource as file

ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath.

In some cases this may be simply impossible - for instance, a ClassLoader could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want.

If you know you've actually got a jar file, you could load that with ZipInputStream to find out what's available. It will mean you'll have different code for directories and jar files though.

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.

How to load html string in a webview?

To load your data in WebView. Call loadData() method of WebView

wv.loadData(yourData, "text/html", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";

Exception thrown in catch and finally clause

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.

Exception currentException = null;

As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.

Also, the finally blocks always run before the method exits. You could then requite the code snippet to:

public class C1 {

    public static void main(String [] argv) throws Exception {
        try {
            System.out.print(1);
            q();

        }
        catch ( Exception i ) {
            // <-- currentException = Exception, as thrown by q()'s finally block
            throw( new MyExc2() ); // <-- currentException = MyExc2
        }
        finally {
             // <-- currentException = MyExc2, thrown from main()'s catch block
            System.out.print(2);
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }

    }  // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.

    static void q() throws Exception {
        try {
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }
        catch( Exception y ) {
           // <-- currentException = null, because the exception is caught and not rethrown
        }
        finally {
            System.out.print(3);
            throw( new Exception() ); // <-- currentException = Exception
        }
    }
}

The order in which the application executes is:

main()
{
  try
    q()
    {
      try
      catch
      finally
    }
  catch
  finally
}

What is an efficient way to implement a singleton pattern in Java?

There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.


The first attempt might look something like this:

public class MySingleton {

     private static MySingleton INSTANCE;

     public static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }
        return INSTANCE;
    }
    ...
}

Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().

But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.


private static MySingleton INSTANCE;

public static synchronized MySingleton getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new MySingleton();
    }
    return INSTANCE;
}

Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.


private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronize(MySingleton.class) {
            INSTANCE = new MySingleton();
        }
    }
    return INSTANCE;
}

Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null.

They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.


private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }
    return INSTANCE;
}

Here we issue another check from inside the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.

This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations.

Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.


private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }
    return INSTANCE;
}

We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.

But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.


private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    MySingleton result = INSTANCE;
    if (result == null) {
        synchronized(MySingleton.class) {
            result = INSTANCE;
            if (result == null) {
                INSTANCE = result = createInstance();
            }
        }
    }
    return result;
}

Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.

I wrote an article about this recently. Deconstructing The Singleton. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.

TypeError: $ is not a function when calling jQuery function

You have to pass $ in function()

<script>
jQuery(document).ready(function($){

// jQuery code is in here

});
</script>

SyntaxError: Unexpected token o in JSON at position 1

Well, I meant that I need to parse object like this: var jsonObj = {"first name" : "fname"}. But, I don't actually. Because it's already an JSON.

PHP - Failed to open stream : No such file or directory

For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.

Range of values in C Int and Long 32 - 64 bits

Excerpt from K&R:

short is often 16 bits, long 32 bits and int either 16 bits or 32 bits. Each compiler is free to choose appropriate sizes for its own hardware, subject only to the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer than long.


You can make use of limits.h that contains the definition of the limits for the decimal/float types:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>


int main(int argc, char** argv) {

    printf("CHAR_BIT    :   %d\n", CHAR_BIT);
    printf("CHAR_MAX    :   %d\n", CHAR_MAX);
    printf("CHAR_MIN    :   %d\n", CHAR_MIN);
    printf("INT_MAX     :   %d\n", INT_MAX);
    printf("INT_MIN     :   %d\n", INT_MIN);
    printf("LONG_MAX    :   %ld\n", (long) LONG_MAX);
    printf("LONG_MIN    :   %ld\n", (long) LONG_MIN);
    printf("SCHAR_MAX   :   %d\n", SCHAR_MAX);
    printf("SCHAR_MIN   :   %d\n", SCHAR_MIN);
    printf("SHRT_MAX    :   %d\n", SHRT_MAX);
    printf("SHRT_MIN    :   %d\n", SHRT_MIN);
    printf("UCHAR_MAX   :   %d\n", UCHAR_MAX);
    printf("UINT_MAX    :   %u\n", (unsigned int) UINT_MAX);
    printf("ULONG_MAX   :   %lu\n", (unsigned long) ULONG_MAX);
    printf("USHRT_MAX   :   %d\n", (unsigned short) USHRT_MAX);
    printf("FLT_MAX     :   %g\n", (float) FLT_MAX);
    printf("FLT_MIN     :   %g\n", (float) FLT_MIN);
    printf("-FLT_MAX    :   %g\n", (float) -FLT_MAX);
    printf("-FLT_MIN    :   %g\n", (float) -FLT_MIN);
    printf("DBL_MAX     :   %g\n", (double) DBL_MAX);
    printf("DBL_MIN     :   %g\n", (double) DBL_MIN);
    printf("-DBL_MAX     :  %g\n", (double) -DBL_MAX);

    return (EXIT_SUCCESS);
}

Maybe you might have to tweak a little bit on your machine, but it is a good template to start to get an idea of the (implementation-defined) min and max values.

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

ASP.NET MVC 3 Razor - Adding class to EditorFor

I just needed to set the size of one textbox on one page. Coding attributes on the model and creating custom editor templates were overkill, so I just wrapped the @Html.EditorFor call with a span tag that called a class which specifies the size of the textbox.

CSS class declaration:

.SpaceAvailableSearch input
{
    width:25px;
}

View code:

<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>

Open another application from your own (intent)

If you're attempting to start a SERVICE rather than activity, this worked for me:

Intent intent = new Intent();
intent.setClassName("com.example.otherapplication", "com.example.otherapplication.ServiceName");
context.startService(intent);

If you use the intent.setComponent(...) method as mentioned in other answers, you may get an "Implicit intents with startService are not safe" warning.

getaddrinfo: nodename nor servname provided, or not known

I restarted my computer (Mac Mountain Lion) and the problem fixed itself. Something having to do with the shell thinking it was disconnected from the internet I think.

Restarting your shell in some definite way may solve this problem as well. Simply opening up a new session/window however did not work.

Best way to create enum of strings?

I don't know what you want to do, but this is how I actually translated your example code....

package test;

/**
 * @author The Elite Gentleman
 *
 */
public enum Strings {
    STRING_ONE("ONE"),
    STRING_TWO("TWO")
    ;

    private final String text;

    /**
     * @param text
     */
    Strings(final String text) {
        this.text = text;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return text;
    }
}

Alternatively, you can create a getter method for text.

You can now do Strings.STRING_ONE.toString();

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

Synchronous request in Node.js

I like Raynos' solution as well, but I prefer a different flow control library.

https://github.com/caolan/async

Depending on whether you need the results in each subsequent function, I'd either use series, parallel, or waterfall.

Series when they have to be serially executed, but you don't necessarily need the results in each subsequent function call.

Parallel if they can be executed in parallel, you don't need the results from each during each parallel function, and you need a callback when all have completed.

Waterfall if you want to morph the results in each function and pass to the next

endpoints = 
 [{ host: 'www.example.com', path: '/api_1.php' },
  { host: 'www.example.com', path: '/api_2.php' },
  { host: 'www.example.com', path: '/api_3.php' }];

async.mapSeries(endpoints, http.get, function(results){
    // Array of results
});

Check for a substring in a string in Oracle without LIKE

If you were only interested in 'z', you could create a function-based index.

CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))

Then your query would use WHERE INSTR(last_name,'z') > 0.

With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.

Also, keep in mind that if your data has the names capitalized in the standard way (e.g., "Zaxxon"), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z').

Error Installing Homebrew - Brew Command Not Found

try this

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"

Java 8: Difference between two LocalDateTime in multiple units

TL;DR

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

and then use the methods period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart().


Expanded answer

I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60, hours < 24, and so on.

Given two LocalDateTimes start and end, e.g.

LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);

we can represent the absolute timespan between the two with a Duration—perhaps using Duration.between(start, end). But the biggest unit we can extract out of a Duration is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration with a pair of (Period, Duration), where the Period measures the difference up to a precision of days and the Duration represents the remainder:

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

Now we can simply use the methods defined on Period and Duration to extract the individual units:

System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
        period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
        duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds

or, using the default format:

System.out.println(period + " + " + duration);
P1Y1D + PT1H29M

Note on years, months & days

Note that, in java.time's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:

LocalDateTime
        start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
        end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
        start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
        end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

In my opinion if src has test/java/ folders then in build path out location should be like target/test-classes.

If src has main/java/ folders then in build path out location should be like target/classes.

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

How to generate a QR Code for an Android application?

Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!

PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.

public static Bitmap generateQrCode(String myCodeText) throws WriterException {
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    QRCodeWriter qrCodeWriter = new QRCodeWriter();

    int size = 256;

    ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
    int width = bitMatrix.width();
    Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < width; y++) {
            bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}

EDIT

It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:

        BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
            }
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

How to run a cron job inside a docker container?

For those who wants to use a simple and lightweight image:

FROM alpine:3.6

# copy crontabs for root user
COPY config/cronjobs /etc/crontabs/root

# start crond with log level 8 in foreground, output to stderr
CMD ["crond", "-f", "-d", "8"]

Where cronjobs is the file that contains your cronjobs, in this form:

* * * * * echo "hello stackoverflow" >> /test_file 2>&1
# remember to end this file with an empty new line

Read only file system on Android

I checked with emulator and following worked.

  1. adb reboot
  2. adb root && adb remount && adb push ~/Desktop/hosts /system/etc/hosts

As mentioned above as well, execute second step in single shot.

link_to image tag. how to add class to a tag

You can also try this

<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo"    %></li>

Where "metas-logo" is a css class with a background image

Importing a csv into mysql via command line

Try this command

 load data local infile 'file.csv' into table table
 fields terminated by ','
 enclosed by '"'
 lines terminated by '\n'
 (column1, column2, column3,...)

The fields here are the actual table fields that the data needs to sit in. The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.

For further details check the manual.

For setting the first row as the table column names, just ignore the row from being read and add the values in the command.

The input is not a valid Base-64 string as it contains a non-base 64 character

Since you're returning a string as JSON, that string will include the opening and closing quotes in the raw response. So your response should probably look like:

"abc123XYZ=="

or whatever...You can try confirming this with Fiddler.

My guess is that the result.Content is the raw string, including the quotes. If that's the case, then result.Content will need to be deserialized before you can use it.

What is the best way to remove accents (normalize) in a Python unicode string?

gensim.utils.deaccent(text) from Gensim - topic modelling for humans:

'Sef chomutovskych komunistu dostal postou bily prasek'

Another solution is unidecode.

Note that the suggested solution with unicodedata typically removes accents only in some character (e.g. it turns 'l' into '', rather than into 'l').

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

How to set date format in HTML date input tag?

<html>

    <body>
        <p id="result">result</p>Enter some text: <input type="date" name="txt" id="value" onchange="myFunction(value)">
        <button onclick="f()">submit</button>
        <script>
            var a;

            function myFunction(val){
                a = val.split("-").reverse().join("-");
                document.getElementById("value").type = "text";
                document.getElementById("value").value = a;
            }

            function f(){
                document.getElementById("result").innerHTML = a;
                var z = a.split("-").reverse().join("-");
                document.getElementById("value").type = "date";
                document.getElementById("value").value = z;
            }

        </script>
    </body>

</html>

Android Spinner : Avoid onItemSelected calls during initialization

I placed a TextView on top of the Spinner, same size and background as the Spinner, so that I would have more control over what it looked like before the user clicks on it. With the TextView there, I could also use the TextView to flag when the user has started interacting.

My Kotlin code looks something like this:

private var mySpinnerHasBeenTapped = false

private fun initializeMySpinner() {

    my_hint_text_view.setOnClickListener {
        mySpinnerHasBeenTapped = true //turn flag to true
        my_spinner.performClick() //call spinner click
    }

    //Basic spinner setup stuff
    val myList = listOf("Leonardo", "Michelangelo", "Rafael", "Donatello")
    val dataAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, myList)
    my_spinner.adapter = dataAdapter

    my_spinner.onItemSelectedListener = object : OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {

            if (mySpinnerHasBeenTapped) { //code below will only run after the user has clicked
                my_hint_text_view.visibility = View.GONE //once an item has been selected, hide the textView
                //Perform action here
            }
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
            //Do nothing
        }
    }
}

Layout file looks something like this, with the important part being that the Spinner and TextView share the same width, height, and margins:

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Spinner
                android:id="@+id/my_spinner"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_for_spinners"

                android:paddingStart="8dp"
                android:paddingEnd="30dp"
                android:singleLine="true" />

            <TextView
                android:id="@+id/my_hint_text_view"
                android:layout_width="match_parent"
                android:layout_height="35dp"                
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_for_spinners"

                android:paddingStart="8dp"
                android:paddingEnd="30dp"
                android:singleLine="true"
                android:gravity="center_vertical"
                android:text="*Select A Turtle"
                android:textColor="@color/green_ooze"
                android:textSize="16sp" />

        </FrameLayout>

I'm sure the other solutions work where you ignore the first onItemSelected call, but I really don't like the idea of assuming it will always be called.

How do I close a tkinter window?

import Tkinter as tk

def quit(root):
    root.destroy()

root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()

generate random double numbers in c++

This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:

#include <functional>
#include <random>

class Rand_double
{
public:
    Rand_double(double low, double high)
    :r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}

    double operator()(){ return r(); }

private:
    std::function<double()> r;
};

#include <iostream>    
int main() {
    // create the random number generator:
    Rand_double rd{0,0.5};

    // print 10 random number between 0 and 0.5
    for (int i=0;i<10;++i){
        std::cout << rd() << ' ';
    }
    return 0;
}

Word-wrap in an HTML table

Problem with

<td style="word-break:break-all;">longtextwithoutspace</td>

is that it will work not so good when text has some spaces, e.g.

<td style="word-break:break-all;">long text with andthenlongerwithoutspaces</td>

If word andthenlongerwithoutspaces fits into table cell in one line but long text with andthenlongerwithoutspaces does not, the long word will be broken in two, instead of being wrapped.

Alternative solution: insert U+200B (ZWSP), U+00AD (soft hyphen) or U+200C (ZWNJ) in every long word after every, say, 20th character (however, see warning below):

_x000D_
_x000D_
td {_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<table style="width: 100%;">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="word-wrap: break-word;">_x000D_
        Looooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooong word_x000D_
      </div>_x000D_
    </td>_x000D_
    <td><span style="display: inline;">Short word</span></td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Warning: inserting additional, zero-length characters does not affect reading. However, it does affect text copied into clipboard (these characters are of course copied as well). If the clipboard text is later used in some search function in the web app... search is going to be broken. Although this solution can be seen in some well known web applications, avoid if possible.

Warning: when inserting additional characters, you should not separate multiple code points within grapheme. See https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries for more info.

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

How to replace all spaces in a string

takes care of multiple white spaces and replaces it for a single character

myString.replace(/\s+/g, "-")

http://jsfiddle.net/aC5ZW/340/

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

how to use concatenate a fixed string and a variable in Python

I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

How can I define fieldset border color?

If you don't want 3D border use:

border:#f00 1px solid;

Make more than one chart in same IPython Notebook cell

I don't know if this is new functionality, but this will plot on separate figures:

df.plot(y='korisnika')
df.plot(y='osiguranika')

while this will plot on the same figure: (just like the code in the op)

df.plot(y=['korisnika','osiguranika'])

I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

How to get store information in Magento?

Get store data

Mage::app()->getStore();

Store Id

Mage::app()->getStore()->getStoreId();

Store code

Mage::app()->getStore()->getCode();

Website Id

Mage::app()->getStore()->getWebsiteId();

Store Name

Mage::app()->getStore()->getName();

Store Frontend Name (see @Ben's answer)

Mage::app()->getStore()->getFrontendName();

Is Active

Mage::app()->getStore()->getIsActive();

Homepage URL of Store

Mage::app()->getStore()->getHomeUrl();

Current page URL of Store

Mage::app()->getStore()->getCurrentUrl();

All of these functions can be found in class Mage_Core_Model_Store

File: app/code/core/Mage/Core/Model/Store.php

How to read a file in other directory in python

For windows you can either use the full path with '\\' ('/' for Linux and Mac) as separator of you can use os.getcwd to get the current working directory and give path in reference to the current working directory

data_dir = os.getcwd()+'\\child_directory'
file = open(data_dir+'\\filename.txt', 'r')

When I tried to give the path of child_diectory entirely it resulted in error. For e.g. in this case:

file = open('child_directory\\filename.txt', 'r')

Resulted in error. But I think it must work or I am doing it somewhat wrong way but it doesn't work for me. The about way always works.

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

Hm, would it be possible to simply do this:

The first time your user opens a pdf, using Javascript you make a popout that basically says "If you cannot see your document, please click HERE". Make "HERE" a big button where it will explain to your user what's the problem. Also make another button "everything's fine". If the user clicks on this one, you remember it, so it isn't displayed in the future.

I'm trying to be practical. Going to great lengths trying to solve this kind of problem "properly" for a small subset of Adobe Reader versions doesn't sound very productive to me.

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address: https://net7mma.codeplex.com/

Or my article @ http://www.codeproject.com/Articles/507218/Managed-Media-Aggregation-using-Rtsp-and-Rtp

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

Ignore .pyc files in git repository

If you want to ignore '.pyc' files globally (i.e. if you do not want to add the line to .gitignore file in every git directory), try the following:

$ cat ~/.gitconfig 
[core]
    excludesFile = ~/.gitignore
$ cat ~/.gitignore
**/*.pyc

[Reference]
https://git-scm.com/docs/gitignore

  • Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig.

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

Configuring angularjs with eclipse IDE

Now you can see the Angularjs tags available as shown below.

AngularJS Tags are available.

VBScript - How to make program wait until process has finished?

You need to tell the run to wait until the process is finished. Something like:

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished

In the script itself, start Excel like so. While debugging start visible:

File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true

Shell script not running, command not found

First:

chmod 777 ./MigrateNshell.sh

Then:

./MigrateNshell.sh

Or, add your program to a directory recognized in your $PATH variable. Example: Path Variable Example Which will then allow you to call your program without ./

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

The new version has changed.. for the latest version use the code below:

$('#UpToDate').datetimepicker({
        format:'MMMM DD, YYYY',
        maxDate:moment(),
        defaultDate:moment()            
    }).on('dp.change',function(e){
        console.log(e);
    });

Cron job every three days

0 0 1-30/3 * *

This would run every three days starting 1st. Here are the 20 scheduled runs -

  • 2015-06-01 00:00:00
  • 2015-06-04 00:00:00
  • 2015-06-07 00:00:00
  • 2015-06-10 00:00:00
  • 2015-06-13 00:00:00
  • 2015-06-16 00:00:00
  • 2015-06-19 00:00:00
  • 2015-06-22 00:00:00
  • 2015-06-25 00:00:00
  • 2015-06-28 00:00:00
  • 2015-07-01 00:00:00
  • 2015-07-04 00:00:00
  • 2015-07-07 00:00:00
  • 2015-07-10 00:00:00
  • 2015-07-13 00:00:00
  • 2015-07-16 00:00:00
  • 2015-07-19 00:00:00
  • 2015-07-22 00:00:00
  • 2015-07-25 00:00:00
  • 2015-07-28 00:00:00

What is the easiest way to parse an INI file in Java?

Or with standard Java API you can use java.util.Properties:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
    props.load(in);
}

Index all *except* one item in python

>>> l = range(1,10)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:2] 
[1, 2]
>>> l[3:]
[4, 5, 6, 7, 8, 9]
>>> l[:2] + l[3:]
[1, 2, 4, 5, 6, 7, 8, 9]
>>> 

See also

Explain Python's slice notation

How to extract the year from a Python datetime object?

If you want the year from a (unknown) datetime-object:

tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)

>>> tijd.timetuple()
time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
>>> tijd.timetuple().tm_year
9999

Execute bash script from URL

The best way to do it is

curl http://domain/path/to/script.sh | bash -s arg1 arg2

which is a slight change of answer by @user77115

Tower of Hanoi: Recursive Algorithm

public static void hanoi(int number, String source, String aux, String dest)
{
    if (number == 1)
    {
        System.out.println(source + " - > "+dest);
    }
    else{
        hanoi(number -1, source, dest, aux);
        hanoi(1, source, aux, dest);
        hanoi(number -1, aux, source, dest);
    }
}

git recover deleted file where no commit was made after the delete

if you are looking for a deleted directory.

 git checkout ./pathToDir/*

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

Access Database opens as read only

alos check the level of access to the shared drive. if the access to the shared drive is read only the file will open in read only format.

How to round up value C# to the nearest integer?

Math.Round(0.5) returns zero due to floating point rounding errors, so you'll need to add a rounding error amount to the original value to ensure it doesn't round down, eg.

Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
Console.ReadKey();

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I ran into this problem too when I copied some text from the Internet. My solution is to trim the text/remove formatting before doing any further processing.

Regex match entire words only

Use word boundaries:

/\b($word)\b/i

Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

overcommit_memory

Controls overcommit of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available.

0 - Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slighly more memory in this mode. This is the default.

1 - Always overcommit. Appropriate for some scientific applications.

2 - Don't overcommit. The total address space commit for the system is not permitted to exceed swap plus a configurable percentage (default is 50) of physical RAM. Depending on the percentage you use, in most situations this means a process will not be killed while attempting to use already-allocated memory but will receive errors on memory allocation as appropriate.

SpringApplication.run main method

You need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        // Recon Logic
    }
}

Why not SpringApplication.run(ReconTool.class, args)

Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).

Example project: https://github.com/mariuszs/spring-run-magic

Center a button in a Linear layout

It would be easier to use relative layouts, but for linear layouts I usually center by making sure the width matches parent :

    android:layout_width="match_parent"

and then just give margins to right and left accordingly.

    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"

Node.js EACCES error when listening on most ports

Running on your workstation

As a general rule, processes running without root privileges cannot bind to ports below 1024.

So try a higher port, or run with elevated privileges via sudo. You can downgrade privileges after you have bound to the low port using process.setgid and process.setuid.

Running on heroku

When running your apps on heroku you have to use the port as specified in the PORT environment variable.

See http://devcenter.heroku.com/articles/node-js

const server = require('http').createServer();
const port = process.env.PORT || 3000;

server.listen(port, () => console.log(`Listening on ${port}`));

What is the best (idiomatic) way to check the type of a Python variable?

isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses.

For example:

 >>> class a_dict(dict):
 ...     pass
 ... 
 >>> type(a_dict()) == type(dict())
 False
 >>> isinstance(a_dict(), dict)
 True
 >>> 

Of course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it.

Remove all files in a directory

Another way I've done this:

os.popen('rm -f ./yourdir')

How to know if other threads have finished?

Many things have been changed in last 6 years on multi-threading front.

Instead of using join() and lock API, you can use

1.ExecutorService invokeAll() API

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

2.CountDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

3.ForkJoinPool or newWorkStealingPool() in Executors is other way

4.Iterate through all Future tasks from submit on ExecutorService and check the status with blocking call get() on Future object

Have a look at related SE questions:

How to wait for a thread that spawns it's own thread?

Executors: How to synchronously wait until all tasks have finished if tasks are created recursively?

matplotlib has no attribute 'pyplot'

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

Merge Two Lists in R

This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

appendList <- function (x, val) 
{
    stopifnot(is.list(x), is.list(val))
    xnames <- names(x)
    for (v in names(val)) {
        x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
            appendList(x[[v]], val[[v]])
        else c(x[[v]], val[[v]])
    }
    x
}

> appendList(first,second)
$a
[1] 1 2

$b
[1] 2 3

$c
[1] 3 4

How link to any local file with markdown syntax?

This is a old question, but to me it still doesn't seem to have a complete answer to the OP's question. The chosen answer about security being the possible issue is actually often not the problem when using the Firefox 'Markdown Viewer' plug-in in my experience. Also, the OP seems to be using MS-Windows, so there is the added issue of specifying different drives.

So, here is a little more complete yet simple answer for the 'Markdown Viewer' plug-in on Windows (and other Markdown renderers I've seen): just enter the local path as you would normally, and if it is an absolute path make sure to start it with a slash. So:

[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)

That last one was probably what the OP was looking for given their example. Note this can also be used to display directories rather than files.

Though late, I hope this helps!

Total width of element (including padding and border) in jQuery

Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight/outerWidth functions to retrieve the width including padding/borders, e.g.

$(elem).outerWidth(); // Returns the width + padding + borders

To include the margin as well, simply pass true:

$(elem).outerWidth( true ); // Returns the width + padding + borders + margins

How to set 24-hours format for date on java?

All u need do is to change the lowercase 'hh' in the pattern to an uppercase letter 'HH'

for Kotlin:

val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())

for java:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

How can I get the corresponding table header (th) from a table cell (td)?

Solution that handles colspan

I have a solution based on matching the left edge of the td to the left edge of the corresponding th. It should handle arbitrarily complex colspans.

I modified the test case to show that arbitrary colspan is handled correctly.

Live Demo

JS

$(function($) {
  "use strict";

  // Only part of the demo, the thFromTd call does the work
  $(document).on('mouseover mouseout', 'td', function(event) {
    var td = $(event.target).closest('td'),
        th = thFromTd(td);
    th.parent().find('.highlight').removeClass('highlight');
    if (event.type === 'mouseover')
      th.addClass('highlight');
  });

  // Returns jquery object
  function thFromTd(td) {
    var ofs = td.offset().left,
        table = td.closest('table'),
        thead = table.children('thead').eq(0),
        positions = cacheThPositions(thead),
        matches = positions.filter(function(eldata) {
          return eldata.left <= ofs;
        }),
        match = matches[matches.length-1],
        matchEl = $(match.el);
    return matchEl;
  }

  // Caches the positions of the headers,
  // so we don't do a lot of expensive `.offset()` calls.
  function cacheThPositions(thead) {
    var data = thead.data('cached-pos'),
        allth;
    if (data)
      return data;
    allth = thead.children('tr').children('th');
    data = allth.map(function() {
      var th = $(this);
      return {
        el: this,
        left: th.offset().left
      };
    }).toArray();
    thead.data('cached-pos', data);
    return data;
  }
});

CSS

.highlight {
  background-color: #EEE;
}

HTML

<table>
    <thead> 
        <tr>
            <th colspan="3">Not header!</th>
            <th id="name" colspan="3">Name</th>
            <th id="address">Address</th>
            <th id="address">Other</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td colspan="2">X</td>
            <td>1</td>
            <td>Bob</td>
            <td>J</td>
            <td>Public</td>
            <td>1 High Street</td>
            <td colspan="2">Postfix</td>
        </tr>
    </tbody>
</table>

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

jQuery: Get selected element tag name

jQuery 1.6+

jQuery('selector').prop("tagName").toLowerCase()

Older versions

jQuery('selector').attr("tagName").toLowerCase()

toLowerCase() is not mandatory.

Change onClick attribute with javascript

Well, just do this and your problem is solved :

document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')

Have a nice day XD

Mac zip compress without __MACOSX folder?

I'm using this Automator Shell Script to fix it after. It's showing up as contextual menu item (right clicking on any file showing up in Finder).

while read -r p; do
  zip -d "$p" __MACOSX/\* || true
  zip -d "$p" \*/.DS_Store || true
done
  1. Create a new Service with Automator
  2. Select "Files and Folders" in "Finder"
  3. Add a "Shell Script Action"

automator shell script

contextual menu item in Finder

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

How can I keep Bootstrap popovers alive while being hovered?

Test with code snippet below:

Small modification (From the solution provided by vikas) to suit my use case.

  1. Open popover on hover event for the popover button
  2. Keep popover open when hovering over the popover box
  3. Close popover on mouseleave for either the popover button, or the popover box.

_x000D_
_x000D_
$(".pop").popover({
    trigger: "manual",
    html: true,
    animation: false
  })
  .on("mouseenter", function() {
    var _this = this;
    $(this).popover("show");
    $(".popover").on("mouseleave", function() {
      $(_this).popover('hide');
    });
  }).on("mouseleave", function() {
    var _this = this;
    setTimeout(function() {
      if (!$(".popover:hover").length) {
        $(_this).popover("hide");
      }
    }, 300);
  });
_x000D_
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
  <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>

  <link rel="stylesheet" href="style.css" />

</head>

<body>
  <h2 class='text-primary'>Another Great "KISS" Bootstrap Popover example!</h2>
  <p class='text-muted'>KISS = Keep It Simple S....</p>

  <p class='text-primary'>Goal:</p>
  <ul>
    <li>Open popover on hover event for the popover button</li>
    <li>Keep popover open when hovering over the popover box</li>
    <li>Close popover on mouseleave for either the popover button, or the popover box.</li>
  </ul>

  <button type="button" class="btn btn-danger pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME
    </button>
  <br><br>
  <button type="button" class="btn btn-info pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    HOVER OVER ME... Again!
    </button><br><br>
  <button type="button" class="btn btn-success pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
    data-original-title="" title="">
    Okay one more time... !
    </button>
  <br><br>
  <p class='text-info'>Hope that helps you... Drove me crazy for a while</p>
  <script src="script.js"></script>
</body>

</html>
_x000D_
_x000D_
_x000D_

How can I trigger the click event of another element in ng-click using angularjs?

So it was a simple fix. Just had to move the ng-click to a scope click handler:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="clickUpload()">Upload</button>



$scope.clickUpload = function(){
    angular.element('#upload').trigger('click');
};

Angular2 Material Dialog css, dialog size

With current version of Angular Material (6.4.7) you can use a custom class:

let dialogRef = dialog.open(UserProfileComponent, {
  panelClass: 'my-class'
});

Now put your class somewhere global (haven't been able to make this work elsewhere), e.g. in styles.css:

.my-class .mat-dialog-container{
  height: 400px;
  width: 600px;
  border-radius: 10px;
  background: lightcyan;
  color: #039be5;
}

Done!

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

It was reproducible only when I use proxy on genymotion(<4.4).

Check your proxy settings in Settings-> Wireless & Networks-> WiFi->(Long Press WiredSSID)-> Modify Network

Select show advanced options: set Proxy settings to NONE.

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

How to print a date in a regular format?

You can do:

mylist.append(str(today))

Using jQuery how to get click coordinates on the target element

$('#something').click(function (e){
    var elm = $(this);
    var xPos = e.pageX - elm.offset().left;
    var yPos = e.pageY - elm.offset().top;

    console.log(xPos, yPos);
});

Outlets cannot be connected to repeating content iOS

Sometimes Xcode could not control over correctly cell outlet connection.

Somehow my current cell’s label/button has connected another cell I just remove those and error goes away.

How to use PHP to connect to sql server

For the following code you have to enable mssql in the php.ini as described at this link: http://www.php.net/manual/en/mssql.installation.php

$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";

$conn = mssql_connect($myServer,$myUser,$myPass);
if (!$conn)
{ 
  die('Not connected : ' . mssql_get_last_message());
} 
$db_selected = mssql_select_db($myDB, $conn);
if (!$db_selected) 
{
  die ('Can\'t use db : ' . mssql_get_last_message());
} 

close vs shutdown socket?

Close

When you have finished using a socket, you can simply close its file descriptor with close; If there is still data waiting to be transmitted over the connection, normally close tries to complete this transmission. You can control this behavior using the SO_LINGER socket option to specify a timeout period; see Socket Options.

ShutDown

You can also shut down only reception or transmission on a connection by calling shutdown.

The shutdown function shuts down the connection of socket. Its argument how specifies what action to perform: 0 Stop receiving data for this socket. If further data arrives, reject it. 1 Stop trying to transmit data from this socket. Discard any data waiting to be sent. Stop looking for acknowledgement of data already sent; don’t retransmit it if it is lost. 2 Stop both reception and transmission.

The return value is 0 on success and -1 on failure.

Drawing a dot on HTML5 canvas

It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate a point with whatever you have.

So basically there are 3 possible solutions:

  • draw point as a line
  • draw point as a polygon
  • draw point as a circle

Each of them has their drawbacks.


Line

function point(x, y, canvas){
  canvas.beginPath();
  canvas.moveTo(x, y);
  canvas.lineTo(x+1, y+1);
  canvas.stroke();
}

Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.


Rectangle

function point(x, y, canvas){
  canvas.strokeRect(x,y,1,1);
}

or in a faster way using fillRect because render engine will just fill one pixel.

function point(x, y, canvas){
  canvas.fillRect(x,y,1,1);
}

Circle

One of the problems with circles is that it is harder for an engine to render them

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.stroke();
}

the same idea as with rectangle you can achieve with fill.

function point(x, y, canvas){
  canvas.beginPath();
  canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
  canvas.fill();
}

Problems with all these solutions:

  • it is hard to keep track of all the points you are going to draw.
  • when you zoom in, it looks ugly

If you are wondering, what is the best way to draw a point, I would go with filled rectangle. You can see my jsperf here with comparison tests

What is the difference between background and background-color

With background you can set all background properties like:

  • background-color
  • background-image
  • background-repeat
  • background-position
    etc.

With background-color you can just specify the color of the background

background: url(example.jpg) no-repeat center center #fff;

VS.

background-image: url(example.jpg);
background-position: center center;
background-repeat: no-repeat;
background-color: #fff;

More info

(See Caption: Background - Shorthand property)

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

File pathBinary = new File("Firefox.exe location");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);

You need to add binary of the browser

or

Best and forever solution: Just add Firefox.exe location to environmental variables

Echo tab characters in bash script

You can also try:

echo Hello$'\t'world.

Installing pip packages to $HOME folder

You can specify the -t option (--target) to specify the destination directory. See pip install --help for detailed information. This is the command you need:

pip install -t path_to_your_home package-name

for example, for installing say mxnet, in my $HOME directory, I type:

pip install -t /home/foivos/ mxnet

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

Globally catch exceptions in a WPF application?

Example code using NLog that will catch exceptions thrown from all threads in the AppDomain, from the UI dispatcher thread and from the async functions:

App.xaml.cs :

public partial class App : Application
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        SetupExceptionHandling();
    }

    private void SetupExceptionHandling()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");

        DispatcherUnhandledException += (s, e) =>
        {
            LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
            e.Handled = true;
        };

        TaskScheduler.UnobservedTaskException += (s, e) =>
        {
            LogUnhandledException(e.Exception, "TaskScheduler.UnobservedTaskException");
            e.SetObserved();
        };
    }

    private void LogUnhandledException(Exception exception, string source)
    {
        string message = $"Unhandled exception ({source})";
        try
        {
            System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception ex)
        {
            _logger.Error(ex, "Exception in LogUnhandledException");
        }
        finally
        {
            _logger.Error(exception, message);
        }
    }

how to increase java heap memory permanently?

You also use this below to expand the memory

export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"

Xmx specifies the maximum memory allocation pool for a Java virtual machine (JVM)

Xms specifies the initial memory allocation pool.

Xss setting memory size of thread stack

XX:MaxPermSize: the maximum permanent generation size

SQL Server format decimal places with commas

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How can I check that two objects have the same set of property names?

To compare two objects along with all attributes of it, I followed this code and it didn't require tostring() or json compar

_x000D_
_x000D_
if(user1.equals(user2))
{
console.log("Both are equal");
}
_x000D_
_x000D_
_x000D_

e.

How to include Javascript file in Asp.Net page

I assume that you are using MasterPage so within your master page you should have

<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

And within any of your pages based on that MasterPage add this

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="js/yourscript.js" type="text/javascript"></script>
</asp:Content>

Best radio-button implementation for IOS

Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.

How do I expand the output display to see more columns of a pandas DataFrame?

You can also try in a loop:

for col in df.columns: 
    print(col) 

Constant pointer vs Pointer to constant

const int* ptr; here think like *ptr is constant and *ptr can't be change again

int * const ptr; while here think like ptr as a constant and that can't be change again

Jasmine.js comparing arrays

just for the record you can always compare using JSON.stringify

const arr = [1,2,3]; expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3])); expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));

It's all meter of taste, this will also work for complex literal objects

Is Google Play Store supported in avd emulators?

Easiest way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:

1- go to C:\Users[user].android\avd[your virtual device folder] open "config.ini" with text editor like notepad

2- change

"PlayStore.enabled=false" to "PlayStore.enabled=true"

3- change

mage.sysdir.1 = system-images\android-30\google_apis\x86\

to

image.sysdir.1 = system-images\android-30\google_apis_playstore\x86\

How to convert a string of bytes into an int?

As Greg said, you can use struct if you are dealing with binary values, but if you just have a "hex number" but in byte format you might want to just convert it like:

s = 'y\xcc\xa6\xbb'
num = int(s.encode('hex'), 16)

...this is the same as:

num = struct.unpack(">L", s)[0]

...except it'll work for any number of bytes.

How to create CSV Excel file C#?

If anyone would like I converted this to an extension method on IEnumerable:

public static class ListExtensions
{
    public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
    {
        StringBuilder sb = new StringBuilder();

        IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

        if (includeHeaderLine)
        {
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(propertyInfo.Name).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        foreach (T obj in listToExport)
        {
            T localObject = obj;

            var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));

            sb.AppendLine(line);
        }

        return sb.ToString();
    }

    private static string SanitizeValuesForCSV(object value, string delimeter)
    {
        string output;

        if (value == null) return "";

        if (value is DateTime)
        {
            output = ((DateTime)value).ToLongDateString();
        }
        else
        {
            output = value.ToString();                
        }

        if (output.Contains(delimeter) || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';

        output = output.Replace("\n", " ");
        output = output.Replace("\r", "");

        return output;
    }
}

jQuery scroll to ID from different page

Combining answers by Petr and Sarfraz, I arrive at the following.

On page1.html:

<a href="page2.html#elementID">Jump</a>

On page2.html:

<script type="text/javascript">
    $(document).ready(function() {
        $('html, body').hide();

        if (window.location.hash) {
            setTimeout(function() {
                $('html, body').scrollTop(0).show();
                $('html, body').animate({
                    scrollTop: $(window.location.hash).offset().top
                    }, 1000)
            }, 0);
        }
        else {
            $('html, body').show();
        }
    });
</script>

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

Visual studio equivalent of java System.out

Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Steps to start Apache httpd.exe (I am using x64 VC11 example here)

http://www.apachelounge.com/download/VC11/

Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe

http://www.microsoft.com/en-us/download/details.aspx?id=30679

You may need to have Visual Studio 2012 Update 3 (VS2012.3)

http://www.microsoft.com/en-us/download/details.aspx?id=30679 (vcredirect.exe)
http://support.microsoft.com/kb/2835600

Unzip httpd-2.4.4-win64-VC11.zip and copy paste in

C:\Apache24

Unzip modules-2.4-win64-VC11.zip and copy paste them in

C:\Apache24\modules

http://www.apachelounge.com/viewtopic.php?p=25091

For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.

http://www.apachelounge.com/download/win64/

In

C:\Apache24\conf\httpd.conf

un-comment (remove # sign) starting below this like copy pasted list in here

# Example:
# LoadModule foo_module modules/mod_foo.so

LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule data_module modules/mod_data.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule filter_module modules/mod_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule heartbeat_module modules/mod_heartbeat.so
LoadModule heartmonitor_module modules/mod_heartmonitor.so
LoadModule ident_module modules/mod_ident.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_debug_module modules/mod_log_debug.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_html_module modules/mod_proxy_html.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reflector_module modules/mod_reflector.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule request_module modules/mod_request.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule sed_module modules/mod_sed.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
LoadModule session_crypto_module modules/mod_session_crypto.so
LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule socache_dbm_module modules/mod_socache_dbm.so
LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule status_module modules/mod_status.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule watchdog_module modules/mod_watchdog.so
LoadModule xml2enc_module modules/mod_xml2enc.so

Then find

C:\Apache24\bin\ApacheMonitor.exe

and double click on it.

Then in Command Prompt (CMD.exe) type

C:\Apache24\bin\httpd.exe

and press enter. It shows any error remaining.

Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.

The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2

After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.

Thank you

iPhone/iOS JSON parsing tutorial

Here's a link to my tutorial, which walks you through :

  • creating a JSON WCF Web Service from scratch (and the problems you'll want to avoid)
  • adapting it to read/write SQL Server data
  • getting an iOS 6 app to use the JSON servies.
  • using the JSON web services with JavaScript

http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm

All source code is provided, free of charge. Enjoy.

iPhone and WireShark

I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.

  1. In Fiddler, Tools -> Fiddler Options -> Connections -> [x] Allow remote computers to connect.
  2. Make sure your windows firewall is disabled.
  3. On the iphone/ipod, go to your wireless settings, use a manual proxy server, enter the fiddler machine's ip address and the same port (defaults to 8888).

Combine two tables that have no common fields

Joining Non-Related Tables

enter image description here

Demo SQL Script

IF OBJECT_ID('Tempdb..#T1') IS NOT NULL  DROP TABLE #T1;

CREATE TABLE #T1 (T1_Name VARCHAR(75));

INSERT INTO #T1 (T1_Name) VALUES ('Animal'),('Bat'),('Cat'),('Duet');

SELECT * FROM #T1;

IF OBJECT_ID('Tempdb..#T2') IS NOT NULL  DROP TABLE #T2;

CREATE TABLE #T2 (T2_Class VARCHAR(10));

INSERT INTO #T2 (T2_Class) VALUES ('Z'),('T'),('H'); 

SELECT * FROM #T2;

To Join Non-Related Tables , we are going to introduce one common joining column of Serial Numbers like below.

SQL Script

SELECT T1.T1_Name,ISNULL(T2.T2_Class,'') AS T2_Class FROM
( SELECT T1_Name,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T1) T1
LEFT JOIN
( SELECT T2_Class,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T2) T2
ON t1.S_NO=T2.S_NO;

jquery live hover

As of jQuery 1.4.1, the hover event works with live(). It basically just binds to the mouseenter and mouseleave events, which you can do with versions prior to 1.4.1 just as well:

$("table tr")
    .mouseenter(function() {
        // Hover starts
    })
    .mouseleave(function() {
        // Hover ends
    });

This requires two binds but works just as well.

How can I find a file/directory that could be anywhere on linux command line?

The find command will take long time, the fastest way to search for file is using locate command, which looks for file names (and path) in a indexed database (updated by command updatedb).

The result will appear immediately with a simple command:

locate {file-name-or-path}

If the command is not found, you need to install mlocate package and run updatedb command first to prepare the search database for the first time.

More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab

How do I use arrays in C++?

Array creation and initialization

As with any other kind of C++ object, arrays can be stored either directly in named variables (then the size must be a compile-time constant; C++ does not support VLAs), or they can be stored anonymously on the heap and accessed indirectly via pointers (only then can the size be computed at runtime).

Automatic arrays

Automatic arrays (arrays living "on the stack") are created each time the flow of control passes through the definition of a non-static local array variable:

void foo()
{
    int automatic_array[8];
}

Initialization is performed in ascending order. Note that the initial values depend on the element type T:

  • If T is a POD (like int in the above example), no initialization takes place.
  • Otherwise, the default-constructor of T initializes all the elements.
  • If T provides no accessible default-constructor, the program does not compile.

Alternatively, the initial values can be explicitly specified in the array initializer, a comma-separated list surrounded by curly brackets:

    int primes[8] = {2, 3, 5, 7, 11, 13, 17, 19};

Since in this case the number of elements in the array initializer is equal to the size of the array, specifying the size manually is redundant. It can automatically be deduced by the compiler:

    int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};   // size 8 is deduced

It is also possible to specify the size and provide a shorter array initializer:

    int fibonacci[50] = {0, 1, 1};   // 47 trailing zeros are deduced

In that case, the remaining elements are zero-initialized. Note that C++ allows an empty array initializer (all elements are zero-initialized), whereas C89 does not (at least one value is required). Also note that array initializers can only be used to initialize arrays; they cannot later be used in assignments.

Static arrays

Static arrays (arrays living "in the data segment") are local array variables defined with the static keyword and array variables at namespace scope ("global variables"):

int global_static_array[8];

void foo()
{
    static int local_static_array[8];
}

(Note that variables at namespace scope are implicitly static. Adding the static keyword to their definition has a completely different, deprecated meaning.)

Here is how static arrays behave differently from automatic arrays:

  • Static arrays without an array initializer are zero-initialized prior to any further potential initialization.
  • Static POD arrays are initialized exactly once, and the initial values are typically baked into the executable, in which case there is no initialization cost at runtime. This is not always the most space-efficient solution, however, and it is not required by the standard.
  • Static non-POD arrays are initialized the first time the flow of control passes through their definition. In the case of local static arrays, that may never happen if the function is never called.

(None of the above is specific to arrays. These rules apply equally well to other kinds of static objects.)

Array data members

Array data members are created when their owning object is created. Unfortunately, C++03 provides no means to initialize arrays in the member initializer list, so initialization must be faked with assignments:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        primes[0] = 2;
        primes[1] = 3;
        primes[2] = 5;
        // ...
    }
};

Alternatively, you can define an automatic array in the constructor body and copy the elements over:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        int local_array[] = {2, 3, 5, 7, 11, 13, 17, 19};
        std::copy(local_array + 0, local_array + 8, primes + 0);
    }
};

In C++0x, arrays can be initialized in the member initializer list thanks to uniform initialization:

class Foo
{
    int primes[8];

public:

    Foo() : primes { 2, 3, 5, 7, 11, 13, 17, 19 }
    {
    }
};

This is the only solution that works with element types that have no default constructor.

Dynamic arrays

Dynamic arrays have no names, hence the only means of accessing them is via pointers. Because they have no names, I will refer to them as "anonymous arrays" from now on.

In C, anonymous arrays are created via malloc and friends. In C++, anonymous arrays are created using the new T[size] syntax which returns a pointer to the first element of an anonymous array:

std::size_t size = compute_size_at_runtime();
int* p = new int[size];

The following ASCII art depicts the memory layout if the size is computed as 8 at runtime:

             +---+---+---+---+---+---+---+---+
(anonymous)  |   |   |   |   |   |   |   |   |
             +---+---+---+---+---+---+---+---+
               ^
               |
               |
             +-|-+
          p: | | |                               int*
             +---+

Obviously, anonymous arrays require more memory than named arrays due to the extra pointer that must be stored separately. (There is also some additional overhead on the free store.)

Note that there is no array-to-pointer decay going on here. Although evaluating new int[size] does in fact create an array of integers, the result of the expression new int[size] is already a pointer to a single integer (the first element), not an array of integers or a pointer to an array of integers of unknown size. That would be impossible, because the static type system requires array sizes to be compile-time constants. (Hence, I did not annotate the anonymous array with static type information in the picture.)

Concerning default values for elements, anonymous arrays behave similar to automatic arrays. Normally, anonymous POD arrays are not initialized, but there is a special syntax that triggers value-initialization:

int* p = new int[some_computed_size]();

(Note the trailing pair of parenthesis right before the semicolon.) Again, C++0x simplifies the rules and allows specifying initial values for anonymous arrays thanks to uniform initialization:

int* p = new int[8] { 2, 3, 5, 7, 11, 13, 17, 19 };

If you are done using an anonymous array, you have to release it back to the system:

delete[] p;

You must release each anonymous array exactly once and then never touch it again afterwards. Not releasing it at all results in a memory leak (or more generally, depending on the element type, a resource leak), and trying to release it multiple times results in undefined behavior. Using the non-array form delete (or free) instead of delete[] to release the array is also undefined behavior.

How to parse dates in multiple formats using SimpleDateFormat

Using DateTimeFormatter it can be achieved as below:


import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.TimeZone;

public class DateTimeFormatTest {

    public static void main(String[] args) {

        String pattern = "[yyyy-MM-dd[['T'][ ]HH:mm:ss[.SSSSSSSz][.SSS[XXX][X]]]]";
        String timeSample = "2018-05-04T13:49:01.7047141Z";
        SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        TemporalAccessor accessor = formatter.parse(timeSample);
        ZonedDateTime zTime = LocalDateTime.from(accessor).atZone(ZoneOffset.UTC);

        Date date=new Date(zTime.toEpochSecond()*1000);
        simpleDateFormatter.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
        System.out.println(simpleDateFormatter.format(date));       
    }
}

Pay attention at String pattern, this is the combination of multiple patterns. In open [ and close ] square brackets you can mention any kind of patterns.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Automatically start a Windows Service on install

Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.

DateTime.MinValue and SqlDateTime overflow

use extensions

public static class DateTimeExtensions
{
    public static DateTime MinValue(this DateTime sqlDateTime)
    {
        return new DateTime(1900, 01, 01, 00, 00, 00);
    }
}


DateTime date = DateTime.Now;
Console.WriteLine("Minvalue is {0} ", date.MinValue().ToShortDateString());

Set element focus in angular way

I like to avoid DOM lookups, watches, and global emitters whenever possible, so I use a more direct approach. Use a directive to assign a simple function that focuses on the directive element. Then call that function wherever needed within the scope of the controller.

Here's a simplified approach for attaching it to scope. See the full snippet for handling controller-as syntax.

Directive:

app.directive('inputFocusFunction', function () {
    'use strict';
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            scope[attr.inputFocusFunction] = function () {
                element[0].focus();
            };
        }
    };
});

and in html:

<input input-focus-function="focusOnSaveInput" ng-model="saveName">
<button ng-click="focusOnSaveInput()">Focus</button>

or in the controller:

$scope.focusOnSaveInput();

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .directive('inputFocusFunction', function() {_x000D_
    'use strict';_x000D_
    return {_x000D_
      restrict: 'A',_x000D_
      link: function(scope, element, attr) {_x000D_
        // Parse the attribute to accomodate assignment to an object_x000D_
        var parseObj = attr.inputFocusFunction.split('.');_x000D_
        var attachTo = scope;_x000D_
        for (var i = 0; i < parseObj.length - 1; i++) {_x000D_
          attachTo = attachTo[parseObj[i]];_x000D_
        }_x000D_
        // assign it to a function that focuses on the decorated element_x000D_
        attachTo[parseObj[parseObj.length - 1]] = function() {_x000D_
          element[0].focus();_x000D_
        };_x000D_
      }_x000D_
    };_x000D_
  })_x000D_
  .controller('main', function() {});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="app" ng-controller="main as vm">_x000D_
  <input input-focus-function="vm.focusOnSaveInput" ng-model="saveName">_x000D_
  <button ng-click="vm.focusOnSaveInput()">Focus</button>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Edited to provide more explanation about the reason for this approach and to extend the code snippet for controller-as use.

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

How to replace a set of tokens in a Java String?

System.out.println(MessageFormat.format("Hello {0}! You have {1} messages", "Join",10L));

Output: Hello Join! You have 10 messages"

How do I prevent mails sent through PHP mail() from going to spam?

<?php 
$to1 = '[email protected]';
$subject = 'Tester subject'; 

    // To send HTML mail, the Content-type header must be set

    $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
    $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
    $headers .= "From: [email protected]" ."\r\n" .
    $headers .= "Organization: Sender Organization\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>

How to change value of object which is inside an array using JavaScript or jQuery?

You can create your specific function like the below, then use that everywhere you need.

var each    = (arr, func) => 
                Array.from(
                    (function* (){
                        var i = 0;
                        for(var item of arr)
                            yield func(item, i++);
                    })()
                );

Enjoy..

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
        {
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Sunken);
            }
            else
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Raised);
            }
        }

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.

change html input type by JS?

Yes, you can even change it by triggering an event

<input type='text' name='pass'  onclick="(this.type='password')" />


<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">

Difference between malloc and calloc?

The calloc() function that is declared in the <stdlib.h> header offers a couple of advantages over the malloc() function.

  1. It allocates memory as a number of elements of a given size, and
  2. It initializes the memory that is allocated so that all bits are zero.

print arraylist element?

You should override toString() method in your Dog class. which will be called when you use this object in sysout.

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

Pretty print in MongoDB shell as default

(note: this is answer to original version of the question, which did not have requirements for "default")

You can ask it to be pretty.

db.collection.find().pretty()

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

This workaround is helpful when this problem pops up.

1) Set Workspace JRE to 1.5 (and apply/save). Projects will rebuild.

2)Set Workspace JRE back to 1.6 (and apply/save). Projects will rebuild.

All errors are then gone (for now at least).

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.