Programs & Examples On #Ofstream

Output file streams are C++ standard library objects used to write to files.

Read file line by line using ifstream in C++

Although there is no need to close the file manually but it is good idea to do so if the scope of the file variable is bigger:

    ifstream infile(szFilePath);

    for (string line = ""; getline(infile, line); )
    {
        //do something with the line
    }

    if(infile.is_open())
        infile.close();

What is a LAMP stack?

The reason they call it a stack is because each level derives off its base layer. Your operating system, Linux, is the base layer. Then Apache, your web daemon sits on top of your OS. Then your database stores all the information served by your web daemon, and PHP (or any P* scripting language) is used to drive and display all the data, and allow for user interaction.

Don't be overly concerned with the term 'stack'. People really just mean software suite or bundle, but you're using it just fine I am sure as you are.

Just disable scroll not hide it?

I have made this one function, that solves this problem with JS. This principle can be easily extended and customized that is a big pro for me.

Using this js DOM API function:

const handleWheelScroll = (element) => (event) => {
  if (!element) {
    throw Error("Element for scroll was not found");
  }
  const { deltaY } = event;
  const { clientHeight, scrollTop, scrollHeight } = element;
  if (deltaY < 0) {
    if (-deltaY > scrollTop) {
      element.scrollBy({
        top: -scrollTop,
        behavior: "smooth",
      });
      event.stopPropagation();
      event.preventDefault();
    }
    return;
  }

  if (deltaY > scrollHeight - clientHeight - scrollTop) {
    element.scrollBy({
      top: scrollHeight - clientHeight - scrollTop,
      behavior: "smooth",
    });
    event.stopPropagation();
    event.preventDefault();
    return;
  }
};

In short, this function will stop event propagation and default behavior if the scroll would scroll something else then the given element (the one you want to scroll in).

Then you can hook and unhook this up like this:

const wheelEventHandler = handleWheelScroll(elementToScrollIn);

window.addEventListener("wheel", wheelEventHandler, {
    passive: false,
});

window.removeEventListener("wheel", wheelEventHandler);

Watch out for that it is a higher order function so you have to keep a reference to the given instance.

I hook the addEventListener part in mouse enter and unhook the removeEventListener in mouse leave events in jQuery, but you can use it as you like.

What is the default boolean value in C#?

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

Remember that using uninitialized variables in C# is not allowed.

With

bool foo = new bool();

foo will have the default value.

Boolean default is false

Android Split string

String s = "String="

String[] str = s.split("="); //now str[0] is "hello" and str[1] is "goodmorning,2,1"

add this string

MySQL: #126 - Incorrect key file for table

Go to /etc/mysql/my.cnf and comment out tmpfs

#tmpdir=/var/tmpfs

This fixes the problem.

I ran the command suggested in another answer and while the directory is small, it was empty, so space was not the issue.

/var/tmp$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/vzfs              60G   51G  9.5G  85% /
none                  1.5G  4.0K  1.5G   1% /dev
tmpfs                 200M     0  200M   0% /var/tmpfs
/var/tmpfs$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/vzfs              60G   51G  9.5G  85% /
none                  1.5G  4.0K  1.5G   1% /dev
tmpfs                 200M     0  200M   0% /var/tmpfs

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have found a 2nd solution.

  1. Press "Debug" button in the popup.
  2. Press Ctrl+Pause|Break twice.
  3. Hit the play button to continue.
  4. Save the file after completion.

Hope this helps someone.

Failed to build gem native extension — Rails install

sudo apt-get install ruby-dev

worked for me

Vue 2 - Mutating props vue-warn

Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)

What is InputStream & Output Stream? Why and when do we use them?

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

Codeigniter how to create PDF

Please click on this link it should work ..

http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/

Or you can see below

There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.

I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.

Now, let’s start with implimentation of the code.

Download the TCPDF library code, you can download it from TCPDF website http://www.tcpdf.org/.

Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.

Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file

Helper: application/helpers/pdf_helper.php

function tcpdf()
{
    require_once('tcpdf/config/lang/eng.php');
    require_once('tcpdf/tcpdf.php');
}

Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.

Controller: application/controllers/createpdf.php

function pdf()
{
    $this->load->helper('pdf_helper');
    /*
        ---- ---- ---- ----
        your code here
        ---- ---- ---- ----
    */
    $this->load->view('pdfreport', $data);
}

Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF example codes as it is in our current controller or view. Now in out current view “pdfreport” copy the given code below:

View: application/views/pdfreport.php

tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
    // we can have any view part here like HTML, PHP etc
    $content = ob_get_contents();
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');

Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,modifications in PDF file by using TCPDF library.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

Laravel update model with unique validation rule for attribute

You can trying code bellow

return [
    'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
    'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
    'password' => 'required|min:6',
    'confirm-password' => 'required|same:password',
];

docker entrypoint running bash script gets "permission denied"

If you do not use DockerFile, you can simply add permission as command line argument of the bash:

docker run -t <image>  /bin/bash -c "chmod +x /usr/src/app/docker-entrypoint.sh; /usr/src/app/docker-entrypoint.sh"

How to connect to SQL Server from command prompt with Windows authentication

type sqlplus/"as sysdba" in cmd for connection in cmd prompt

WindowsError: [Error 126] The specified module could not be found

If you are using GCC to compile it for Windows, it's possible that the error is because dependent libraries can't be found.

Using the -static flag if linking with GCC might fix that.

Trigger function when date is selected with jQuery UI datepicker

Working demo : http://jsfiddle.net/YbLnj/

Documentation: http://jqueryui.com/demos/datepicker/

code

$("#dt").datepicker({
    onSelect: function(dateText, inst) {
        var date = $(this).val();
        var time = $('#time').val();
        alert('on select triggered');
        $("#start").val(date + time.toString(' HH:mm').toString());

    }
});

Reflection generic get field value

You should pass the object to get method of the field, so

  Field field = object.getClass().getDeclaredField(fieldName);    
  field.setAccessible(true);
  Object value = field.get(object);

How to get the difference between two arrays of objects in JavaScript

you can do diff a on b and diff b on a, then merge both results

_x000D_
_x000D_
let a = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" },_x000D_
    { value: "4", display: "Ryan" }_x000D_
]_x000D_
_x000D_
let b = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" }_x000D_
]_x000D_
_x000D_
// b diff a_x000D_
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));_x000D_
_x000D_
// a diff b_x000D_
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));  _x000D_
_x000D_
// show merge _x000D_
console.log([...resultA, ...resultB]);
_x000D_
_x000D_
_x000D_

How to Refresh a Component in Angular

just do this : (for angular 9)

import { Inject } from '@angular/core';    
import { DOCUMENT } from '@angular/common';

constructor(@Inject(DOCUMENT) private document: Document){ }

someMethode(){ this.document.location.reload(); }

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I was having the exact same problem. I considered the answer @Snarfblam provided; however, if you read the documentation on MSDN, the ProcessCMDKey method is meant to override key events for menu items in an application.

I recently stumbled across this article from microsoft, which looks quite promising: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx. According to microsoft, the best thing to do is set e.IsInputKey=true; in the PreviewKeyDown event after detecting the arrow keys. Doing so will fire the KeyDown event.

This worked quite well for me and was less hack-ish than overriding the ProcessCMDKey.

Postgres FOR LOOP

Below is example you can use:

create temp table test2 (
  id1  numeric,
  id2  numeric,
  id3  numeric,
  id4  numeric,
  id5  numeric,
  id6  numeric,
  id7  numeric,
  id8  numeric,
  id9  numeric,
  id10 numeric) 
with (oids = false);

do
$do$
declare
     i int;
begin
for  i in 1..100000
loop
    insert into test2  values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;

Where am I? - Get country

Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();

Since it is the sim code it also should not change when traveling to other countries.

How to search JSON data in MySQL?

If your are using MySQL Latest version following may help to reach your requirement.

select * from products where attribs_json->"$.feature.value[*]" in (1,3)

When is del useful in Python?

When is del useful in python?

You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[]. This may be useful if for example you are in os.walk and wish to delete an element in the directory. I would not consider a keyword useful for this though, since one could just make a [].remove(index) method (the .remove method is actually search-and-remove-first-instance-of-value).

How do I implement interfaces in python?

interface supports Python 2.7 and Python 3.4+.

To install interface you have to

pip install python-interface

Example Code:

from interface import implements, Interface

class MyInterface(Interface):

    def method1(self, x):
        pass

    def method2(self, x, y):
        pass


class MyClass(implements(MyInterface)):

    def method1(self, x):
        return x * 2

    def method2(self, x, y):
        return x + y

How to trigger event in JavaScript?

A working example:

// Add an event listener
document.addEventListener("name-of-event", function(e) {
  console.log(e.detail); // Prints "Example of an event"
});

// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);

For older browsers polyfill and more complex examples, see MDN docs.

See support tables for EventTarget.dispatchEvent and CustomEvent.

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

How do CSS triangles work?

here is another fiddle:

.container:after {
    position: absolute;
    right: 0;
    content: "";
    margin-right:-50px;
    margin-bottom: -8px;
    border-width: 25px;
    border-style: solid;
    border-color: transparent transparent transparent #000;
    width: 0;
    height: 0;
    z-index: 10;
    -webkit-transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
    transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
    bottom: 21px;
}
.container {
    float: left;
    margin-top: 100px;
    position: relative;
    width: 150px;
    height: 80px;
    background-color: #000;
}

.containerRed {
    float: left;
    margin-top: 100px;
    position: relative;
    width: 100px;
    height: 80px;
    background-color: red;
}

https://jsfiddle.net/qdhvdb17/

How to add a new line of text to an existing file in Java?

The solution with FileWriter is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!

So at best use FileOutputStream:

    Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file, true), "UTF-8"));

Remove the last character in a string in T-SQL?

Try this

DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'
SELECT LEFT(@String, LEN(@String) - 1) AS MyTrimmedColumn

ArrayList - How to modify a member of an object?

Use myList.get(3) to get access to the current object and modify it, assuming instances of Customer have a way to be modified.

How do I copy a 2 Dimensional array in Java?

I solved it writing a simple function to copy multidimensional int arrays using System.arraycopy

public static void arrayCopy(int[][] aSource, int[][] aDestination) {
    for (int i = 0; i < aSource.length; i++) {
        System.arraycopy(aSource[i], 0, aDestination[i], 0, aSource[i].length);
    }
}

or actually I improved it for for my use case:

/**
 * Clones the provided array
 * 
 * @param src
 * @return a new clone of the provided array
 */
public static int[][] cloneArray(int[][] src) {
    int length = src.length;
    int[][] target = new int[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

How to use sbt from behind proxy?

For those still landing on this thread trying to find where/how to configure HTTP proxy in IntelliJ, here's how I managed to get it to work for me. I hope this helps!

(Note: specify your network username and password in the corresponding boxes):-

enter image description here

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Reposting this here for others from the requests issue page:

Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so:

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl

class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)

When you've done that, you can do this:

import requests
s = requests.Session()
s.mount('https://', MyAdapter())

Any request through that session object will then use TLSv1.

Maven 3 warnings about build.plugins.plugin.version

get the latest version information from:

https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin

click on the latest version (or the one you'd like to use) and you'll see the the dependency info (as of 2019-05 it's 3.8.1):

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
</dependency>

you might want to use the version tag and the comment for your plugin tag.

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <source />
        <target />
    </configuration>
</plugin>

if you like you can modify your pom to have the version information in the properties tag as outlined in another answer.

Convert seconds to Hour:Minute:Second

$given = 685;

 /*
 * In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
 * We would need to take this into consideration, and so we will first
 * check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
 * and then after multiplying it by the number of hours in a day (24), we
 * will just use "floor" to get the number of hours as the rest would
 * be the minutes and seconds anyways.
 *
 * We can also have minutes and seconds combined in one variable,
 * e.g. $min_sec = gmdate( "i:s", $given );
 * But for versatility sake, I have taken them separately.
 */

$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

$min = gmdate( "i", $given );

$sec = gmdate( "s", $given );

echo $formatted_string = $hours.':'.$min.':'.$sec;

To convert it into a function:

function getHoursFormat( $given ){

 $hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

 $min = gmdate( "i", $given );

 $sec = gmdate( "s", $given );

 $formatted_string = $hours.':'.$min.':'.$sec;

 return $formatted_string;

}

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Convert list of dictionaries to a pandas DataFrame

The easiest way I have found to do it is like this:

dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)

Generate random integers between 0 and 9

This is more of a mathematical approach but it works 100% of the time:

Let's say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

num = (b-a)*random.random() + a;

Of course, you can generate more numbers.

How to config Tomcat to serve images from an external folder outside webapps?

Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.

Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.

Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.

I think this implementation would give you the most flexibility and control on the overall application.

When should I use a struct rather than a class in C#?

A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data. A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

Classes and Structs (C# Programming Guide)

How can I get the name of an html page in Javascript?

Try this

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.

How do I convert from BLOB to TEXT in MySQL?

Here's an example of a person who wants to convert a blob to char(1000) with UTF-8 encoding:

CAST(a.ar_options AS CHAR(10000) CHARACTER SET utf8)

This is his answer. There is probably much more you can read about CAST right here. I hope it helps some.

Eclipse : Maven search dependencies doesn't work

Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.

Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.

After downloading completely, artifact searching will be ready to use.

Maven Settings

UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.

In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.

A 66M index file will be downloaded.

Maven Repositories -> Rebuild Index

Prompt for user input in PowerShell

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString

To convert the password to plain text:

[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

Overriding !important style

Building on @Premasagar's excellent answer; if you don't want to remove all the other inline styles use this

//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
    //remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    //insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty() because it wont remove !important rules in Chrome.
Can't use element.style[property] = '' because it only accepts camelCase in FireFox.

Is it possible to program iPhone in C++

Having some experience of this, you can indeed use C++ code for your "core" code, but you have to use objective-C for anything iPhone specific.

Don't try to force Objective-C to act like C++. At first it will seem to you this is possible, but the resulting code really won't work well with Cocoa, and you will get very confused as to what is going on. Take the time to learn properly, without any C++ around, how to build GUIs and iPhone applications, then link in your C++ base.

Disable scrolling on `<input type=number>`

Easiest solution is to add onWheel={ event => event.currentTarget.blur() }} on input itself.

Postgres manually alter sequence

this worked for me:

SELECT pg_catalog.setval('public.hibernate_sequence', 3, true);

What is the purpose of class methods?

Honestly? I've never found a use for staticmethod or classmethod. I've yet to see an operation that can't be done using a global function or an instance method.

It would be different if python used private and protected members more like Java does. In Java, I need a static method to be able to access an instance's private members to do stuff. In Python, that's rarely necessary.

Usually, I see people using staticmethods and classmethods when all they really need to do is use python's module-level namespaces better.

How to validate IP address in Python?

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

How to perform Unwind segue programmatically?

Quoting text from Apple's Technical Note on Unwind Segue: To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.

Link to Technical Note

DataTables: Cannot read property style of undefined

POSSIBLE CAUSES

  • Number of th elements in the table header or footer differs from number of columns in the table body or defined using columns option.
  • Attribute colspan is used for th element in the table header.
  • Incorrect column index specified in columnDefs.targets option.

SOLUTIONS

  • Make sure that number of th elements in the table header or footer matches number of columns defined in the columns option.
  • If you use colspan attribute in the table header, make sure you have at least two header rows and one unique th element for each column. See Complex header for more information.
  • If you use columnDefs.targets option, make sure that zero-based column index refers to existing columns.

LINKS

See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.

SSL Error: CERT_UNTRUSTED while using npm command

npm ERR! node -v v0.8.0
npm ERR! npm -v 1.1.32

Update your node.js installation.The following commands should do it (from here):

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Edit: okay, if you really have a good reason to run an ancient version of the software, npm set ca null will fix the issue. It happened, because built-in npm certificate has expired over the years.

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

SQL Server using wildcard within IN

  1. I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z

  2. I had to write a script to pull the current user (declare them) and pull the masks for the declared user.

  3. Create some temporary tables just basic ones to rank the row numbers for this current user

  4. loop through each result (YOUR Or this Or that etc...)

  5. Insert into the test Table.

Here is the script I used:

Drop Table #UserMasks 
Drop Table #TESTUserMasks 

Create Table #TESTUserMasks (
    [User] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

Create Table #UserMasks (
    [RN] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

DECLARE @User INT
SET @User = 74054

Insert Into #UserMasks 
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
       REPLACE(mask,'?','') Mask
from dbo.Access_Masks 
where prontouserid = @User

DECLARE @TopFlag INT
SET @TopFlag = 1

WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
    Insert Into #TestUserMasks 
    select (@User),Code from dbo.MaskArrayLookupTable 
    where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)

    SET @TopFlag = @TopFlag + 1
END
GO

select * from #TESTUserMasks

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

This workaround is dangerous and not recommended:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

It's not a good idea to disable SSL peer verification. Doing so might expose your requests to MITM attackers.

In fact, you just need an up-to-date CA root certificate bundle. Installing an updated one is as easy as:

  1. Downloading up-to-date cacert.pem file from cURL website and

  2. Setting a path to it in your php.ini file, e.g. on Windows:

    curl.cainfo=c:\php\cacert.pem

That's it!

Stay safe and secure.

What's the difference between struct and class in .NET?

From Microsoft's Choosing Between Class and Struct ...

As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

? CONSIDER a struct instead of a class:

  • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (cannot be changed)
  • It will not have to be boxed frequently.

Best way to replace multiple characters in a string?

How about this?

def replace_all(dict, str):
    for key in dict:
        str = str.replace(key, dict[key])
    return str

then

print(replace_all({"&":"\&", "#":"\#"}, "&#"))

output

\&\#

similar to answer

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

Assets file project.assets.json not found. Run a NuGet package restore

For me when i did - dotnet restore still error was occurring.

I went to

1 Tool -> NuGet Package Maneger -> Package Manager settings -> click on "Clear on Nuget Catche(s)"

2 dotnet restore

resolved issues.

intellij idea - Error: java: invalid source release 1.9

In Project Structure in Project SDK: modify SDK to 11 or higher and in Project language level: modify to 11 - Local variable syntax for lambda parameters

Check whether a value exists in JSON object

This example puts your JSON into proper format and does an existence check. I use jquery for convenience.

http://jsfiddle.net/nXFxC/

<!-- HTML -->
<span id="test">Hello</span><br>
<span id="test2">Hello</span>

//Javascript

$(document).ready(function(){
    var JSON = {"animals":[{"name":"cat"}, {"name":"dog"}]};

if(JSON.animals[1].name){      
$("#test").html("It exists");
}
if(!JSON.animals[2]){       
$("#test2").html("It doesn't exist");
}
});

How can I detect window size with jQuery?

Do you want to detect when the window has been resized?

You can use JQuery's resize to attach a handler.

Reading a date using DataReader

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
            ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
        };
    }

OR

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = GetValue<int>(reader["conId"]),
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
            ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
        };
    }

// Base methods
        protected T GetValue<T>(object obj)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return default(T);
    }

    protected T GetValue<T>(object obj, object defaultValue)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return (T)defaultValue;
    }

How to get the list of properties of a class?

Try this:

var model = new MyObject();
foreach (var property in model.GetType().GetProperties())
{
    var descricao = property;
    var type = property.PropertyType.Name;
}

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Import functions from another js file. Javascript

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

models/course.js

export function Course() {
    this.id = '';
    this.name = '';
};

models/student.js

import { Course } from './course.js';

export function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
};

index.html

<div id="myDiv">
</div>
<script type="module">
    import { Student } from './models/student.js';

    window.onload = function () {
        var x = new Student();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

Convert date to UTC using moment.js

As of : moment.js version 2.24.0

let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :

var utcStart = new moment("09:00", "HH:mm").utc();

or in case you specify a date

var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();

As you can see the result output will be returned in UTC :

//You can call the format() that will return your UTC date in a string 
 utcStart.format(); 
//Result : 2019-06-24T13:00:00 

But if you do this as below, it will not convert to UTC :

var myTime = new moment.utc("09:00", "HH:mm"); 

You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00

IIS sc-win32-status codes

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

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

Populate nested array in mongoose

I found this question through another question which was KeystoneJS specific but was marked as duplicate. If anyone here might be looking for a Keystone answer, this is how I did my deep populate query in Keystone.

Mongoose two level population using KeystoneJs [duplicate]

exports.getStoreWithId = function (req, res) {
    Store.model
        .find()
        .populate({
            path: 'productTags productCategories',
            populate: {
                path: 'tags',
            },
        })
        .where('updateId', req.params.id)
        .exec(function (err, item) {
            if (err) return res.apiError('database error', err);
            // possibly more than one
            res.apiResponse({
                store: item,
            });
        });
};

JSON and escaping characters

This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

grep output to show only matching file

Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *

ArrayList insertion and retrieval order

If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

How to access a value defined in the application.properties file in Spring Boot

Tried Class PropertiesLoaderUtils ?

This approach uses no annotation of Spring boot. A traditional Class way.

example:

Resource resource = new ClassPathResource("/application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    String url_server=props.getProperty("server_url");

Use getProperty() method to pass the key and access the value in the properties file.

Could not resolve all dependencies for configuration ':classpath'

**A problem occurred evaluating project ':app'.

Could not resolve all files for configuration 'classpath'.**

Solution: Platform->cordova-support-google-services

In this file Replace classpath 'com.android.tools.build:gradle:+' to this classpath 'com.android.tools.build:gradle:3.+'

Installing Bower on Ubuntu

sudo ln -s /usr/bin/nodejs /usr/bin/node

or install legacy nodejs:

sudo apt-get install nodejs-legacy

As seen in this GitHub issue.

Android: remove notification from notification bar

this will help:

NotificationManager mNotificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();

this should remove all notifications made by the app

and if you create a notification by calling

startForeground();

inside a Service.you may have to call

stopForeground(false);

first,then cancel the notification.

How to make --no-ri --no-rdoc the default for gem install?

On Windows7 the .gemrc file is not present, you can let Ruby create one like this (it's not easy to do this in explorer).

gem sources --add http://rubygems.org

You will have to confirm (it's unsafe). Now the file is created in your userprofile folder (c:\users\)

You can edit the textfile to remove the source you added or you can remove it with

gem sources --remove http://rubygems.org

Getting a list of associative array keys

for (var key in dictionary) {
  // Do something with key
}

It's the for..in statement.

Difference between drop table and truncate table?

Truncating the table empties the table. Dropping the table deletes it entirely. Either one will be fast, but dropping it will likely be faster (depending on your database engine).

If you don't need it anymore, drop it so it's not cluttering up your schema.

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

How to scale a BufferedImage

If you do not mind using an external library, Thumbnailator can perform scaling of BufferedImages.

Thumbnailator will take care of handling the Java 2D processing (such as using Graphics2D and setting appropriate rendering hints) so that a simple fluent API call can be used to resize images:

BufferedImage image = Thumbnails.of(originalImage).scale(2.0).asBufferedImage();

Although Thumbnailator, as its name implies, is geared toward shrinking images, it will do a decent job enlarging images as well, using bilinear interpolation in its default resizer implementation.


Disclaimer: I am the maintainer of the Thumbnailator library.

How do I get a computer's name and IP address using VB.NET?

Private Function GetIPv4Address() As String
    GetIPv4Address = String.Empty
    Dim strHostName As String = System.Net.Dns.GetHostName()
    Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)

    For Each ipheal As System.Net.IPAddress In iphe.AddressList
        If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
            GetIPv4Address = ipheal.ToString()
        End If
    Next

End Function

Catching exceptions from Guzzle

I want to update the answer for exception handling in Psr-7 Guzzle, Guzzle7 and HTTPClient(expressive, minimal API around the Guzzle HTTP client provided by laravel).

Guzzle7 (same works for Guzzle 6 as well)

Using RequestException, RequestException catches any exception that can be thrown while transferring requests.

try{
  $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
  
  $guzzleResponse = $client->get('/foobar');
  // or can use
  // $guzzleResponse = $client->request('GET', '/foobar')
    if ($guzzleResponse->getStatusCode() == 200) {
         $response = json_decode($guzzleResponse->getBody(),true);
         //perform your action with $response 
    } 
}
catch(\GuzzleHttp\Exception\RequestException $e){
   // you can catch here 400 response errors and 500 response errors
   // You can either use logs here use Illuminate\Support\Facades\Log;
   $error['error'] = $e->getMessage();
   $error['request'] = $e->getRequest();
   if($e->hasResponse()){
       if ($e->getResponse()->getStatusCode() == '400'){
           $error['response'] = $e->getResponse(); 
       }
   }
   Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
   //other errors 
}

Psr7 Guzzle

use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;

try {
    $client->request('GET', '/foo');
} catch (RequestException $e) {
    $error['error'] = $e->getMessage();
    $error['request'] = Psr7\Message::toString($e->getRequest());
    if ($e->hasResponse()) {
        $error['response'] = Psr7\Message::toString($e->getResponse());
    }
    Log::error('Error occurred in get request.', ['error' => $error]);
}

For HTTPClient

use Illuminate\Support\Facades\Http;
try{
    $response = Http::get('http://api.foo.com');
    if($response->successful()){
        $reply = $response->json();
    }
    if($response->failed()){
        if($response->clientError()){
            //catch all 400 exceptions
            Log::debug('client Error occurred in get request.');
            $response->throw();
        }
        if($response->serverError()){
            //catch all 500 exceptions
            Log::debug('server Error occurred in get request.');
            $response->throw();
        }
        
    }
 }catch(Exception $e){
     //catch the exception here
 }

How to find where javaw.exe is installed?

It worked to me:

    String javaHome = System.getProperty("java.home");
    File f = new File(javaHome);
    f = new File(f, "bin");
    f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
    System.out.println(f + "    exists: " + f.exists());

How to download a file from a website in C#

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Why aren't Xcode breakpoints functioning?

There appears to be 3 states for the breakpoints in Xcode. If you click on them they'll go through the different settings. Dark blue is enabled, grayed out is disabled and I've seen a pale blue sometimes that required me to click on the breakpoint again to get it to go to the dark blue color.

Other than this make sure that you're launching it with the debug command not the run command. You can do that by either hitting option + command + return, or the Go (debug) option from the run menu.

Eliminate extra separators below UITableView

You can just add an empty footer at the end then it will hide the empty cells but it will also look quite ugly:

tableView.tableFooterView = UIView()

enter image description here

There is a better approach: add a 1 point line at the end of the table view as the footer and the empty cells will also not been shown anymore.

let footerView = UIView()
footerView.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)
footerView.backgroundColor = tableView.separatorColor
tableView.tableFooterView = footerView

enter image description here

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

How to get controls in WPF to fill available space?

Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.

The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.

The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.

remove item from array using its name / value

it worked for me..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });

Regular Expression to match string starting with a specific word

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

Bootstrap 3 dropdown select

The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.

You could look to use something like this:

http://silviomoreto.github.io/bootstrap-select/

Which will make your selectboxes more consistent cross browser.

Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

How to check if a view controller is presented modally or pushed on a navigation stack?

self.navigationController != nil would mean it's in a navigation stack.

In order to handle the case that the current view controller is pushed while the navigation controller is presented modally, I have added some lines of code to check if the current view controller is the root controller in the navigation stack .

extension UIViewController {
    var isModal: Bool {
        if let index = navigationController?.viewControllers.firstIndex(of: self), index > 0 {
            return false
        } else if presentingViewController != nil {
            return true
        } else if let navigationController = navigationController, navigationController.presentingViewController?.presentedViewController == navigationController {
            return true
        } else if let tabBarController = tabBarController, tabBarController.presentingViewController is UITabBarController {
            return true
        } else {
            return false
        }
    }
}

React-Redux: Actions must be plain objects. Use custom middleware for async actions

For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.

actions.js:

export function addNewComponent() {
  return {
    type: ADD_NEW_COMPONENT,
  };
}

myComponent.js:

import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';

  useEffect(() => {
    dispatch(refreshAllComponents); // <= Here was what I've missed.
  }, []);

I've forgotten to dispatch the action function with (). So doing this solved my issue.

  useEffect(() => {
    dispatch(refreshAllComponents());
  }, []);

Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

Visual Studio: ContextSwitchDeadlock

It sounds like you are doing this on the main UI thread in the app. The UI thread is responsible for pumping windows messages as the arrive, and yet because yours is blocked in database calls it is unable to do so. This can cause problems with system wide messages.

You should look at spawning a background thread for the long running operation and putting up some kind of "I'm busy" dialog for the user while it happens.

Opening the Settings app from another app

Add this to your class,

 public class func showSettingsAlert(title:String,message:String,onVC viewController:UIViewController,onCancel:(()->())?){
            YourClass.show2ButtonsAlert(onVC: viewController, title: title, message: message, button1Title: "Settings", button2Title: "Cancel", onButton1Click: {
                if let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString){
                    UIApplication.sharedApplication().openURL(settingsURL)
                }
                }, onButton2Click: {
                    onCancel?()
            })
        }

 public class func show2ButtonsAlert(onVC viewController:UIViewController,title:String,message:String,button1Title:String,button2Title:String,onButton1Click:(()->())?,onButton2Click:(()->())?){
            dispatch_async(dispatch_get_main_queue()) {
                let alert : UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

                alert.addAction(UIAlertAction(title: button1Title, style:.Default, handler: { (action:UIAlertAction) in
                    onButton1Click?()
                }))

                alert.addAction(UIAlertAction(title: button2Title, style:.Default, handler: { (action:UIAlertAction) in
                    onButton2Click?()
                }))

                viewController.presentViewController(alert, animated: true, completion: nil)
            }
        }

Call like this,

YourClass.showSettingsAlert("App would like to access camera", message: "App would like to access camera desc", onVC: fromViewController, onCancel: {
  print("canceled")
})

Regex number between 1 and 100

There are many options how to write a regex pattern for that

  • ^(?:(?!0)\d{1,2}|100)$
  • ^(?:[1-9]\d?|100)$
  • ^(?!0)(?=100$|..$|.$)\d+$

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

I was struggling with this recently, and found the right way to create a default task that runs sass then sass:watch was:

gulp.task('default', gulp.series('sass', 'sass:watch'));

How do you import an Eclipse project into Android Studio now?

In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.

/workspace/android-support-v7-appcompat

being a common one.

In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.

To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.

<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>

That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:

dependencies {
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Reading JSON from a file?

To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html You may want to do a careful use of the orient parameter.

T-SQL: Looping through an array of known values

CREATE TABLE #ListOfIDs (IDValue INT)

DECLARE @IDs VARCHAR(50), @ID VARCHAR(5)
SET @IDs = @OriginalListOfIDs + ','

WHILE LEN(@IDs) > 1
BEGIN
SET @ID = SUBSTRING(@IDs, 0, CHARINDEX(',', @IDs));
INSERT INTO #ListOfIDs (IDValue) VALUES(@ID);
SET @IDs = REPLACE(',' + @IDs, ',' + @ID + ',', '')
END

SELECT * 
FROM #ListOfIDs

Script not served by static file handler on IIS7.5

alt text

should check out this option i suppose

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

How to calculate the running time of my program?

Beside the well-known (and already mentioned) System.currentTimeMillis() and System.nanoTime() there is also a neat library called perf4j which might be useful too, depending on your purpose of course.

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

Defining constant string in Java?

Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

How to send and retrieve parameters using $state.go toParams and $stateParams?

Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.

I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.

Just add your parameters with a default value on your state definition. Your state can still have an Url value.

$stateProvider.state('state1', {
    url : '/url',
    templateUrl : "new.html",
    controller : 'TestController',
    params: {new_param: null}
});

and add the param to $state.go()

$state.go('state1',{new_param: "Going places!"});

How do I display a wordpress page content?

@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.

<?php
    wp_reset_query(); // necessary to reset query
    while ( have_posts() ) : the_post();
        the_content();
    endwhile; // End of the loop.
?>

EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.

How to uncheck a radio button?

You can also simulate the radiobutton behavior using only checkboxes:

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

Then, you can use this simple code to work for you:

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

It works fine and you have more control over the behavior of each button.

You can try it by yourself at: http://jsfiddle.net/almircampos/n1zvrs0c/

This fork also let's you unselect all as requested in a comment: http://jsfiddle.net/5ry8n4f4/

String.strip() in Python

If you can comment out code and your program still works, then yes, that code was optional.

.strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.

For example, by using .strip(), the following two lines in a file would lead to the same end result:

 foo\tbar \n
foo\tbar\n

I'd say leave it in.

How to convert JSON object to JavaScript array?

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

How do I URl encode something in Node.js?

Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).

This is correct if you plan on using the string later as a query string:

> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'

If you don't want ASCII characters like /, : and ? to be escaped, use encodeURI instead:

> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

However, for other use-cases, you might need uri-js instead:

> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'

java.lang.OutOfMemoryError: Java heap space

In netbeans, Go to 'Run' toolbar, --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up windo --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'. It could solve heap size problem.

Set style for TextView programmatically

The accepted answer was great solution for me. The only thing to add is about inflate() method.

In accepted answer all android:layout_* parameters will not be applied.

The reason is no way to adjust it, cause null was passed as ViewGroup parent.

You can use it like this:

View view = inflater.inflate(R.layout.view, parent, false);

and the parent is the ViewGroup, from where you like to adjust android:layout_*.

In this case, all relative properties will be set.

Hope it'll be useful for someone.

JavaScript code to stop form submission

The following works as of now (tested in Chrome and Firefox):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

Select unique values with 'select' function in 'dplyr' library

Just to add to the other answers, if you would prefer to return a vector rather than a dataframe, you have the following options:

dplyr < 0.7.0

Enclose the dplyr functions in a parentheses and combine it with $ syntax:

(mtcars %>% distinct(cyl))$cyl

dplyr >= 0.7.0

Use the pull verb:

mtcars %>% distinct(cyl) %>% pull()

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem, the annotation @Autowired in the test code did not work under using the Maven command line while it worked fine in Eclipse. I just update my JUnit version from 4.4 to 4.9 and the problem was solved.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
</dependency>

EnterKey to press button in VBA Userform

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!

Check line for unprintable characters while reading text file

While it's not hard to do this manually using BufferedReader and InputStreamReader, I'd use Guava:

List<String> lines = Files.readLines(file, Charsets.UTF_8);

You can then do whatever you like with those lines.

EDIT: Note that this will read the whole file into memory in one go. In most cases that's actually fine - and it's certainly simpler than reading it line by line, processing each line as you read it. If it's an enormous file, you may need to do it that way as per T.J. Crowder's answer.

How do I test a website using XAMPP?

Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/

Good luck!

How to implement LIMIT with SQL Server?

In SQL there's no LIMIT keyword exists. If you only need a limited number of rows you should use a TOP keyword which is similar to a LIMIT.

How to format strings using printf() to get equal length in the output

printf allows formatting with width specifiers. For example,

printf( "%-30s %s\n", "Starting initialization...", "Ok." );

You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

How do I create dynamic properties in C#?

If it is for binding, then you can reference indexers from XAML

Text="{Binding [FullName]}"

Here it is referencing the class indexer with the key "FullName"

How to write a confusion matrix in Python?

You should map from classes to a row in your confusion matrix.

Here the mapping is trivial:

def row_of_class(classe):
    return {1: 0, 2: 1}[classe]

In your loop, compute expected_row, correct_row, and increment conf_arr[expected_row][correct_row]. You'll even have less code than what you started with.

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

Check if value exists in column in VBA

Simplest is to use Match

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
    ' String is in range

How to stop Python closing immediately when executed in Microsoft Windows

The only thing that worked for me -i command line argument.

Just put all your python code inside a .py file and then run the following command;

python -i script.py

It means that if you set -i variable and run your module then python doesn't exit on SystemExit. Read more at the this link.

Laravel 5.1 - Checking a Database Connection

Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

// Test database connection
try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

how to call url of any other website in php

use curl php library: http://php.net/manual/en/book.curl.php

direct example: CURL_EXEC:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

How to add an extra column to a NumPy array

Add an extra column to a numpy array:

Numpy's np.append method takes three parameters, the first two are 2D numpy arrays and the 3rd is an axis parameter instructing along which axis to append:

import numpy as np  
x = np.array([[1,2,3], [4,5,6]]) 
print("Original x:") 
print(x) 

y = np.array([[1], [1]]) 
print("Original y:") 
print(y) 

print("x appended to y on axis of 1:") 
print(np.append(x, y, axis=1)) 

Prints:

Original x:
[[1 2 3]
 [4 5 6]]
Original y:
[[1]
 [1]]
x appended to y on axis of 1:
[[1 2 3 1]
 [4 5 6 1]]

Java - Check Not Null/Empty else assign default value

Use org.apache.commons.lang3.StringUtils

String emptyString = new String();    
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);

String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);

Both of the above options will print:

default

default

How to run a cron job inside a docker container?

The adopted solution may be dangerous in a production environment.

In docker you should only execute one process per container because if you don't, the process that forked and went background is not monitored and may stop without you knowing it.

When you use CMD cron && tail -f /var/log/cron.log the cron process basically fork in order to execute cron in background, the main process exits and let you execute tailf in foreground. The background cron process could stop or fail you won't notice, your container will still run silently and your orchestration tool will not restart it.

You can avoid such a thing by redirecting directly the cron's commands output into your docker stdout and stderr which are located respectively in /proc/1/fd/1 and /proc/1/fd/2.

Using basic shell redirects you may want to do something like this :

* * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2

And your CMD will be : CMD ["cron", "-f"]

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

How to trigger Jenkins builds remotely and to pass parameters

When we have to send multiple trigger parameters to jenkins job, the following commands works.

curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162&param2=store"

What is the preferred syntax for defining enums in JavaScript?

This is an old one I know, but the way it has since been implemented via the TypeScript interface is:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["Foo"] = 0] = "Foo";
    MyEnum[MyEnum["FooBar"] = 2] = "FooBar";
    MyEnum[MyEnum["Bar"] = 1] = "Bar";
})(MyEnum|| (MyEnum= {}));

This enables you to look up on both MyEnum.Bar which returns 1, and MyEnum[1] which returns "Bar" regardless of the order of declaration.

How to concatenate two numbers in javascript?

// enter code here
var a = 9821099923;
var b = 91;
alert ("" + b + a); 
// after concating , result is 919821099923 but its is now converted into string  

console.log(Number.isInteger("" + b + a))  // false

// you have to do something like this

var c= parseInt("" + b + a)
console.log(c); // 919821099923
console.log(Number.isInteger(c)) // true

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Running these commands solved my problem (credit to this answer):

import django
django.setup()

However I'm not sure why I need this. Comments would be appreciated.

Difference between staticmethod and classmethod

staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object).

classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access self.<attribute(s)> and accesses self.__class__.<attribute(s)> only.

Think we have a class with b=2, we will create an object and re-set this to b=4 in it. Staticmethod cannot access nothing from previous. Classmethod can access .b==2 only, via cls.b. Normal method can access both: .b==4 via self.b and .b==2 via self.__class__.b.

We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes self.attribute(s). There are languages where the OOP is implemented that way and I think it is not bad idea. :)

jQuery access input hidden value

Watch out if you want to retrieve a boolean value from a hidden field!

For example:

<input type="hidden" id="SomeBoolean" value="False"/>

(An input like this will be rendered by ASP MVC if you use @Html.HiddenFor(m => m.SomeBoolean).)

Then the following will return a string 'False', not a JS boolean!

var notABool = $('#SomeBoolean').val();

If you want to use the boolean for some logic, use the following instead:

var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }

How to concatenate a std::string and an int?

As a one liner: name += std::to_string(age);

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Row count on the Filtered data

I would think that now you have the range for each of the row, you can easily manipulate that range with the offset(row, column) action? What is the point of counting the records filtered (unless you need that count in a variable)? So instead of (or as well as in the same block) write your code action to move each row to an empty hidden sheet and once all done, you can do any work you like from the transferred range data?

Artisan, creating tables in database

Migration files must match the pattern *_*.php, or else they won't be found. Since users.php does not match this pattern (it has no underscore), this file will not be found by the migrator.

Ideally, you should be creating your migration files using artisan:

php artisan make:migration create_users_table

This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.

You can also use the --create or --table switches to add a little bit more boilerplate to help get you started:

php artisan make:migration create_users_table --create=users

The documentation on migrations can be found here.

How do I convert between big-endian and little-endian values in C++?

Portable technique for implementing optimizer-friendly unaligned non-inplace endian accessors. They work on every compiler, every boundary alignment and every byte ordering. These unaligned routines are supplemented, or mooted, depending on native endian and alignment. Partial listing but you get the idea. BO* are constant values based on native byte ordering.

uint32_t sw_get_uint32_1234(pu32)
uint32_1234 *pu32;
{
  union {
    uint32_1234 u32_1234;
    uint32_t u32;
  } bou32;
  bou32.u32_1234[0] = (*pu32)[BO32_0];
  bou32.u32_1234[1] = (*pu32)[BO32_1];
  bou32.u32_1234[2] = (*pu32)[BO32_2];
  bou32.u32_1234[3] = (*pu32)[BO32_3];
  return(bou32.u32);
}

void sw_set_uint32_1234(pu32, u32)
uint32_1234 *pu32;
uint32_t u32;
{
  union {
    uint32_1234 u32_1234;
    uint32_t u32;
  } bou32;
  bou32.u32 = u32;
  (*pu32)[BO32_0] = bou32.u32_1234[0];
  (*pu32)[BO32_1] = bou32.u32_1234[1];
  (*pu32)[BO32_2] = bou32.u32_1234[2];
  (*pu32)[BO32_3] = bou32.u32_1234[3];
}

#if HAS_SW_INT64
int64 sw_get_int64_12345678(pi64)
int64_12345678 *pi64;
{
  union {
    int64_12345678 i64_12345678;
    int64 i64;
  } boi64;
  boi64.i64_12345678[0] = (*pi64)[BO64_0];
  boi64.i64_12345678[1] = (*pi64)[BO64_1];
  boi64.i64_12345678[2] = (*pi64)[BO64_2];
  boi64.i64_12345678[3] = (*pi64)[BO64_3];
  boi64.i64_12345678[4] = (*pi64)[BO64_4];
  boi64.i64_12345678[5] = (*pi64)[BO64_5];
  boi64.i64_12345678[6] = (*pi64)[BO64_6];
  boi64.i64_12345678[7] = (*pi64)[BO64_7];
  return(boi64.i64);
}
#endif

int32_t sw_get_int32_3412(pi32)
int32_3412 *pi32;
{
  union {
    int32_3412 i32_3412;
    int32_t i32;
  } boi32;
  boi32.i32_3412[2] = (*pi32)[BO32_0];
  boi32.i32_3412[3] = (*pi32)[BO32_1];
  boi32.i32_3412[0] = (*pi32)[BO32_2];
  boi32.i32_3412[1] = (*pi32)[BO32_3];
  return(boi32.i32);
}

void sw_set_int32_3412(pi32, i32)
int32_3412 *pi32;
int32_t i32;
{
  union {
    int32_3412 i32_3412;
    int32_t i32;
  } boi32;
  boi32.i32 = i32;
  (*pi32)[BO32_0] = boi32.i32_3412[2];
  (*pi32)[BO32_1] = boi32.i32_3412[3];
  (*pi32)[BO32_2] = boi32.i32_3412[0];
  (*pi32)[BO32_3] = boi32.i32_3412[1];
}

uint32_t sw_get_uint32_3412(pu32)
uint32_3412 *pu32;
{
  union {
    uint32_3412 u32_3412;
    uint32_t u32;
  } bou32;
  bou32.u32_3412[2] = (*pu32)[BO32_0];
  bou32.u32_3412[3] = (*pu32)[BO32_1];
  bou32.u32_3412[0] = (*pu32)[BO32_2];
  bou32.u32_3412[1] = (*pu32)[BO32_3];
  return(bou32.u32);
}

void sw_set_uint32_3412(pu32, u32)
uint32_3412 *pu32;
uint32_t u32;
{
  union {
    uint32_3412 u32_3412;
    uint32_t u32;
  } bou32;
  bou32.u32 = u32;
  (*pu32)[BO32_0] = bou32.u32_3412[2];
  (*pu32)[BO32_1] = bou32.u32_3412[3];
  (*pu32)[BO32_2] = bou32.u32_3412[0];
  (*pu32)[BO32_3] = bou32.u32_3412[1];
}

float sw_get_float_1234(pf)
float_1234 *pf;
{
  union {
    float_1234 f_1234;
    float f;
  } bof;
  bof.f_1234[0] = (*pf)[BO32_0];
  bof.f_1234[1] = (*pf)[BO32_1];
  bof.f_1234[2] = (*pf)[BO32_2];
  bof.f_1234[3] = (*pf)[BO32_3];
  return(bof.f);
}

void sw_set_float_1234(pf, f)
float_1234 *pf;
float f;
{
  union {
    float_1234 f_1234;
    float f;
  } bof;
  bof.f = (float)f;
  (*pf)[BO32_0] = bof.f_1234[0];
  (*pf)[BO32_1] = bof.f_1234[1];
  (*pf)[BO32_2] = bof.f_1234[2];
  (*pf)[BO32_3] = bof.f_1234[3];
}

double sw_get_double_12345678(pd)
double_12345678 *pd;
{
  union {
    double_12345678 d_12345678;
    double d;
  } bod;
  bod.d_12345678[0] = (*pd)[BO64_0];
  bod.d_12345678[1] = (*pd)[BO64_1];
  bod.d_12345678[2] = (*pd)[BO64_2];
  bod.d_12345678[3] = (*pd)[BO64_3];
  bod.d_12345678[4] = (*pd)[BO64_4];
  bod.d_12345678[5] = (*pd)[BO64_5];
  bod.d_12345678[6] = (*pd)[BO64_6];
  bod.d_12345678[7] = (*pd)[BO64_7];
  return(bod.d);
}

void sw_set_double_12345678(pd, d)
double_12345678 *pd;
double d;
{
  union {
    double_12345678 d_12345678;
    double d;
  } bod;
  bod.d = d;
  (*pd)[BO64_0] = bod.d_12345678[0];
  (*pd)[BO64_1] = bod.d_12345678[1];
  (*pd)[BO64_2] = bod.d_12345678[2];
  (*pd)[BO64_3] = bod.d_12345678[3];
  (*pd)[BO64_4] = bod.d_12345678[4];
  (*pd)[BO64_5] = bod.d_12345678[5];
  (*pd)[BO64_6] = bod.d_12345678[6];
  (*pd)[BO64_7] = bod.d_12345678[7];
}

These typedefs have the benefit of raising compiler errors if not used with accessors, thus mitigating forgotten accessor bugs.

typedef char int8_1[1], uint8_1[1];

typedef char int16_12[2], uint16_12[2]; /* little endian */
typedef char int16_21[2], uint16_21[2]; /* big endian */

typedef char int24_321[3], uint24_321[3]; /* Alpha Micro, PDP-11 */

typedef char int32_1234[4], uint32_1234[4]; /* little endian */
typedef char int32_3412[4], uint32_3412[4]; /* Alpha Micro, PDP-11 */
typedef char int32_4321[4], uint32_4321[4]; /* big endian */

typedef char int64_12345678[8], uint64_12345678[8]; /* little endian */
typedef char int64_34128756[8], uint64_34128756[8]; /* Alpha Micro, PDP-11 */
typedef char int64_87654321[8], uint64_87654321[8]; /* big endian */

typedef char float_1234[4]; /* little endian */
typedef char float_3412[4]; /* Alpha Micro, PDP-11 */
typedef char float_4321[4]; /* big endian */

typedef char double_12345678[8]; /* little endian */
typedef char double_78563412[8]; /* Alpha Micro? */
typedef char double_87654321[8]; /* big endian */

Button inside of anchor link works in Firefox but not in Internet Explorer?

The code below will work just fine in all browsers:

<button onClick="location.href = 'http://www.google.com'">Go to Google</button>

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

Any way to write a Windows .bat file to kill processes?

Use Powershell! Built in cmdlets for managing processes. Examples here (hard way), here(built in) and here (more).

How to normalize a NumPy array to within a certain range?

You are trying to min-max scale the values of audio between -1 and +1 and image between 0 and 255.

Using sklearn.preprocessing.minmax_scale, should easily solve your problem.

e.g.:

audio_scaled = minmax_scale(audio, feature_range=(-1,1))

and

shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)

note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.

Docker Networking - nginx: [emerg] host not found in upstream

I believe Nginx dont take in account Docker resolver (127.0.0.11), so please, can you try adding:

resolver 127.0.0.11

in your nginx configuration file?

Tests not running in Test Explorer

It is worth mentioning that sometimes NUnit Test Adapter files get corrupted in user folder C:\Users[User]\AppData\Local\Temp\VisualStudioTestExplorerExtensions\NUnit3TestAdapter.3.8.0/build/net35/NUnit3.TestAdapter.dll on Windows 10 and that causes Test Explorer to stop working as it should.

How can I execute Shell script in Jenkinsfile?

If you see your error message it says

Building in workspace /var/lib/jenkins/workspace/AutoScript

and as per your comments you have put urltest.sh in

/var/lib/jenkins

Hence Jenkins is not able to find the file. In your build step do this thing, it will work

cd             # which will point to /var/lib/jenkins
./urltest.sh   # it will run your script

If it still fails try to chown the file as jenkin user may not have file permission, but I think if you do above step you will be able to run.

How to change port number for apache in WAMP

Just go to httpd.conf file, for ex. under WAMP environment its situated at:

C:\wamp\bin\apache\apache2.2.22\conf\httpd.conf

go to line no. 46 and edit Listen 80 to your requirement for ex.

Listen 8383

newer versions of WAMP uses these 2 lines:

Listen 0.0.0.0:8383  
Listen [::0]:8383

Next go to line no. 171 and edit ServerName localhost:80 to your requirement for ex.

ServerName localhost:8383

Restart Apache and its done !!

Now, you can access with your URL:

http://localhost:8383 or http://192.168.1.1:8383

Hope it helps to people looking for solution here.

How to find MySQL process list and to kill those processes?

select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;

Then copy and paste the result back into the terminal. Something like:

KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;

How to capture a JFrame's close button click event?

This may work:

jdialog.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        System.out.println("jdialog window closed event received");
    }

    public void windowClosing(WindowEvent e) {
        System.out.println("jdialog window closing event received");
    }
});

Source: https://alvinalexander.com/java/jdialog-close-closing-event

Remove an item from an IEnumerable<T> collection

You can't. IEnumerable<T> can only be iterated.

In your second example, you can remove from original collection by iterating over a copy of it

foreach(var u in users.ToArray()) // ToArray creates a copy
{
   if(u.userId != 1233)
   {
        users.Remove(u);
   }
}

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

Clear text input on click with AngularJS

Easiest way to clear/reset the text field on click is to clear/reset the scope

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>

In Controller

$scope.clearfunction=function(event){
   event.searchAll=null;
}

Gaussian fit for Python

Actually, you do not need to do a first guess. Simply doing

import matplotlib.pyplot as plt  
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)

P.S.: use numpy.exp() better, says a warning of scipy

Dump all documents of Elasticsearch

To export all documents from ElasticSearch into JSON, you can use the esbackupexporter tool. It works with index snapshots. It takes the container with snapshots (S3, Azure blob or file directory) as the input and outputs one or several zipped JSON files per index per day. It is quite handy when exporting your historical snapshots. To export your hot index data, you may need to make the snapshot first (see the answers above).

How can I get a Dialog style activity window to fill the screen?

This answer is a workaround for those who use "Theme.AppCompat.Dialog" or any other "Theme.AppCompat.Dialog" descendants like "Theme.AppCompat.Light.Dialog", "Theme.AppCompat.DayNight.Dialog", etc. I myself has to use AppCompat dialog because i use AppCompatActivity as extends for all my activities. There will be a problem that make the dialog has padding on every sides(top, right, bottom and left) if we use the accepted answer.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

On your Activity's style, add these code

<style name="DialogActivityTheme" parent="Theme.AppCompat.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@null</item>
</style>

As you may notice, the problem that generate padding to our dialog is "android:windowBackground", so here i make the window background to null.

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"

Android: Force EditText to remove focus?

editText.setFocusableInTouchMode(true)

The EditText will be able to get the focus when the user touch it. When the main layout (activity, dialog, etc.) becomes visible the EditText doesn't automatically get the focus even though it is the first view in the layout.

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Creating a dynamic choice field

you can filter the waypoints by passing the user to the form init

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

from your view while initiating the form pass the user

form = waypointForm(user)

in case of model form

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(
            queryset=Waypoint.objects.filter(user=user)
        )

    class Meta:
        model = Waypoint

How to right-align form input boxes?

I answered this question in a blog post: https://wscherphof.wordpress.com/2015/06/17/right-align-form-elements-with-css/ It refers to this fiddle: https://jsfiddle.net/wscherphof/9sfcw4ht/9/

Spoiler: float: right; is the right direction, but it takes just a little more attention to get neat results.

how to convert binary string to decimal?

Another implementation just for functional JS practicing could be

_x000D_
_x000D_
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)_x000D_
console.log(bin2int("101010"));
_x000D_
_x000D_
_x000D_ where +c coerces String type c to a Number type value for proper addition.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity is the base class of all other activities, I don't think it will be deprecated. The relationship among them is:

Activity <- FragmentActivity <- AppCompatActivity <- ActionBarActivity

'<-' means inheritance here. The reference said ActionBarActivity is deprecated, use AppCompatActivity instead.

So basically, using AppCompatActivity is always the right choice. The differences between them are:

  • Activity is the basic one.
  • Based on Activity, FragmentActivity provides the ability to use Fragment.
  • Based on FragmentActivity, AppCompatActivity provides features to ActionBar.

How to remove any URL within a string in Python

I wasn't able to find any that handled my particular situation, which was removing urls in the middle of tweets that also have whitespaces in the middle of urls so I made my own:

(https?:\/\/)(\s)*(www\.)?(\s)*((\w|\s)+\.)*([\w\-\s]+\/)*([\w\-]+)((\?)?[\w\s]*=\s*[\w\%&]*)*

here's an explanation:
(https?:\/\/) matches http:// or https://
(\s)* optional whitespaces
(www\.)? optionally matches www.
(\s)* optionally matches whitespaces
((\w|\s)+\.)* matches 0 or more of one or more word characters followed by a period
([\w\-\s]+\/)* matches 0 or more of one or more words(or a dash or a space) followed by '\'
([\w\-]+) any remaining path at the end of the url followed by an optional ending
((\?)?[\w\s]*=\s*[\w\%&]*)* matches ending query params (even with white spaces,etc)

test this out here:https://regex101.com/r/NmVGOo/8

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

Check permissions to read+write for project folder (Right Click for project folder in Finder > Get Info)

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

#
# creates new column 'E' with values -99
# 
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

#
# creates new column 'F' with values -99
# 
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

How do I calculate tables size in Oracle

First, gather optimiser stats on the table (if you haven't already):

begin
   dbms_stats.gather_table_stats('MYSCHEMA','MYTABLE');
end;
/

WARNING: As Justin says in his answer, gathering optimiser stats affects query optimisation and should not be done without due care and consideration!

Then find the number of blocks occupied by the table from the generated stats:

select blocks, empty_blocks, num_freelist_blocks
from   all_tables
where  owner = 'MYSCHEMA'
and    table_name = 'MYTABLE';
  • The total number of blocks allocated to the table is blocks + empty_blocks + num_freelist_blocks.

  • blocks is the number of blocks that actually contain data.

Multiply the number of blocks by the block size in use (usually 8KB) to get the space consumed - e.g. 17 blocks x 8KB = 136KB.

To do this for all tables in a schema at once:

begin
    dbms_stats.gather_schema_stats ('MYSCHEMA');
end;
/

select table_name, blocks, empty_blocks, num_freelist_blocks
from   user_tables;

Note: Changes made to the above after reading this AskTom thread

The meaning of NoInitialContextException error

The javax.naming package comprises the JNDI API. Since it's just an API, rather than an implementation, you need to tell it which implementation of JNDI to use. The implementations are typically specific to the server you're trying to talk to.

To specify an implementation, you pass in a Properties object when you construct the InitialContext. These properties specify the implementation to use, as well as the location of the server. The default InitialContext constructor is only useful when there are system properties present, but the properties are the same as if you passed them in manually.

As to which properties you need to set, that depends on your server. You need to hunt those settings down and plug them in.

Command copy exited with code 4 when building - Visual Studio restart solves it

As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

The point of "don't test private methods" really is Test the class like someone who uses it.

If you have a public API with 5 methods, any consumer of your class can use these, and therefore you should test them. A consumer should not access the private methods/properties of your class, meaning you can change private members when the public exposed functionality stays the same.


If you rely on internal extensible functionality, use protected instead of private.
Note that protected is still a public API (!), just used differently.

class OverlyComplicatedCalculator {
    public add(...numbers: number[]): number {
        return this.calculate((a, b) => a + b, numbers);
    }
    // can't be used or tested via ".calculate()", but it is still part of your public API!
    protected calculate(operation, operands) {
        let result = operands[0];
        for (let i = 1; i < operands.length; operands++) {
            result = operation(result, operands[i]);
        }
        return result;
    }
}

Unit test protected properties in the same way a consumer would use them, via subclassing:

it('should be extensible via calculate()', () => {
    class TestCalculator extends OverlyComplicatedCalculator {
        public testWithArrays(array: any[]): any[] {
            const concat = (a, b) => [].concat(a, b);
            // tests the protected method
            return this.calculate(concat, array);
        }
    }
    let testCalc = new TestCalculator();
    let result = testCalc.testWithArrays([1, 'two', 3]);
    expect(result).toEqual([1, 'two', 3]);
});

Actionbar notification count icon (badge) like Google has

I am not sure if this is the best solution or not, but it is what I need.

Please tell me if you know what is need to be changed for better performance or quality. In my case, I have a button.

Custom item on my menu - main.xml

<item
    android:id="@+id/badge"
    android:actionLayout="@layout/feed_update_count"
    android:icon="@drawable/shape_notification"
    android:showAsAction="always">
</item>

Custom shape drawable (background square) - shape_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
    <stroke android:color="#22000000" android:width="2dp"/>
    <corners android:radius="5dp" />
    <solid android:color="#CC0001"/>
</shape>

Layout for my view - feed_update_count.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/notif_count"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:minWidth="32dp"
     android:minHeight="32dp"
     android:background="@drawable/shape_notification"
     android:text="0"
     android:textSize="16sp"
     android:textColor="@android:color/white"
     android:gravity="center"
     android:padding="2dp"
     android:singleLine="true">    
</Button>

MainActivity - setting and updating my view

static Button notifCount;
static int mNotifCount = 0;    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main, menu);

    View count = menu.findItem(R.id.badge).getActionView();
    notifCount = (Button) count.findViewById(R.id.notif_count);
    notifCount.setText(String.valueOf(mNotifCount));
    return super.onCreateOptionsMenu(menu);
}

private void setNotifCount(int count){
    mNotifCount = count;
    invalidateOptionsMenu();
}

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Hide options in a select list using jQuery

Anybody stumbling across this question might also consider the use of Chosen, which greatly expands the capabilities of selects.

How to install Boost on Ubuntu

Install libboost-all-dev by entering the following commands in the terminal

Step 1

Update package repositories and get latest package information.

sudo apt update -y

Step 2

Install the packages and dependencies with -y flag .

sudo apt install -y libboost-all-dev

Now that you have your libboost-all-dev installed source: https://linuxtutorial.me/ubuntu/focal/libboost-all-dev/