Programs & Examples On #Generic function

What is the most appropriate way to store user settings in Android application

Okay; it's been a while since the answer is kind-of mixed, but here's a few common answers. I researched this like crazy and it was hard to build a good answer

  1. The MODE_PRIVATE method is considered generally safe, if you assume that the user didn't root the device. Your data is stored in plain text in a part of the file system that can only be accessed by the original program. This makings grabbing the password with another app on a rooted device easy. Then again, do you want to support rooted devices?

  2. AES is still the best encryption you can do. Remember to look this up if you are starting a new implementation if it's been a while since I posted this. The largest issue with this is "What to do with the encryption key?"

So, now we are at the "What to do with the key?" portion. This is the hard part. Getting the key turns out to be not that bad. You can use a key derivation function to take some password and make it a pretty secure key. You do get into issues like "how many passes do you do with PKFDF2?", but that's another topic

  1. Ideally, you store the AES key off the device. You have to figure out a good way to retrieve the key from the server safely, reliably, and securely though

  2. You have a login sequence of some sort (even the original login sequence you do for remote access). You can do two runs of your key generator on the same password. How this works is that you derive the key twice with a new salt and a new secure initialization vector. You store one of those generated passwords on the device, and you use the second password as the AES key.

When you log in, you re-derive the key on the local login and compare it to the stored key. Once that is done, you use derive key #2 for AES.

  1. Using the "generally safe" approach, you encrypt the data using AES and store the key in MODE_PRIVATE. This is recommended by a recent-ish Android blog post. Not incredibly secure, but way better for some people over plain text

You can do a lot of variations of these. For example, instead of a full login sequence, you can do a quick PIN (derived). The quick PIN might not be as secure as a full login sequence, but it's many times more secure than plain text

Get Value of a Edit Text field

I hope this one should work:

Integer.valueOf(mEdit.getText().toString());

I tried Integer.getInteger() method instead of valueOf() - it didn't work.

How can I build XML in C#?

For simple cases, I would also suggest looking at XmlOutput a fluent interface for building Xml.

XmlOutput is great for simple Xml creation with readable and maintainable code, while generating valid Xml. The orginal post has some great examples.

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

Consider these filenames:

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.

A canonical path is always an absolute path.

Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

Also note the following example with nio.Paths:

String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";

System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());

While both paths refer to the same location, the output will be quite different:

C:\Windows
C:\Windows\System32\drivers

Get CPU Usage from Windows Command Prompt

The following works correctly on Windows 7 Ultimate from an elevated command prompt:

C:\Windows\system32>typeperf "\Processor(_Total)\% Processor Time"

"(PDH-CSV 4.0)","\\vm\Processor(_Total)\% Processor Time"
"02/01/2012 14:10:59.361","0.648721"
"02/01/2012 14:11:00.362","2.986384"
"02/01/2012 14:11:01.364","0.000000"
"02/01/2012 14:11:02.366","0.000000"
"02/01/2012 14:11:03.367","1.038332"

The command completed successfully.

C:\Windows\system32>

Or for a snapshot:

C:\Windows\system32>wmic cpu get loadpercentage
LoadPercentage
8

var.replace is not a function

Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?

Otherwise, I don't see a problem with your code - the example below works as expected

function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}


trim('    hello   ');  // --> 'hello'

However, if you call your functoin with something non-string, you will indeed get the error above:

trim({});  // --> TypeError: str.replace is not a function

How can I uninstall Ruby on ubuntu?

If you used rbenv to install it, you can use

rbenv versions 

to see which versions you have installed.

Then, use the uninstall command:

rbenv uninstall [-f|--force] <version>

for example:

rbenv uninstall 2.4.0  # Uninstall Ruby 2.4.0

If you installed Rails, it will be removed, too.

How copy data from Excel to a table using Oracle SQL Developer

It's not exactly copy and paste but you can import data from Excel using Oracle SQL Developer.

Navigate to the table you want to import the data into and click on the Data tab.

After clicking on the data tab you should notice a drop down that says Actions... indicating the position of the Data tab and Actions... drop down

Click Actions... and select the bottom option Import Data...

Then just follow the wizard to select the correct sheet, and columns that you want to import.

EDIT : To view the data tab :

  1. Select the SCHEMA where your table is created.(Choose from the Connections tab on the left pane).
  2. Right click on the SCHEMA and choose SCHEMA BROWSER.
  3. Select your table from the list (by giving your schema).
  4. Now you will see the DATA tab.
  5. Click on Actions and Import Data...

Response Content type as CSV

Use text/csv as the content type.

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

How to get the caller class in Java

To get caller/called class name use below code, it works fine for me.

String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();

Print array without brackets and commas

I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ",""); as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.

PostgreSQL - fetch the row which has the Max value for a column

Actaully there's a hacky solution for this problem. Let's say you want to select the biggest tree of each forest in a region.

SELECT (array_agg(tree.id ORDER BY tree_size.size)))[1]
FROM tree JOIN forest ON (tree.forest = forest.id)
GROUP BY forest.id

When you group trees by forests there will be an unsorted list of trees and you need to find the biggest one. First thing you should do is to sort the rows by their sizes and select the first one of your list. It may seems inefficient but if you have millions of rows it will be quite faster than the solutions that includes JOIN's and WHERE conditions.

BTW, note that ORDER_BY for array_agg is introduced in Postgresql 9.0

How to use PHP with Visual Studio

By default VS is not made to run PHP, but you can do it with extensions:

You can install an add-on with the extension manager, PHP Tools for Visual Studio.

If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.

You have also a cool PHP compiler called Phalanger: Phalanger PHP Compiler

If I'm not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.

If you want cool standalone IDE's for PHP: (Free)

Radio buttons and label to display in same line

I wasn't able to reproduce your problem in Google Chrome 4.0, IE8, or Firefox 3.5 using that code. The label and radio button stayed on the same line.

Try putting them both inside a <p> tag, or set the radio button to be inline like The Elite Gentleman suggested.

How can I let a user download multiple files when a button is clicked?

This works in all browsers (IE11, Firefox, Microsoft Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.

<select class="document">
    <option val="word.docx">some word document</option>
</select>

//user clicks a download button to download all selected documents
    $('#downloadDocumentsButton').click(function () {
        var interval = 1000;
        //select elements have class name of "document"
        $('.document').each(function (index, element) {
            var doc = $(element).val();
            if (doc) {
                setTimeout(function () {
                    window.location = doc;
                }, interval * (index + 1));
            }
        });
    });

This solution uses promises:

function downloadDocs(docs) {
    docs[0].then(function (result) {
        if (result.web) {
            window.open(result.doc);
        }
        else {
            window.location = result.doc;
        }
        if (docs.length > 1) {
            setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
        }
    });
}

 $('#downloadDocumentsButton').click(function () {
    var files = [];
    $('.document').each(function (index, element) {
        var doc = $(element).val();
        var ext = doc.split('.')[doc.split('.').length - 1];

        if (doc && $.inArray(ext, docTypes) > -1) {
            files.unshift(Promise.resolve({ doc: doc, web: false }));
        }
        else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
            files.push(Promise.resolve({ doc: doc, web: true }));
        }
    });

    downloadDocs(files);
});

BigDecimal to string

To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.

new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()

will print the "10.0001"

How to get the clicked link's href with jquery?

$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

how to start the tomcat server in linux?

The command you have typed is /startup.sh, if you have to start a shell script you have to fire the command as shown below:

$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh 
or 
$ ./startup.sh 

Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin.

MySQL Error: #1142 - SELECT command denied to user

This error also arises for a syntax error occurred due to aliasing tablename.

For instance, when executed below query,

select * from a.table1, b.table2 where a.table1= b.table2

below error occurs:

MySQL Error: #1142. Response form the database. SELECT command denied to user "username@ip" for table "table1"

Solution : Syntax to alias tablename should be used proper, syntax solution for above instance >select * from table1 a, table2 b where a.table1= b.table2

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

How to justify navbar-nav in Bootstrap 3

You can justify the navbar contents by using:

@media (min-width: 768px){
  .navbar-nav{
     margin: 0 auto;
     display: table;
     table-layout: fixed;
     float: none;
  }
}  

See this live: http://jsfiddle.net/panchroma/2fntE/

Good luck!

How to change my Git username in terminal?

usually the user name resides under git config

git config --global user.name "first last"

although if you still see above doesn't work you could edit .gitconfig under your user directory of mac and update

[user]
        name = gitusername
        email = [email protected]

Converting Integers to Roman Numerals - Java

I have written a very simple solution. All we have to do is divide and find how many times a particular letter(or letter combination occurs) and append that to the StringBuilder object sb. We also should keep track of the remaining number (num).

public static String intToRoman(int num) {
    StringBuilder sb = new StringBuilder();
    int times = 0;
    String[] romans = new String[] { "I", "IV", "V", "IX", "X", "XL", "L",
            "XC", "C", "CD", "D", "CM", "M" };
    int[] ints = new int[] { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500,
            900, 1000 };
    for (int i = ints.length - 1; i >= 0; i--) {
        times = num / ints[i];
        num %= ints[i];
        while (times > 0) {
            sb.append(romans[i]);
            times--;
        }
    }
    return sb.toString();
} 

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

None of the other answers resolved this error for me.
I did find a solution that worked, which I suggest for those in the same situation:

  1. Close Visual Studio
  2. Browse to Projects\yourProject\yourProject
  3. Rename Web.Debug.config and Web.Release.config
  4. Rebuild and run your application

http://localhost:50070 does not work HADOOP

There is a similar question and answer at: Start Hadoop 50075 Port is not resolved

Take a look at your core-site.xml file to determine which port it is set to. If 0, it will randomly pick a port, so be sure to set one.

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]

CSS

a.divlink { 
     display:block;
     width:500px;
     height:500px; 
     float:left;
}

HTML

<div>
    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    </a>
    <a class="divlink" href="yourlink2.html">
         Another text or element
    </a>
</div>

How to add a custom HTTP header to every WCF call?

If you want to add custom HTTP headers to every WCF call in an object oriented way, look no further.

Just as in Mark Good's and paulwhit's answer, we need to subclass IClientMessageInspector to inject the custom HTTP headers into the WCF request. However, lets make the inspector more generic by accepting an dictionary containing the headers we want to add:

public class HttpHeaderMessageInspector : IClientMessageInspector
{
    private Dictionary<string, string> Headers;

    public HttpHeaderMessageInspector(Dictionary<string, string> headers)
    {
        Headers = headers;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        // ensure the request header collection exists
        if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
        {
            request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
        }

        // get the request header collection from the request
        var HeadersCollection = ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers;

        // add our headers
        foreach (var header in Headers) HeadersCollection[header.Key] = header.Value;

        return null;
    }

    // ... other unused interface methods removed for brevity ...
}

Just as in Mark Good's and paulwhit's answer, we need to subclass IEndpointBehavior to inject our HttpHeaderMessageInspector into our WCF client.

public class AddHttpHeaderMessageEndpointBehavior : IEndpointBehavior
{
    private IClientMessageInspector HttpHeaderMessageInspector;

    public AddHttpHeaderMessageEndpointBehavior(Dictionary<string, string> headers)
    {
        HttpHeaderMessageInspector = new HttpHeaderMessageInspector(headers);
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(HttpHeaderMessageInspector);
    }

    // ... other unused interface methods removed for brevity ...
}

The last part needed to finish our object oriented approach, is to create a subclass of our WCF auto-generated client (I used Microsoft's WCF Web Service Reference Guide to generate a WCF client).

In my case, I need to attach an API key to the x-api-key HTML header.

The subclass does the following:

  • calls the constructor of the base class with the required parameters (in my case a EndpointConfiguration enum was generated to pass into the constructor - maybe your implementation won't have this)
  • Defines the headers that should be attached to every requests
  • Attaches AddHttpHeaderMessageEndpointBehavior to the client's Endpoint behaviors
public class Client : MySoapClient
{
    public Client(string apiKey) : base(EndpointConfiguration.SomeConfiguration)
    {
        var headers = new Dictionary<string, string>
        {
            ["x-api-key"] = apiKey
        };

        var behaviour = new AddHttpHeaderMessageEndpointBehavior(headers);
        Endpoint.EndpointBehaviors.Add(behaviour);
    }
}

Finally, use your client!

var apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var client = new Client (apiKey);
var result = client.SomeRequest()

The resulting HTTP request should contain your HTTP headers and look something like this:

POST http://localhost:8888/api/soap HTTP/1.1
Cache-Control: no-cache, max-age=0
Connection: Keep-Alive
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
x-api-key: XXXXXXXXXXXXXXXXXXXXXXXXX
SOAPAction: "http://localhost:8888/api/ISoapService/SomeRequest"
Content-Length: 144
Host: localhost:8888

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <SomeRequestxmlns="http://localhost:8888/api/"/>
  </s:Body>
</s:Envelope>

Populate unique values into a VBA array from Excel

In this situation I always use code like this (just make sure delimeter you've chosen is not a part of search range)

Dim tmp As String
Dim arr() As String

If Not Selection Is Nothing Then
   For Each cell In Selection
      If (cell <> "") And (InStr(tmp, cell) = 0) Then
        tmp = tmp & cell & "|"
      End If
   Next cell
End If

If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)

arr = Split(tmp, "|")

How do I remove blue "selected" outline on buttons?

That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!

Use this to remove this effect:

button {
  outline: none; // this one
}

Android, How to create option Menu

please see :==

private int group1Id = 1;

int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
    menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
    menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
    menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
    menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
    menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);

    return super.onCreateOptionsMenu(menu); 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        // write your code here
        Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
        msg.show();
        return true;

    case 2:
        // write your code here
        return true;

    case 3:
        // write your code here
        return true;

    case 4:
        // write your code here
        return true;

    case 5:
        // write your code here
        return true;

    case 6:
        // write your code here
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

Angular pass callback function to child component as @Input similar to AngularJS way

Another alternative.

The OP asked a way to use a callback. In this case he was referring specifically to a function that process an event (in his example: a click event), which shall be treated as the accepted answer from @serginho suggests: with @Output and EventEmitter.

However, there is a difference between a callback and an event: With a callback your child component can retrieve some feedback or information from the parent, but an event only can inform that something happened without expect any feedback.

There are use cases where a feedback is necessary, ex. get a color, or a list of elements that the component needs to handle. You can use bound functions as some answers have suggested, or you can use interfaces (that's always my preference).

Example

Let's suppose you have a generic component that operates over a list of elements {id, name} that you want to use with all your database tables that have these fields. This component should:

  • retrieve a range of elements (page) and show them in a list
  • allow remove an element
  • inform that an element was clicked, so the parent can take some action(s).
  • allow retrieve the next page of elements.

Child Component

Using normal binding we would need 1 @Input() and 3 @Output() parameters (but without any feedback from the parent). Ex. <list-ctrl [items]="list" (itemClicked)="click($event)" (itemRemoved)="removeItem($event)" (loadNextPage)="load($event)" ...>, but creating an interface we will need only one @Input():

import {Component, Input, OnInit} from '@angular/core';

export interface IdName{
  id: number;
  name: string;
}

export interface IListComponentCallback<T extends IdName> {
    getList(page: number, limit: number): Promise< T[] >;
    removeItem(item: T): Promise<boolean>;
    click(item: T): void;
}

@Component({
    selector: 'list-ctrl',
    template: `
      <button class="item" (click)="loadMore()">Load page {{page+1}}</button>
      <div class="item" *ngFor="let item of list">
          <button (click)="onDel(item)">DEL</button>
          <div (click)="onClick(item)">
            Id: {{item.id}}, Name: "{{item.name}}"
          </div>
      </div>
    `,
    styles: [`
      .item{ margin: -1px .25rem 0; border: 1px solid #888; padding: .5rem; width: 100%; cursor:pointer; }
      .item > button{ float: right; }
      button.item{margin:.25rem;}
    `]
})
export class ListComponent implements OnInit {
    @Input() callback: IListComponentCallback<IdName>; // <-- CALLBACK
    list: IdName[];
    page = -1; 
    limit = 10;

    async ngOnInit() {
      this.loadMore();
    }
    onClick(item: IdName) {
      this.callback.click(item);   
    }
    async onDel(item: IdName){ 
        if(await this.callback.removeItem(item)) {
          const i = this.list.findIndex(i=>i.id == item.id);
          this.list.splice(i, 1);
        }
    }
    async loadMore(){
      this.page++;
      this.list = await this.callback.getList(this.page, this.limit); 
    }
}

Parent Component

Now we can use the list component in the parent.

import { Component } from "@angular/core";
import { SuggestionService } from "./suggestion.service";
import { IdName, IListComponentCallback } from "./list.component";

type Suggestion = IdName;

@Component({
  selector: "my-app",
  template: `
    <list-ctrl class="left" [callback]="this"></list-ctrl>
    <div class="right" *ngIf="msg">{{ msg }}<br/><pre>{{item|json}}</pre></div>
  `,
  styles:[`
    .left{ width: 50%; }
    .left,.right{ color: blue; display: inline-block; vertical-align: top}
    .right{max-width:50%;overflow-x:scroll;padding-left:1rem}
  `]
})
export class ParentComponent implements IListComponentCallback<Suggestion> {
  msg: string;
  item: Suggestion;

  constructor(private suggApi: SuggestionService) {}

  getList(page: number, limit: number): Promise<Suggestion[]> {
    return this.suggApi.getSuggestions(page, limit);
  }
  removeItem(item: Suggestion): Promise<boolean> {
    return this.suggApi.removeSuggestion(item.id)
      .then(() => {
        this.showMessage('removed', item);
        return true;
      })
      .catch(() => false);
  }
  click(item: Suggestion): void {
    this.showMessage('clicked', item);
  }
  private showMessage(msg: string, item: Suggestion) {
    this.item = item;
    this.msg = 'last ' + msg;
  }
}

Note that the <list-ctrl> receives this (parent component) as the callback object. One additional advantage is that it's not required to send the parent instance, it can be a service or any object that implements the interface if your use case allows it.

The complete example is on this stackblitz.

Is it possible to get all arguments of a function as single object inside that function?

In ES6 you can do something like this:

_x000D_
_x000D_
function foo(...args) _x000D_
{_x000D_
   let [a,b,...c] = args;_x000D_
_x000D_
   console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
_x000D_
_x000D_

Convert a String to int?

With a recent nightly, you can do this:

let my_int = from_str::<int>(&*my_string);

What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

How do you exit from a void function in C++?

Use a return statement!

return;

or

if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.

How to add users to Docker container?

To avoid the interactive questions by adduser, you can call it with these parameters:

RUN adduser --disabled-password --gecos '' newuser

The --gecos parameter is used to set the additional information. In this case it is just empty.

On systems with busybox (like Alpine), use

RUN adduser -D -g '' newuser

See busybox adduser

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,

public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
    this.context = context;
    this.listLoanAmount = listLoanAmount;
    this.layoutInflater = LayoutInflater.from(context);
}

at the top of the class create LayoutInflater variable, hope this will help you

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Can someone give an example of cosine similarity, in a very simple, graphical way?

This is a simple Python code which implements cosine similarity.

from scipy import linalg, mat, dot
import numpy as np

In [12]: matrix = mat( [[2, 1, 0, 2, 0, 1, 1, 1],[2, 1, 1, 1, 1, 0, 1, 1]] )

In [13]: matrix
Out[13]: 
matrix([[2, 1, 0, 2, 0, 1, 1, 1],
        [2, 1, 1, 1, 1, 0, 1, 1]])
In [14]: dot(matrix[0],matrix[1].T)/np.linalg.norm(matrix[0])/np.linalg.norm(matrix[1])
Out[14]: matrix([[ 0.82158384]])

Twitter Bootstrap tabs not working: when I click on them nothing happens

This solved it when none of the other examples did:

$('#myTab a').click(function (e) {
  e.preventDefault();
  $(this).tab('show');
});

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Arrays in unix shell?

in bash, you create array like this

arr=(one two three)

to call the elements

$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three

to ask for user input, you can use read

read -p "Enter your choice: " choice

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

Permutations in JavaScript?

Most answers to this question use expensive operations like continuous insertions and deletions of items in an array, or copying arrays reiteratively.

Instead, this is the typical backtracking solution:

function permute(arr) {
  var results = [],
      l = arr.length,
      used = Array(l), // Array of bools. Keeps track of used items
      data = Array(l); // Stores items of the current permutation
  (function backtracking(pos) {
    if(pos == l) return results.push(data.slice());
    for(var i=0; i<l; ++i) if(!used[i]) { // Iterate unused items
      used[i] = true;      // Mark item as used
      data[pos] = arr[i];  // Assign item at the current position
      backtracking(pos+1); // Recursive call
      used[i] = false;     // Mark item as not used
    }
  })(0);
  return results;
}
permute([1,2,3,4]); // [  [1,2,3,4], [1,2,4,3], /* ... , */ [4,3,2,1]  ]

Since the results array will be huge, it might be a good idea to iterate the results one by one instead of allocating all the data simultaneously. In ES6, this can be done with generators:

function permute(arr) {
  var l = arr.length,
      used = Array(l),
      data = Array(l);
  return function* backtracking(pos) {
    if(pos == l) yield data.slice();
    else for(var i=0; i<l; ++i) if(!used[i]) {
      used[i] = true;
      data[pos] = arr[i];
      yield* backtracking(pos+1);
      used[i] = false;
    }
  }(0);
}
var p = permute([1,2,3,4]);
p.next(); // {value: [1,2,3,4], done: false}
p.next(); // {value: [1,2,4,3], done: false}
// ...
p.next(); // {value: [4,3,2,1], done: false}
p.next(); // {value: undefined, done: true}

javascript filter array multiple conditions

Dynamic filters with AND condition

Filter out people with gender = 'm'

_x000D_
_x000D_
var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)
_x000D_
_x000D_
_x000D_

Filter out people with gender = 'm' and name = 'joseph'

_x000D_
_x000D_
var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm',
    name: 'joseph'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)
_x000D_
_x000D_
_x000D_

You can give as many filters as you want.

Capture HTML Canvas as gif/jpg/png/pdf?

Another interesting solution is PhantomJS. It's a headless WebKit scriptable with JavaScript or CoffeeScript.

One of the use case is screen capture : you can programmatically capture web contents, including SVG and Canvas and/or Create web site screenshots with thumbnail preview.

The best entry point is the screen capture wiki page.

Here is a good example for polar clock (from RaphaelJS):

>phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png

Do you want to render a page to a PDF ?

> phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf

Call static methods from regular ES6 class methods

Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

class Super {
  static whoami() {
    return "Super";
  }
  lognameA() {
    console.log(Super.whoami());
  }
  lognameB() {
    console.log(this.constructor.whoami());
  }
}
class Sub extends Super {
  static whoami() {
    return "Sub";
  }
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub

Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.

This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self.

If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.

How to use Java property files?

You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  ...
}

Iterate as:

for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

What are XAND and XOR

There's a simple argument to see where the binary logic gates come from, using truth tables, which have come up already.

There are six that represent commutative operations, in which a op b == b op a. Each binary operator has an associated three column truth table that defines it. The first two columns can be fixed for the defining tables for all the operators.

Consider the third column. It's a sequence of four binary digits. There are sixteen combinations, but the constraint of commutativity effectively removes one row from the truth tables, so it's only eight. Two more get knocked off because all truths or all falses isn't a useful gate. These are the familiar or, and, and xor, plus their negations.

"This operation requires IIS integrated pipeline mode."

This error means the application pool to which your deployed application belongs is not in Integrated mode.

  1. Create a new application pool with .NET 4 version selected, and Managed Pipeline mode as Integrated.
  2. Change your application's app pool to the above created one and try now.

npm install vs. update - what's the difference?

The difference between npm install and npm update handling of package versions specified in package.json:

{
  "name":          "my-project",
  "version":       "1.0",                             // install   update
  "dependencies":  {                                  // ------------------
    "already-installed-versionless-module":  "*",     // ignores   "1.0" -> "1.1"
    "already-installed-semver-module":       "^1.4.3" // ignores   "1.4.3" -> "1.5.2"
    "already-installed-versioned-module":    "3.4.1"  // ignores   ignores
    "not-yet-installed-versionless-module":  "*",     // installs  installs
    "not-yet-installed-semver-module":       "^4.2.1" // installs  installs
    "not-yet-installed-versioned-module":    "2.7.8"  // installs  installs
  }
}

Summary: The only big difference is that an already installed module with fuzzy versioning ...

  • gets ignored by npm install
  • gets updated by npm update

Additionally: install and update by default handle devDependencies differently

  • npm install will install/update devDependencies unless --production flag is added
  • npm update will ignore devDependencies unless --dev flag is added

Why use npm install at all?

Because npm install does more when you look besides handling your dependencies in package.json. As you can see in npm install you can ...

  • manually install node-modules
  • set them as global (which puts them in the shell's PATH) using npm install -g <name>
  • install certain versions described by git tags
  • install from a git url
  • force a reinstall with --force

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

Git Server Like GitHub?

Bare Bones Browser

git instaweb --httpd=webrick

from the git scm book

combine it with something like the approach described here for distributed development (credit to datagrok for the well described concept)

Launch a one-off git server from any local repository.

I tweeted this already but I thought it could use some expansion:

Enable decentralized git workflow: git config alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"

Say you use a git workflow that involves working with a core "official" repository that you pull and push your changes from and into. I'm sure many companies do this, as do many users of git hosting services like Github.

Say that server, or Github, goes down for a bit.

No worries, after all, one of the reasons you use git is so you have a copy of the entire project history in your local clone.

You can keep right on coding and committing, while you wait for the operations team to bring the server back to life. Note to self: buy doughnuts for operations team.

But what if, during this downtime, you want to collaborate with another person, who may not be a git expert, on the same repository?

Or, instead of downtime, what if you and your collaborator are in the field, and for some reason you can't get your VPN to let you connect to your official repo?

Or, what if you and your collaborator are spiking out a bunch of experimental changes, and even though you have access, you don't want to push your unfinished mess into the official central repository? (Not even as feature branches.) Maybe you're in the middle of cleaning up a disastrous rebase or merge and the branches are all over the place.

Well, git, as you are probably aware, is a "distributed" version control system.

Even though you might use a central "official" git repository in your workflow, you still have the ability to use git in a peer-to-peer manner, where you and your collaborator simply build and share commits with each other, and the central server never even has to know.

So, how do you get your branches and commits over to them, or vice versa?

  • You could use git's facilities for e-mailing patches. But that's a bit inelegant and requires some knowledge on their end of how to apply e-mailed patches.
  • You could create an account on your own machine for your collaborator to ssh into. But maybe you don't have local root access, or maybe you don't trust them with SSH access to your box.
  • You could clone your repo onto a thumbdrive and pass it back and forth. But that's rather tedious, especially if you happen to be on the same local network, and requires a thumb drive.

You can probably think of other methods, too. But there's a super easy way: if you can see each other on the network, you can launch a one-off git server that they can use as their remote to clone, fetch, and pull your changes, and kill it when you're done with it.

The tool that enables this is git daemon, which has a lot of options and functionality, but for the purpose of enabling this easy one-off "just serve up the repo I'm in," the way to use it is to create an alias. I like to call it git serve. Run:

git config --global alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"

Using an alias is actually crucial, because git aliases are executed in the base directory of your working tree. So the path '.git' will always point to the right place, no matter where you are within the directory tree of your repository.

Use your new git serve like so:

  1. Run git serve. "Ready to rumble," it will report. Git is bad-ass.
  2. Find out your IP address. Say it's 192.168.1.123.
  3. Say "hey Jane, I'm not ready/able to push these commits up to origin, but you can fetch my commits into your clone by running git fetch git://192.168.1.123/"
  4. Press ctrl+c when you don't want to serve that repo any longer.

You could also tell Jane to git clone git://192.168.1.123/ local-repo-name if she does not yet have a clone of the repository. Or, use git pull git://192.168.1.123/ branchname to do a fetch and merge at once, useful if you are working together on a feature branch.

Note however that you shouldn't do this on hostile networks if you keep secrets in your repository, because there's no authentication. It doesn't advertise its existence, but anybody with a a port scanner can find it, connect to it, and clone your repo.

But it's not super dangerous because it is read-only by default. Read the git daemon man page carefully if you think that you want to enable write access. In the case where you want to obtain your collaborator's commits, it's much safer to leave it read-only, and ask your collaborator to also run this command, so you can pull from them.

Tangentially related: on the subject of one-off servers, if you want to temporarily share a bunch of static files over HTTP: python -m SimpleHTTPServer

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I was able to solve "ORA-00604: error" by Droping with purge.

DROP TABLE tablename PURGE

How to fix a collation conflict in a SQL Server query?

if the database is maintained by you then simply create a new database and import the data from the old one. the collation problem is solved!!!!!

Docker: Container keeps on restarting again on again

In my case nginx container was keep on restarting , I checked logs of nginx container and came to know .crt and .key file of a unrequired domain are having errors , so I removed respective .conf file , .crt and .key and then restarted nginx . That's it nginx is working fine without restarting .

PHP - Move a file into a different folder on the server

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");

How can I import data into mysql database via mysql workbench?

  • Under Server Administration on the Home window select the server instance you want to restore database to (Create New Server Instance if doing it first time).
  • Click on Manage Import/Export
  • Click on Data Import/Restore on the left side of the screen.
  • Select Import from Self-Contained File radio button (right side of screen)
  • Select the path of .sql
  • Click Start Import button at the right bottom corner of window.

Hope it helps.

---Edited answer---

Regarding selection of the schema. MySQL Workbench (5.2.47 CE Rev1039) does not yet support exporting to the user defined schema. It will create only the schema for which you exported the .sql... In 5.2.47 we see "New" target schema. But it does not work. I use MySQL Administrator (the old pre-Oracle MySQL Admin beauty) for my work for backup/restore. You can still download it from Googled trustable sources (search MySQL Administrator 1.2.17).

python replace single backslash with double backslash

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

Match everything except for specified strings

You don't need negative lookahead. There is working example:

/([\s\S]*?)(red|green|blue|)/g

Description:

  • [\s\S] - match any character
  • * - match from 0 to unlimited from previous group
  • ? - match as less as possible
  • (red|green|blue|) - match one of this words or nothing
  • g - repeat pattern

Example:

whiteredwhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredwhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredredgreenredgreenredgreenredgreenredgreenbluewhiteredbluewhiteredbluewhiteredbluewhiteredbluewhiteredwhite

Will be:

whitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhite

Test it: regex101.com

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I can elaborate on the details of DLLs in Windows to help clarify those mysteries to my friends here in *NIX-land...

A DLL is like a Shared Object file. Both are images, ready to load into memory by the program loader of the respective OS. The images are accompanied by various bits of metadata to help linkers and loaders make the necessary associations and use the library of code.

Windows DLLs have an export table. The exports can be by name, or by table position (numeric). The latter method is considered "old school" and is much more fragile -- rebuilding the DLL and changing the position of a function in the table will end in disaster, whereas there is no real issue if linking of entry points is by name. So, forget that as an issue, but just be aware it's there if you work with "dinosaur" code such as 3rd-party vendor libs.

Windows DLLs are built by compiling and linking, just as you would for an EXE (executable application), but the DLL is meant to not stand alone, just like an SO is meant to be used by an application, either via dynamic loading, or by link-time binding (the reference to the SO is embedded in the application binary's metadata, and the OS program loader will auto-load the referenced SO's). DLLs can reference other DLLs, just as SOs can reference other SOs.

In Windows, DLLs will make available only specific entry points. These are called "exports". The developer can either use a special compiler keyword to make a symbol an externally-visible (to other linkers and the dynamic loader), or the exports can be listed in a module-definition file which is used at link time when the DLL itself is being created. The modern practice is to decorate the function definition with the keyword to export the symbol name. It is also possible to create header files with keywords which will declare that symbol as one to be imported from a DLL outside the current compilation unit. Look up the keywords __declspec(dllexport) and __declspec(dllimport) for more information.

One of the interesting features of DLLs is that they can declare a standard "upon load/unload" handler function. Whenever the DLL is loaded or unloaded, the DLL can perform some initialization or cleanup, as the case may be. This maps nicely into having a DLL as an object-oriented resource manager, such as a device driver or shared object interface.

When a developer wants to use an already-built DLL, she must either reference an "export library" (*.LIB) created by the DLL developer when she created the DLL, or she must explicitly load the DLL at run time and request the entry point address by name via the LoadLibrary() and GetProcAddress() mechanisms. Most of the time, linking against a LIB file (which simply contains the linker metadata for the DLL's exported entry points) is the way DLLs get used. Dynamic loading is reserved typically for implementing "polymorphism" or "runtime configurability" in program behaviors (accessing add-ons or later-defined functionality, aka "plugins").

The Windows way of doing things can cause some confusion at times; the system uses the .LIB extension to refer to both normal static libraries (archives, like POSIX *.a files) and to the "export stub" libraries needed to bind an application to a DLL at link time. So, one should always look to see if a *.LIB file has a same-named *.DLL file; if not, chances are good that *.LIB file is a static library archive, and not export binding metadata for a DLL.

How do I write to the console from a Laravel Controller?

I haven't tried this myself, but a quick dig through the library suggests you can do this:

$output = new Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln("<info>my message</info>");

I couldn't find a shortcut for this, so you would probably want to create a facade to avoid duplication.

How do I overload the square-bracket operator in C#?

If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:

public object this[int i] => this.InnerList[i];

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

PHP Session timeout

<?php
session_start();
if($_SESSION['login'] != 'ok')
    header('location: /dashboard.php?login=0');

if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
    // session inactive more than 10 min
    header('location: /logout.php?timeout=1');
}

$_SESSION['last-activity'] = time(); // update last activity time stamp

if(time() - $_SESSION['created'] > 600) {
    // session started more than 10 min ago
    session_regenerate_id(true); // change session id and invalidate old session
    $_SESSION['created'] = time(); // update creation time
}
?>

Enable vertical scrolling on textarea

Here's your CSS

element{
  width: 200px;
  height: 300px;
  overflow-y: auto;
}

Convert JSON String To C# Object

add this ddl to reference to your project: System.Web.Extensions.dll

use this namespace: using System.Web.Script.Serialization;

public class IdName
{
    public int Id { get; set; }
    public string Name { get; set; }
}


   string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
   var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);

   string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
   var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);

How can I roll back my last delete command in MySQL?

Use the BEGIN TRANSACTION command before starting queries. So that you can ROLLBACK things at any point of time.

FOR EXAMPLE:

  1. begin transaction
  2. select * from Student
  3. delete from Student where Id=2
  4. select * from Student
  5. rollback
  6. select * from Student

how can get index & count in vuejs

Using Vue 1.x, use the special variable $index like so:

<li v-for="catalog in catalogs">this index : {{$index + 1}}</li>

alternatively, you can specify an alias as a first argument for v-for directive like so:

<li v-for="(itemObjKey, catalog) in catalogs">
    this index : {{itemObjKey + 1}}
</li>

See : Vue 1.x guide

Using Vue 2.x, v-for provides a second optional argument referencing the index of the current item, you can add 1 to it in your mustache template as seen before:

<li v-for="(catalog, itemObjKey) in catalogs">
    this index : {{itemObjKey + 1}}
</li>

See: Vue 2.x guide

Eliminating the parentheses in the v-for syntax also works fine hence:

<li v-for="catalog, itemObjKey in catalogs">
    this index : {{itemObjKey + 1}}
</li>

Hope that helps.

Key Listeners in python?

There is a way to do key listeners in python. This functionality is available through pynput.

Command line:

$ pip install pynput

Python code:

from pynput import keyboard
# your code here

Determining if an Object is of primitive type

Integer is not a primitive, Class.isPrimitive() is not lying.

Spring JSON request getting 406 (not Acceptable)

check this thread. spring mvc restcontroller return json string p/s: you should add jack son mapping config to your WebMvcConfig class

@Override protected void configureMessageConverters( List<HttpMessageConverter<?>> converters) { // put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON converters.add(new MappingJackson2HttpMessageConverter()); // and probably needs a string converter too for text/plain content-type strings to be properly handled converters.add(new StringHttpMessageConverter()); }

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Rails DB Migration - How To Drop a Table?

You can roll back a migration the way it is in the guide:

http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations

Generate a migration:

rails generate migration revert_create_tablename

Write the migration:

require_relative '20121212123456_create_tablename'

class RevertCreateTablename < ActiveRecord::Migration[5.0]
  def change
    revert CreateTablename    
  end
end

This way you can also rollback and can use to revert any migration

Taking screenshot on Emulator from Android Studio

Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To start the standalone Device Monitor application in Android Studio 3.1 and lower you can run android-sdk/tools/monitor.bat

Run / Open VSCode from Mac Terminal

To set it up, launch VS Code. Then open the Command Palette (??P) and type shell command to find the Shell Command: Install 'code' command in PATH command.enter image description here

https://code.visualstudio.com/docs/setup/mac

How to prepend a string to a column value in MySQL?

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Consider the following servlet conf:

   <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet/*</url-pattern>
    </servlet-mapping>

Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi, it will invoke NewServlet as it is mapped with the pattern described above.

Here:

getRequestURI() =  /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi

We have those ones:

  • getPathInfo()

    returns
    a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information

  • getRequestURI()

    returns
    a String containing the part of the URL from the protocol name up to the query string

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance "2" (with JMH):

class A{}
class B extends A{}

public class InstanceOfTest {

public static final Object a = new A();
public static final Object b = new B();

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testInstanceOf()
{
    return b instanceof A;
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsInstance()
{
    return A.class.isInstance(b);
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsAssignableFrom()
{
    return A.class.isAssignableFrom(b.getClass());
}

public static void main(String[] args) throws RunnerException {
    Options opt = new OptionsBuilder()
            .include(InstanceOfTest.class.getSimpleName())
            .warmupIterations(5)
            .measurementIterations(5)
            .forks(1)
            .build();

    new Runner(opt).run();
}
}

It gives:

Benchmark                            Mode  Cnt  Score   Error  Units
InstanceOfTest.testInstanceOf        avgt    5  1,972 ? 0,002  ns/op
InstanceOfTest.testIsAssignableFrom  avgt    5  1,991 ? 0,004  ns/op
InstanceOfTest.testIsInstance        avgt    5  1,972 ? 0,003  ns/op

So that we can conclude: instanceof as fast as isInstance() and isAssignableFrom() not far away (+0.9% executon time). So no real difference whatever you choose

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

Maven dependency update on commandline

Simple run your project online i.e mvn clean install . It fetches all the latest dependencies that you mention in your pom.xml and built the project

C# find biggest number

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 3, 9, 5 };
        int biggestNumber = numbers.Max();
        Console.WriteLine(biggestNumber);
        Console.ReadLine();
    }
}

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64.

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

i hope this will help of you thanks

mongo - couldn't connect to server 127.0.0.1:27017

This work me:-

In Mongo 3.2 for window, you should start Mongodb service. So, run the Command Prompt as Administrator then net start MongoDB

How to get JavaScript variable value in PHP

Add a cookie with the javascript variable you want to access.

document.cookie="profile_viewer_uid=1";

Then acces it in php via

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];

Set position / size of UI element as percentage of screen size

I think what you want is to set the android:layout_weight,

http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

something like this (I'm just putting text views above and below as placeholders):

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="68"/>
    <Gallery 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="0dp"

        android:layout_weight="16"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="16"/>

  </LinearLayout>

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

How do you run `apt-get` in a dockerfile behind a proxy?

You can use the --build-arg option when you want to build using a Dockerfile.

From a link on https://github.com/docker/docker/issues/14634 , see the section "Build with --build-arg with multiple HTTP_PROXY":

[root@pppdc9prda2y java]# docker build 
  --build-arg https_proxy=$HTTP_PROXY --build-arg http_proxy=$HTTP_PROXY 
  --build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTP_PROXY 
  --build-arg NO_PROXY=$NO_PROXY  --build-arg no_proxy=$NO_PROXY -t java .

NOTE: On your own system, make sure you have set the HTTP_PROXY and NO_PROXY environment variables.

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

    '----------------------------------------------------------------
    '#PURPOSE: Checks whether the supplied db connection is alive and
    '          hasn't had it's TCP connection forcibly closed by remote
    '          host, for example, as happens during an undock event
    '#RETURNS: True if the supplied db is connected and error-free, 
    '          False otherwise
    '#AUTHOR:  Belladonna
    '----------------------------------------------------------------

    Dim i As Long
    Dim cmd As New ADODB.Command

    'Set up SQL command to return 1
    cmd.CommandText = "SELECT 1"
    cmd.ActiveConnection = adoCn

    'Run a simple query, to test the connection
    On Error Resume Next
    i = cmd.Execute.Fields(0)
    On Error GoTo 0

    'Tidy up
    Set cmd = Nothing

    'If i is 1, connection is open
    If i = 1 Then
        adoIsConnected = True
    Else
        adoIsConnected = False
    End If

End Function

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

Adding a splash screen to Flutter apps

The code from Jaldhi Bhatt doesn't works for me.

Flutter throws a 'Navigator operation requested with a context that does not include a Navigator.'

I fixed the code wrapping the Navigator consumer component inside of another component that initialize the Navigator context using routes, as mentioned in this article.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:my-app/view/main-view.dart';

class SplashView extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        home: Builder(
          builder: (context) => new _SplashContent(),
        ),
        routes: <String, WidgetBuilder>{
          '/main': (BuildContext context) => new MainView()}
    );
  }
}

class _SplashContent extends StatefulWidget{

  @override
  _SplashContentState createState() => new _SplashContentState();
}

class _SplashContentState extends State<_SplashContent>
    with SingleTickerProviderStateMixin {

  var _iconAnimationController;
  var _iconAnimation;

  startTimeout() async {
    var duration = const Duration(seconds: 3);
    return new Timer(duration, handleTimeout);
  }

  void handleTimeout() {
    Navigator.pushReplacementNamed(context, "/main");
  }

  @override
  void initState() {
    super.initState();

    _iconAnimationController = new AnimationController(
        vsync: this, duration: new Duration(milliseconds: 2000));

    _iconAnimation = new CurvedAnimation(
        parent: _iconAnimationController, curve: Curves.easeIn);
    _iconAnimation.addListener(() => this.setState(() {}));

    _iconAnimationController.forward();

    startTimeout();
  }

  @override
  Widget build(BuildContext context) {
    return new Center(
        child: new Image(
          image: new AssetImage("images/logo.png"),
          width: _iconAnimation.value * 100,
          height: _iconAnimation.value * 100,
        )
    );
  }
}

How to remove duplicate white spaces in string using Java?

This can be possible in three steps:

  1. Convert the string in to character array (ToCharArray)
  2. Apply for loop on charater array
  3. Then apply string replace function (Replace ("sting you want to replace"," original string"));

HTML/CSS font color vs span style

1st preference external style sheet.

<span class="myClass">test</span>

css

.myClass
{
color:red;
}

2nd preference inline style

<span style="color:red">test</span>

<font> as mentioned is deprecated.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

maven "cannot find symbol" message unhelpful

SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again

WHY SO :
I get this error many times. Most of the times I will try to build my component alone (As I have not made changes elsewhere).

Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times

How to add background-image using ngStyle (angular2)?

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

_x000D_
_x000D_
import { Component, OnInit, Input } from '@angular/core';_x000D_
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';_x000D_
_x000D_
@Component({_x000D_
  selector: 'my-component',_x000D_
  templateUrl: './my-component.component.html',_x000D_
  styleUrls: ['./my-component.component.scss']_x000D_
})_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  public backgroundImg: SafeStyle;_x000D_
  @Input() myObject: any;_x000D_
_x000D_
  constructor(private sanitizer: DomSanitizer) {}_x000D_
_x000D_
  ngOnInit() {_x000D_
     this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
_x000D_
_x000D_
_x000D_

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

According to the new browser policy, the user must interact with DOM first before playing the Audio element.

If you want to play the media on page load then you can simply add autoplay property to audio element in HTML like this

<video id="video" src="./music.mp4" autoplay>

or if you don't want to do autoplay then you can handle this using Javascript. Since the autoplay property is set to true, media will be played, we can simply mute the media.

document.getElementById('video').autoplay = true;
document.getElementById('video').muted = true; 

Imp: Now Whenever you play the media don't forget to turn the muted property to false. Like this

document.getElementById('video').muted = false; 
document.getElementById('video').play();

Or you can also show a simple popup where the user will click the allow button in the modal. So he interacts with DOM first, then you don't need anything to do

How to use glOrtho() in OpenGL?

glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:

OpenGL documentation (my bold)

The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).

The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:

Parallel projections have lines of projection that are parallel both in reality and in the projection plane.

Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".

PHP removing a character in a string

I think that it's better to use simply str_replace, like the manual says:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

What is the most compatible way to install python modules on a Mac?

If you use Python from MacPorts, it has it's own easy_install located at: /opt/local/bin/easy_install-2.6 (for py26, that is). It's not the same one as simply calling easy_install directly, even if you used python_select to change your default python command.

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Accessing items in an collections.OrderedDict by index

If you have pandas installed, you can convert the ordered dict to a pandas Series. This will allow random access to the dictionary elements.

>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'

>>> s = pd.Series(d)

>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar

Border Radius of Table is not working

This is my solution using the wrapper, just removing border-collapse might not be helpful always, because you might want to have borders.

_x000D_
_x000D_
.wrapper {_x000D_
  overflow: auto;_x000D_
  border-radius: 6px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border-style: hidden;_x000D_
_x000D_
  width:100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Column 1</th>_x000D_
        <th>Column 2</th>_x000D_
        <th>Column 3</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>Foo Bar boo</td>_x000D_
        <td>Lipsum</td>_x000D_
        <td>Beehuum Doh</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Dolor sit</td>_x000D_
        <td>ahmad</td>_x000D_
        <td>Polymorphism</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Kerbalium</td>_x000D_
        <td>Caton, gookame kyak</td>_x000D_
        <td>Corona Premium Beer</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

This article helped: https://css-tricks.com/table-borders-inside/

How to style an asp.net menu with CSS

I ran into the issue where the class of 'selected' wasn't being added to my menu item. Turns out that you can't have a NavigateUrl on it for whatever reason.

Once I removed the NavigateUrl it applied the 'selected' css class to the a tag and I was able to apply the background style with:

div.menu ul li a.static.selected
{
    background-color: #bfcbd6 !important;
    color: #465c71 !important;
    text-decoration: none !important;
}

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

What is the difference between new/delete and malloc/free?

new and delete are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).

malloc and free are C functions and they allocate and free memory blocks (in size).

Both use the heap to make the allocation. malloc and free are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).

Extract elements of list at odd positions

You can make use of bitwise AND operator &. Let's see below:

x = [1, 2, 3, 4, 5, 6, 7]
y = [i for i in x if i&1]
>>> 
[1, 3, 5, 7]

Bitwise AND operator is used with 1, and the reason it works because, odd number when written in binary must have its first digit as 1. Let's check

23 = 1 * (2**4) + 0 * (2**3) + 1 * (2**2) + 1 * (2**1) + 1 * (2**0) = 10111
14 = 1 * (2**3) + 1 * (2**2) + 1 * (2**1) + 0 * (2**0) = 1110

AND operation with 1 will only return 1 (1 in binary will also have last digit 1), iff the value is odd.

Check the Python Bitwise Operator page for more.

P.S: You can tactically use this method if you want to select odd and even columns in a dataframe. Let's say x and y coordinates of facial key-points are given as columns x1, y1, x2, etc... To normalize the x and y coordinates with width and height values of each image you can simply perform

for i in range(df.shape[1]):
    if i&1:
        df.iloc[:, i] /= heights
    else:
        df.iloc[:, i] /= widths

This is not exactly related to the question but for data scientists and computer vision engineers this method could be useful.

Cheers!

Show div when radio button selected

 $('input[type="radio"]').change(function(){
      if($("input[name='group']:checked")){
      $(div).show();
    }
  });

Set type for function parameters?

TypeScript is one of the best solution for now

TypeScript extends JavaScript by adding types to the language.

https://www.typescriptlang.org/

Count number of rows by group using dplyr

another approach is to use the double colons:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

Python - List of unique dictionaries

We can do with pandas

import pandas as pd
yourdict=pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[293]: [{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]

Notice slightly different from the accept answer.

drop_duplicates will check all column in pandas , if all same then the row will be dropped .

For example :

If we change the 2nd dict name from john to peter

L=[
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'peter', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]
pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[295]: 
[{'age': 34, 'id': 1, 'name': 'john'},
 {'age': 34, 'id': 1, 'name': 'peter'},# here will still keeping the dict in the out put 
 {'age': 30, 'id': 2, 'name': 'hanna'}]

Correct Way to Load Assembly, Find Class and Call Run() Method

I'm doing exactly what you're looking for in my rules engine, which uses CS-Script for dynamically compiling, loading, and running C#. It should be easily translatable into what you're looking for, and I'll give an example. First, the code (stripped-down):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CSScriptLibrary;

namespace RulesEngine
{
    /// <summary>
    /// Make sure <typeparamref name="T"/> is an interface, not just any type of class.
    /// 
    /// Should be enforced by the compiler, but just in case it's not, here's your warning.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RulesEngine<T> where T : class
    {
        public RulesEngine(string rulesScriptFileName, string classToInstantiate)
            : this()
        {
            if (rulesScriptFileName == null) throw new ArgumentNullException("rulesScriptFileName");
            if (classToInstantiate == null) throw new ArgumentNullException("classToInstantiate");

            if (!File.Exists(rulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", rulesScriptFileName);
            }

            RulesScriptFileName = rulesScriptFileName;
            ClassToInstantiate = classToInstantiate;

            LoadRules();
        }

        public T @Interface;

        public string RulesScriptFileName { get; private set; }
        public string ClassToInstantiate { get; private set; }
        public DateTime RulesLastModified { get; private set; }

        private RulesEngine()
        {
            @Interface = null;
        }

        private void LoadRules()
        {
            if (!File.Exists(RulesScriptFileName))
            {
                throw new FileNotFoundException("Unable to find rules script", RulesScriptFileName);
            }

            FileInfo file = new FileInfo(RulesScriptFileName);

            DateTime lastModified = file.LastWriteTime;

            if (lastModified == RulesLastModified)
            {
                // No need to load the same rules twice.
                return;
            }

            string rulesScript = File.ReadAllText(RulesScriptFileName);

            Assembly compiledAssembly = CSScript.LoadCode(rulesScript, null, true);

            @Interface = compiledAssembly.CreateInstance(ClassToInstantiate).AlignToInterface<T>();

            RulesLastModified = lastModified;
        }
    }
}

This will take an interface of type T, compile a .cs file into an assembly, instantiate a class of a given type, and align that instantiated class to the T interface. Basically, you just have to make sure the instantiated class implements that interface. I use properties to setup and access everything, like so:

private RulesEngine<IRulesEngine> rulesEngine;

public RulesEngine<IRulesEngine> RulesEngine
{
    get
    {
        if (null == rulesEngine)
        {
            string rulesPath = Path.Combine(Application.StartupPath, "Rules.cs");

            rulesEngine = new RulesEngine<IRulesEngine>(rulesPath, typeof(Rules).FullName);
        }

        return rulesEngine;
    }
}

public IRulesEngine RulesEngineInterface
{
    get { return RulesEngine.Interface; }
}

For your example, you want to call Run(), so I'd make an interface that defines the Run() method, like this:

public interface ITestRunner
{
    void Run();
}

Then make a class that implements it, like this:

public class TestRunner : ITestRunner
{
    public void Run()
    {
        // implementation goes here
    }
}

Change the name of RulesEngine to something like TestHarness, and set your properties:

private TestHarness<ITestRunner> testHarness;

public TestHarness<ITestRunner> TestHarness
{
    get
    {
        if (null == testHarness)
        {
            string sourcePath = Path.Combine(Application.StartupPath, "TestRunner.cs");

            testHarness = new TestHarness<ITestRunner>(sourcePath , typeof(TestRunner).FullName);
        }

        return testHarness;
    }
}

public ITestRunner TestHarnessInterface
{
    get { return TestHarness.Interface; }
}

Then, anywhere you want to call it, you can just run:

ITestRunner testRunner = TestHarnessInterface;

if (null != testRunner)
{
    testRunner.Run();
}

It would probably work great for a plugin system, but my code as-is is limited to loading and running one file, since all of our rules are in one C# source file. I would think it'd be pretty easy to modify it to just pass in the type/source file for each one you wanted to run, though. You'd just have to move the code from the getter into a method that took those two parameters.

Also, use your IRunnable in place of ITestRunner.

Detecting EOF in C

EOF is just a macro with a value (usually -1). You have to test something against EOF, such as the result of a getchar() call.

One way to test for the end of a stream is with the feof function.

if (feof(stdin))

Note, that the 'end of stream' state will only be set after a failed read.

In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.

How can I String.Format a TimeSpan object with a custom format in .NET?

Dim duration As New TimeSpan(1, 12, 23, 62)

DEBUG.WriteLine("Time of Travel: " + duration.ToString("dd\.hh\:mm\:ss"))

It works for Framework 4

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

Installing a pip package from within a Jupyter Notebook not working

Alternative option : you can also create a bash cell in jupyter using bash kernel and then pip install geocoder. That should work

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

Get list from pandas DataFrame column headers

In the Notebook

For data exploration in the IPython notebook, my preferred way is this:

sorted(df)

Which will produce an easy to read alphabetically ordered list.

In a code repository

In code I find it more explicit to do

df.columns

Because it tells others reading your code what you are doing.

HTML5 Audio stop function

This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").

<div id="plHolder">
     <audio controls id="player">
     ...
     </audio>
<div>

Then this javascript should work:

function stopAudio() {
    var savePlayer = $('#plHolder').html(); // Save player code
    $('#player').remove(); // Remove player from DOM
    $('#FlHolder').html(savePlayer); // Restore it
}

ANTLR: Is there a simple example?

Note: this answer is for ANTLR3! If you're looking for an ANTLR4 example, then this Q&A demonstrates how to create a simple expression parser, and evaluator using ANTLR4.


You first create a grammar. Below is a small grammar that you can use to evaluate expressions that are built using the 4 basic math operators: +, -, * and /. You can also group expressions using parenthesis.

Note that this grammar is just a very basic one: it does not handle unary operators (the minus in: -1+9) or decimals like .99 (without a leading number), to name just two shortcomings. This is just an example you can work on yourself.

Here's the contents of the grammar file Exp.g:

grammar Exp;

/* This will be the entry point of our parser. */
eval
    :    additionExp
    ;

/* Addition and subtraction have the lowest precedence. */
additionExp
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

/* Multiplication and division have a higher precedence. */
multiplyExp
    :    atomExp
         ( '*' atomExp 
         | '/' atomExp
         )* 
    ;

/* An expression atom is the smallest part of an expression: a number. Or 
   when we encounter parenthesis, we're making a recursive call back to the
   rule 'additionExp'. As you can see, an 'atomExp' has the highest precedence. */
atomExp
    :    Number
    |    '(' additionExp ')'
    ;

/* A number: can be an integer value, or a decimal value */
Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

/* We're going to ignore all white space characters */
WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

(Parser rules start with a lower case letter, and lexer rules start with a capital letter)

After creating the grammar, you'll want to generate a parser and lexer from it. Download the ANTLR jar and store it in the same directory as your grammar file.

Execute the following command on your shell/command prompt:

java -cp antlr-3.2.jar org.antlr.Tool Exp.g

It should not produce any error message, and the files ExpLexer.java, ExpParser.java and Exp.tokens should now be generated.

To see if it all works properly, create this test class:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        parser.eval();
    }
}

and compile it:

// *nix/MacOS
javac -cp .:antlr-3.2.jar ANTLRDemo.java

// Windows
javac -cp .;antlr-3.2.jar ANTLRDemo.java

and then run it:

// *nix/MacOS
java -cp .:antlr-3.2.jar ANTLRDemo

// Windows
java -cp .;antlr-3.2.jar ANTLRDemo

If all goes well, nothing is being printed to the console. This means the parser did not find any error. When you change "12*(5-6)" into "12*(5-6" and then recompile and run it, there should be printed the following:

line 0:-1 mismatched input '<EOF>' expecting ')'

Okay, now we want to add a bit of Java code to the grammar so that the parser actually does something useful. Adding code can be done by placing { and } inside your grammar with some plain Java code inside it.

But first: all parser rules in the grammar file should return a primitive double value. You can do that by adding returns [double value] after each rule:

grammar Exp;

eval returns [double value]
    :    additionExp
    ;

additionExp returns [double value]
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

// ...

which needs little explanation: every rule is expected to return a double value. Now to "interact" with the return value double value (which is NOT inside a plain Java code block {...}) from inside a code block, you'll need to add a dollar sign in front of value:

grammar Exp;

/* This will be the entry point of our parser. */
eval returns [double value]                                                  
    :    additionExp { /* plain code block! */ System.out.println("value equals: "+$value); }
    ;

// ...

Here's the grammar but now with the Java code added:

grammar Exp;

eval returns [double value]
    :    exp=additionExp {$value = $exp.value;}
    ;

additionExp returns [double value]
    :    m1=multiplyExp       {$value =  $m1.value;} 
         ( '+' m2=multiplyExp {$value += $m2.value;} 
         | '-' m2=multiplyExp {$value -= $m2.value;}
         )* 
    ;

multiplyExp returns [double value]
    :    a1=atomExp       {$value =  $a1.value;}
         ( '*' a2=atomExp {$value *= $a2.value;} 
         | '/' a2=atomExp {$value /= $a2.value;}
         )* 
    ;

atomExp returns [double value]
    :    n=Number                {$value = Double.parseDouble($n.text);}
    |    '(' exp=additionExp ')' {$value = $exp.value;}
    ;

Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

and since our eval rule now returns a double, change your ANTLRDemo.java into this:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        System.out.println(parser.eval()); // print the value
    }
}

Again (re) generate a fresh lexer and parser from your grammar (1), compile all classes (2) and run ANTLRDemo (3):

// *nix/MacOS
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .:antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .:antlr-3.2.jar ANTLRDemo            // 3

// Windows
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .;antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .;antlr-3.2.jar ANTLRDemo            // 3

and you'll now see the outcome of the expression 12*(5-6) printed to your console!

Again: this is a very brief explanation. I encourage you to browse the ANTLR wiki and read some tutorials and/or play a bit with what I just posted.

Good luck!

EDIT:

This post shows how to extend the example above so that a Map<String, Double> can be provided that holds variables in the provided expression.

To get this code working with a current version of Antlr (June 2014) I needed to make a few changes. ANTLRStringStream needed to become ANTLRInputStream, the returned value needed to change from parser.eval() to parser.eval().value, and I needed to remove the WS clause at the end, because attribute values such as $channel are no longer allowed to appear in lexer actions.

How to access the elements of a 2D array?

If you have

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

Then

a[1][1]

Will work fine. It points to the second column, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a)

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]]

php convert datetime to UTC

If you have a date in this format YYYY-MM-HH dd:mm:ss, you can actually trick php by adding a UTC at the end of your "datetime string" and use strtotime to convert it.

date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";

This will print this:

2009-01-01 13:00:00
2009-06-01 14:00:00

And as you can see it takes care of the daylight savings time problem as well.

A little strange way to solve it.... :)

How can I view an old version of a file with Git?

Helper to fetch multiple files from a given revision

When trying to resolve merge conflicts, this helper is very useful:

#!/usr/bin/env python3

import argparse
import os
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('revision')
parser.add_argument('files', nargs='+')
args = parser.parse_args()
toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip().decode()
for path in args.files:
    file_relative = os.path.relpath(os.path.abspath(path), toplevel)
    base, ext = os.path.splitext(path)
    new_path = base + '.old' + ext
    with open(new_path, 'w') as f:
        subprocess.call(['git', 'show', '{}:./{}'.format(args.revision, path)], stdout=f)

GitHub upstream.

Usage:

git-show-save other-branch file1.c path/to/file2.cpp

Outcome: the following contain the alternate versions of the files:

file1.old.c
path/to/file2.old.cpp

This way, you keep the file extension so your editor won't complain, and can easily find the old file just next to the newer one.

Fully custom validation error message with Rails

I recommend installing the custom_error_message gem (or as a plugin) originally written by David Easley

It lets you do stuff like:

validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"

In PHP with PDO, how to check the final SQL parametrized query?

You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .

How to change the port of Tomcat from 8080 to 80?

1) Go to conf folder in tomcat installation directory

 e.g. C:\Tomcat 6.0\conf\

2) Edit following tag in server.xml file

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

3) Change the port=8080 value to port=80

4) Save file.

5) Stop your Tomcat and restart it.

How to find the type of an object in Go?

You can just use the fmt package fmt.Printf() method, more information: https://golang.org/pkg/fmt/

example: https://play.golang.org/p/aJG5MOxjBJD

How can I disable HREF if onclick is executed?

It's simpler if you pass an event parameter like this:

<a href="#" onclick="yes_js_login(event);">link</a>
function yes_js_login(e) {
    e.stopImmediatePropagation();
}

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

Android Studio - Failed to apply plugin [id 'com.android.application']

I found the simplest answer to this.

Just go gradle.properties file and change the enableUnitTestBinaryResources from true to false

android.enableUnitTestBinaryResources=false

The snapshot is shown below

enter image description here

Programmatically check Play Store for app updates

enter image description hereGoogle introduced in-app update api. Using that we can ask user to update app inside the application. if user accept we can directly download latest app and install without redirect to playstore. for more details please refer the below link

link1link2

How to set the current working directory?

people using pandas package

import os
import pandas as pd

tar = os.chdir('<dir path only>') # do not mention file name here
print os.getcwd()# to print the path name in CLI

the following syntax to be used to import the file in python CLI

dataset(*just a variable) = pd.read_csv('new.csv')

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

None of the solutions so far completely worked for me when I tried (sometimes, only buggy on secondary loads), but as a workaround, using an object element as described here, then wrapping in a scrollable div, then setting the object to a very high height (5000px) did the job for me. It's a big workaround and doesn't work incredibly well (for starters, pages over 5000px would cause issues -- 10000px completely broke it for me though) but it seems to get the job done in some of my test cases:

var style = 'left: ...px; top: ...px; ' +
        'width: ...px; height: ...px; border: ...';

if (isIOs) {
    style += '; overflow: scroll !important; -webkit-overflow-scrolling: touch !important;';
    html = '<div style="' + style + '">' +
           '<object type="text/html" data="http://example.com" ' +
           'style="width: 100%; height: 5000px;"></object>' +
           '</div>';
}
else {
    style += '; overflow: auto;';
    html = '<iframe src="http://example.com" ' +
           'style="' + style + '"></iframe>';
}

Here's hoping Apple will fix the Safari iFrame issues.

Getting number of elements in an iterator in Python

I like the cardinality package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.

Usage:

>>> import cardinality
>>> cardinality.count([1, 2, 3])
3
>>> cardinality.count(i for i in range(500))
500
>>> def gen():
...     yield 'hello'
...     yield 'world'
>>> cardinality.count(gen())
2

The actual count() implementation is as follows:

def count(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>native</param-value>
</context-param>

Single controller with multiple GET methods in ASP.NET Web API

I am not sure if u have found the answer, but I did this and it works

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET /api/values/5
public string Get(int id)
{
    return "value";
}

// GET /api/values/5
[HttpGet]
public string GetByFamily()
{
    return "Family value";
}

Now in global.asx

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
    name: "DefaultApi2",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Excel VBA - select a dynamic cell range

If you want to select a variable range containing all headers cells:

Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row.

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.

Git command to show which specific files are ignored by .gitignore

Another option that's pretty clean (No pun intended.):

git clean -ndX

Explanation:

$ git help clean

git-clean - Remove untracked files from the working tree
-n, --dry-run - Don't actually remove anything, just show what would be done.
-d - Remove untracked directories in addition to untracked files.
-X - Remove only files ignored by Git.

Note: This solution will not show ignored files that have already been removed.

Is it possible to put CSS @media rules inline?

Inline styles cannot currently contain anything other than declarations (property: value pairs).

You can use style elements with appropriate media attributes in head section of your document.

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

How to re-enable right click so that I can inspect HTML elements in Chrome?

I just visited this site and it really bugged me,

apparently there are a couple ways to disable the mouse click:

1)

<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
function disableclick(event)
{
  if(event.button==2)
   {
     alert(status);
     return false;    
   }
}
</script>

and

<body oncontextmenu="return false">

...

in this case what you will have to do in the dev tools is :

document.removeEventListener("onmousedown",disableclick);
document.oncontextmenu = function(){}

2)

using flash as a content wrapper - no solution here except taking a screenshot

3)

some sites want to prevent downloading images via right click -> save image as

so what they do is put this:

<div style="background-image: url(YourImage.jpg);">
   <img src="transparent.gif"/>
</div>

which is a transparent image spreding on the full width and height of the screen all you need to do is go to the elements inspector and find the div and delete it.

In my case #1 did the trick

Get the IP address of the machine

Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the netdevice(7) man page.

Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How do you transfer or export SQL Server 2005 data to Excel

It's a LOT easier just to do it from within Excel.!! Open Excel Data>Import/Export Data>Import Data Next to file name click "New Source" Button On Welcome to the Data Connection Wizard, choose Microsoft SQL Server. Click Next. Enter Server Name and Credentials. From the drop down, choose whichever database holds the table you need. Select your table then Next..... Enter a Description if you'd like and click Finish. When your done and back in Excel, just click "OK" Easy.

How can I use Guzzle to send a POST request in JSON?

I use the following code that works very reliably.

The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.

The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.

If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.

    public function callAPI($request, $searchType) {
    $guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);

    try {
        $result = $guzzleClient->post( $searchType, ["json" => $request]);
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error .= '<pre>'.print_r($request, $return=true).'</pre>';
        $error .= 'No returnable data';
        Event::logError(__LINE__, __FILE__, $error);
        return false;
    }
    return json_decode($result->getBody(), $return=true);
}

How to get the sizes of the tables of a MySQL database?

Adapted from ChapMic's answer to suite my particular need.

Only specify your database name, then sort all the tables in descending order - from LARGEST to SMALLEST table inside selected database. Needs only 1 variable to be replaced = your database name.

SELECT 
table_name AS `Table`, 
round(((data_length + index_length) / 1024 / 1024), 2) AS `size`
FROM information_schema.TABLES 
WHERE table_schema = "YOUR_DATABASE_NAME_HERE"
ORDER BY size DESC;

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

Extract Google Drive zip from Google colab notebook

Mount GDrive:

from google.colab import drive
drive.mount('/content/gdrive')

Open the link -> copy authorization code -> paste that into the prompt and press "Enter"

Check GDrive access:

!ls "/content/gdrive/My Drive"

Unzip (q stands for "quiet") file from GDrive:

!unzip -q "/content/gdrive/My Drive/dataset.zip"

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

How can I convert a PFX certificate file for use with Apache on a linux server?

Additionally to

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key

I also generated Certificate Authority (CA) certificate:

openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts

And included it in Apache config file:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 SSLCACertificateFile /path/to/domain-ca.crt
 ...
</VirtualHost>

Difference between "module.exports" and "exports" in the CommonJs Module System

Also, one things that may help to understand:

math.js

this.add = function (a, b) {
    return a + b;
};

client.js

var math = require('./math');
console.log(math.add(2,2); // 4;

Great, in this case:

console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true

Thus, by default, "this" is actually equals to module.exports.

However, if you change your implementation to:

math.js

var add = function (a, b) {
    return a + b;
};

module.exports = {
    add: add
};

In this case, it will work fine, however, "this" is not equal to module.exports anymore, because a new object was created.

console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false

And now, what will be returned by the require is what was defined inside the module.exports, not this or exports, anymore.

Another way to do it would be:

math.js

module.exports.add = function (a, b) {
    return a + b;
};

Or:

math.js

exports.add = function (a, b) {
    return a + b;
};

Creating a zero-filled pandas data frame

You can try this:

d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)

Options for initializing a string array

Basic:

string[] myString = new string[]{"string1", "string2"};

or

string[] myString = new string[4];
myString[0] = "string1"; // etc.

Advanced: From a List

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

From StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();

Fixing Sublime Text 2 line endings?

The comment states

// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).

You are setting

"default_line_ending": "LF",

You should set

"default_line_ending": "unix",

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After reading several suggestions here and combining the ideas, for me following changes in /etc/ImageMagick-6/policy.xml were necessary:

<policy domain="coder" rights="read|write" pattern="PDF" />

... rights="none" did not help. ...pattern="LABEL" was not neccessary. Although I do not work with big png files (only ~1 Mb) some changes in memory limits were also necessary:

<policy domain="resource" name="memory" value="2GiB"/>

(instead of 256Mib), and

<policy domain="resource" name="area" value="2GB"/>

(instead of 128 MB)

How to recover corrupted Eclipse workspace?

One more solution that I've discovered by accident, and may help someone:

  1. Back up the corrupted workspace.
  2. Move half of you projects to some temporary location.
  3. Start Eclipse, if it works, go to step 5.
  4. Move the half of projects you've removed back into the workspace, move out the other half. If you've already done that, keep removing/readding your projects in a binary search manner. Go to step 3.
  5. Exit Eclipse, move back all your projects, and start it again. You should see now that some of your projects are closed (and in the wrong working sets). Re-open your projects and move them to the correct working sets.

In my case, it was a project that got corrupted, and not the entire workspace (attempting to import said project into a fresh workspace caused it to fail as well). So, I've started to search for the faulty project - instead, I got the result described above.

How to convert buffered image to image and vice-versa?

Just an information: let us all remember that the Image class is actually an abstract class and referencing a variable of this with a BufferedImage only stores or returns any Object's memory adress.

Also, wherefore, static java.awt.image.imageIO's read() method returns a BufferedImage object, therefore no doubt that using operator/expression instanceof BufferedImage on that object will return true.

In fact, being abstract, Image class has such method signatures as:

  1. public abstract Graphics getGraphics()
  2. public abstract ImageProducer getSource()

among others.

I emphasize, an actual Image variable only holds memory adress of a concrete Image-subclass object, almost like pointers in C, C++, Ada, etc.

If you're introduced or advanced in those languages, and also of Java interface instances like Runnable, javax.sound.Clip, AWT's Shape, etc.. . Take note that Image has: public abstract Image getScaledInstance(...) - you get the point. (Of course, scaling in 2D Graphics programming is interchangeable to resizing, for which precision is desirable).

But in an impossible case when herein ImageIO method return ! (instanceof BufferedImage) just create a new BufferedImage object with this ImgObjNotInstncfBufImg apassed to one of its constructor argument. Then, at (rational) will manipulate this in the logic of your code.

Anyways, the Affine Transform class is appropriate for transforming Shapes and Images to thier scaled, rotated, relocated, etc forms, so I recommend you to study about using an "affine transform".

Take note that you can manipulate the actual pixels in such Image's Raster - well another technical 2D Graphics jargon which must be referenced from a technical glossary - which perhaps a excercised skill in Java ways of binary blitwise operations will be needed, in types of Image buffers that store individual color attributes in a compact in of 32-bytes - 7-bits each for the alpha and RGB values.

I suspect your gonna use it in layering images. So, FINALLY, the rational is that you only reference BufferedImage with the abstract Image, and if ever your Image object isn't a BufferedImage one yet, then you can just make an image out of this related-but-non-BufferedImage-instance without having to worry about any conversion, casting, autoboxing or whatever; manipulating a BufferedImage really means manipulating also the underlying root Image data-bearing object that it points to.

Okay, finished; I think I certainly extracted and splintered out what deadlock you may have thought you are facing to. As I have said abstract classes in java, and also interfaces, are very much the equivaleng of the low-level, more-close-to-hardware operators called pointers in other languages.

logout and redirecting session in php

Use this instead:

<?
session_start();
session_unset();
session_destroy();

header("location:home.php");
exit();
?>

How to add extra whitespace in PHP?

To render more than one whitespace on most web browsers use &nbsp; instead of normal white spaces.

echo "<p>Hello &nbsp;&nbsp;&nbsp; punt"; // This will render as Hello   Punt (with 4 white spaces)
echo "<p> Hello       punt"; // This will render as Hello punt (with one space)

For showing data in raw format (with exact number of spaces and "enters") use HTML <pre> tag.

echo "<pre>Hello        punt</pre>"; //Will render exactly as written here (8 white spaces)

Or you can use some CSS to style current block, not to break text or strip spaces (I don't know, but this one)

Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

Textarea resize control is available via the CSS3 resize property:

textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }

Allowable values self-explanatory: none (disables textarea resizing), both, vertical and horizontal.

Notice that in Chrome, Firefox and Safari the default is both.

If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height, max-width, min-height, and min-width CSS properties to provide resizing within certain proportions.

Code example:

_x000D_
_x000D_
#textarea-wrapper {_x000D_
  padding: 10px;_x000D_
  background-color: #f4f4f4;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
  min-height:50px;_x000D_
  max-height:120px;_x000D_
  width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
  resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
  <label for="resize-default">Textarea (default):</label>_x000D_
  <textarea name="resize-default" id="resize-default"></textarea>_x000D_
  _x000D_
  <label for="resize-vertical">Textarea (vertical):</label>_x000D_
  <textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot connect to repo with TortoiseSVN

As stated by David W. "First of all, check your URL" - Our dns entry changed breaking all svn repo connections. Connecting on ip instead of url as Wes stated worked - (now we have to fix our dns)

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

VirtualBox error "Failed to open a session for the virtual machine"

maybe it is caused by privilege, please try this:

#sudo chmod 755 /Applications 
#sudo chmod 755 /Applications/Virtualbox.app

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

How do I redirect with JavaScript?

You can't redirect to a function. What you can do is pass some flag on the URL when redirecting, then check that flag in the server side code and if raised, execute the function.

For example:

document.location = "MyPage.php?action=DoThis";

Then in your PHP code check for "action" in the query string and if equal to "DoThis" execute whatever function you need.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

After stumbling around, this worked for me:

df = df.astype(object).where(pd.notnull(df),None)

How to view changes made to files on a certain revision in Subversion

Call this in the project:

svn diff -r REVNO:HEAD --summarize

REVNO is the start revision number and HEAD is the end revision number. If HEAD is equal to the last revision number, it can skip it.

The command returns a list with all files that are changed/added/deleted in this revision period.

The command can be called with the URL revision parameter to check changes like this:

svn diff -r REVNO:HEAD --summarize SVN_URL

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

How to get the values of a ConfigurationSection of type NameValueSectionHandler

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }

The usage is straightforward:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

For me, this works only Steps for MIUI 9 and Above:

Settings -> Additional Settings -> Developer options ->

Turn off "MIUI optimization" and Restart

Turn On "USB Debugging"

Turn On "Install via USB"

Set USB Configuration to Charging

MTP(Media Transfer Protocol) is the default mode. Works even in MTP in some cases

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I had the same error happening when I had two different ASP.net projects in two different Visual Studio instances.
Closing one of them fixed the issue.

How to check if a value exists in an object using JavaScript

you can try this one

var obj = {
  "a": "test1",
  "b": "test2"
};

const findSpecificStr = (obj, str) => {
  return Object.values(obj).includes(str);
}

findSpecificStr(obj, 'test1');

Set Response Status Code

Why not using Cakes Response Class? You can set the status code of the response simply by this:

$this->response->statusCode(200);

Then just render a file with the error message, which suits best with JSON.

How to put text in the upper right, or lower right corner of a "box" using css

_x000D_
_x000D_
<div style="position: relative; width: 250px;">_x000D_
  <div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;">_x000D_
    here_x000D_
  </div>_x000D_
  <div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;">_x000D_
    and here_x000D_
  </div>_x000D_
  Lorem Ipsum etc <br />_x000D_
  blah <br />_x000D_
  blah blah <br />_x000D_
  blah <br />_x000D_
  lorem ipsums_x000D_
</div>
_x000D_
_x000D_
_x000D_

Gets you pretty close, although you may need to tweak the "top" and "bottom" values.

What is the difference between statically typed and dynamically typed languages?

Compiled vs. Interpreted

"When source code is translated"

  • Source Code: Original code (usually typed by a human into a computer)
  • Translation: Converting source code into something a computer can read (i.e. machine code)
  • Run-Time: Period when program is executing commands (after compilation, if compiled)
  • Compiled Language: Code translated before run-time
  • Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.


Python Example

Dynamic, Interpreted

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.


Go Example

Static, Compiled

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.


Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.


More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

num = 2
num = '3' // ERROR

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.