Programs & Examples On #Acrobat

Adobe Acrobat is a family of applications developed by Adobe in order to view, create, manipulate, print and manage files in Portable Document Format (PDF).

Adobe Reader Command Line Reference

I found this:

http://www.robvanderwoude.com/commandlineswitches.php#Acrobat

Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":

AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Documentation for using JavaScript code inside a PDF file

The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.

To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.

Display Adobe pdf inside a div

You cannot, and here is the simple answer.

Every media asset poured into the browser is identified by a mime type name. A browser then makes processing determinations upon that mime type name. If it is image/gif or image/jpeg the browser processes the asset as an image. If it is text/css or text/javascript it is processed as a code asset unless the asset is addressed independent of HTML. PDF is identified as application/pdf. When browsers see application/pdf they immediately switch processing to a plugin software capable of processing that media type. If you attempt to push media of type application/pdf into a div the browser will likely throw an error to the user. Typically files of type application/pdf are linked to directly so that the processing software an intercept the request and process the media independent of the browser.

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

Possible to perform cross-database queries with PostgreSQL?

dblink() -- executes a query in a remote database

dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.

When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.

one of the good example:

SELECT * 
FROM   table1 tb1 
LEFT   JOIN (
   SELECT *
   FROM   dblink('dbname=db2','SELECT id, code FROM table2')
   AS     tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;

Note: I am giving this information for future reference. Refrence

Is there a command line utility for rendering GitHub flavored Markdown?

To read a README.md file in the terminal I use:

pandoc README.md | lynx -stdin

Pandoc outputs it in HTML format, which Lynx renders in your terminal.

It works great: It fills my terminal, shortcuts are shown below, I can scroll through, and the links work! There is only one font size though, but the colors + indentation + alignment make up for that.

Installation:

sudo apt-get install pandoc lynx

When to use React setState callback

Yes there is, since setState works in an asynchronous way. That means after calling setState the this.state variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful

Consider the example below

....
changeTitle: function changeTitle (event) {
  this.setState({ title: event.target.value });
  this.validateTitle();
},
validateTitle: function validateTitle () {
  if (this.state.title.length === 0) {
    this.setState({ titleError: "Title can't be blank" });
  }
},
....

The above code may not work as expected since the title variable may not have mutated before validation is performed on it. Now you may wonder that we can perform the validation in the render() function itself but it would be better and a cleaner way if we can handle this in the changeTitle function itself since that would make your code more organised and understandable

In this case callback is useful

....
changeTitle: function changeTitle (event) {
  this.setState({ title: event.target.value }, function() {
    this.validateTitle();
  });

},
validateTitle: function validateTitle () {
  if (this.state.title.length === 0) {
    this.setState({ titleError: "Title can't be blank" });
  }
},
....

Another example will be when you want to dispatch and action when the state changed. you will want to do it in a callback and not the render() as it will be called everytime rerendering occurs and hence many such scenarios are possible where you will need callback.

Another case is a API Call

A case may arise when you need to make an API call based on a particular state change, if you do that in the render method, it will be called on every render onState change or because some Prop passed down to the Child Component changed.

In this case you would want to use a setState callback to pass the updated state value to the API call

....
changeTitle: function (event) {
  this.setState({ title: event.target.value }, () => this.APICallFunction());
},
APICallFunction: function () {
  // Call API with the updated value
}
....

Good Hash Function for Strings

This function provided by Nick is good but if you use new String(byte[] bytes) to make the transformation to String, it failed. You can use this function to do that.

private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static String byteArray2Hex(byte[] bytes) {
    StringBuffer sb = new StringBuffer(bytes.length * 2);
    for(final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

public static String getStringFromSHA256(String stringToEncrypt) throws NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(stringToEncrypt.getBytes());
    return byteArray2Hex(messageDigest.digest());
}

May be this can help somebody

How to export table as CSV with headings on Postgresql?

COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);

as described in the manual.

Can you call Directory.GetFiles() with multiple filters?

What about

string[] filesPNG = Directory.GetFiles(path, "*.png");
string[] filesJPG = Directory.GetFiles(path, "*.jpg");
string[] filesJPEG = Directory.GetFiles(path, "*.jpeg");

int totalArraySizeAll = filesPNG.Length + filesJPG.Length + filesJPEG.Length;
List<string> filesAll = new List<string>(totalArraySizeAll);
filesAll.AddRange(filesPNG);
filesAll.AddRange(filesJPG);
filesAll.AddRange(filesJPEG);

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

How can I convert a .jar to an .exe?

Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:

exestub.sh:

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt  0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
    case $1 in
        -Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
        -D*)  JAVA_OPT="$JAVA_OPT $1" ;;
        *)    PROG_OPT="$PROG_OPT $1" ;;
    esac
    shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT

Then you create your runnable file from your jar:

$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable

It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>, as <myexe> is a valid zip/jar file.

How to increase an array's length

You can make use of ArrayList. Array has the fixed number of size.

This Example here can help you. The example is pretty easy with its output.

Output:
2 5 1 23 14 
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29

How to declare variable and use it in the same Oracle SQL script?

Here's your answer:

DEFINE num := 1;       -- The semi-colon is needed for default values.
SELECT &num FROM dual;

What's the proper way to compare a String to an enum value?

You should declare toString() and valueOf() method in enum.

 import java.io.Serializable;

public enum Gesture implements Serializable {
    ROCK,PAPER,SCISSORS;

    public String toString(){
        switch(this){
        case ROCK :
            return "Rock";
        case PAPER :
            return "Paper";
        case SCISSORS :
            return "Scissors";
        }
        return null;
    }

    public static Gesture valueOf(Class<Gesture> enumType, String value){
        if(value.equalsIgnoreCase(ROCK.toString()))
            return Gesture.ROCK;
        else if(value.equalsIgnoreCase(PAPER.toString()))
            return Gesture.PAPER;
        else if(value.equalsIgnoreCase(SCISSORS.toString()))
            return Gesture.SCISSORS;
        else
            return null;
    }
}

How to run a C# console application with the console hidden

If you're creating a program that doesn't require user input you could always just create it as a service. A service won't show any kind of UI.

What is the difference between T(n) and O(n)?

Short explanation:

If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).

If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).

Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.


More technically:

O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.

f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))

Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).

In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,

f(x) = T(g(x)) iff g(x) = T(f(x))

Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,

f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))


There are also little-oh and little-omega (?) notations representing loose upper and loose lower bounds of a function.

To summarize:

f(x) = O(g(x)) (big-oh) means that the growth rate of f(x) is asymptotically less than or equal to to the growth rate of g(x).

f(x) = O(g(x)) (big-omega) means that the growth rate of f(x) is asymptotically greater than or equal to the growth rate of g(x)

f(x) = o(g(x)) (little-oh) means that the growth rate of f(x) is asymptotically less than the growth rate of g(x).

f(x) = ?(g(x)) (little-omega) means that the growth rate of f(x) is asymptotically greater than the growth rate of g(x)

f(x) = T(g(x)) (theta) means that the growth rate of f(x) is asymptotically equal to the growth rate of g(x)

For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.

Show / hide div on click with CSS

You can find <div> by id, look at it's style.display property and toggle it from none to block and vice versa.

_x000D_
_x000D_
function showDiv(Div) {_x000D_
    var x = document.getElementById(Div);_x000D_
    if(x.style.display=="none") {_x000D_
        x.style.display = "block";_x000D_
    } else {_x000D_
        x.style.display = "none";_x000D_
    }_x000D_
}
_x000D_
<div id="welcomeDiv" style="display:none;" class="answer_list">WELCOME</div>_x000D_
<input type="button" name="answer" value="Show Div" onclick="showDiv('welcomeDiv')" />
_x000D_
_x000D_
_x000D_

Kill a Process by Looking up the Port being used by it from a .BAT

Just for completion:

I wanted to kill all processes connected to a specific port but not the process listening

the command (in cmd shell) for the port 9001 is:

FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| findstr -rc:":9001[ ]*ESTA"') DO TaskKill /F /PID %P

findstr:

  • r is for expressions and c for exact chain to match.
  • [ ]* is for matching spaces

netstat:

  • a -> all
  • n -> don't resolve (faster)
  • o -> pid

It works because netstat prints out the source port then destination port and then ESTABLISHED

How to write a cron that will run a script every day at midnight?

Quick guide to setup a cron job

Create a new text file, example: mycronjobs.txt

For each daily job (00:00, 03:45), save the schedule lines in mycronjobs.txt

00 00 * * * ruby path/to/your/script.rb
45 03 * * * path/to/your/script2.sh

Send the jobs to cron (everytime you run this, cron deletes what has been stored and updates with the new information in mycronjobs.txt)

crontab mycronjobs.txt

Extra Useful Information

See current cron jobs

crontab -l

Remove all cron jobs

crontab -r

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Can you use if/else conditions in CSS?

Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.

Query to select data between two dates with the format m/d/yyyy

select * from xxx where dates between '2012-10-10' and '2012-10-12'

I always use YYYY-MM-DD in my views and never had any issue. Plus, it is readable and non equivocal.
You should be aware that using BETWEEN might not return what you expect with a DATETIME field, since it would eliminate records dated '2012-10-12 08:00' for example.
I would rather use where dates >= '2012-10-10' and dates < '2012-10-13' (lower than next day)

Bringing a subview to be in front of all other views

try this:

self.view.layer.zPosition = 1;

Android Studio Rendering Problems : The following classes could not be found

Please see the following link - here is where I found a solution that worked for me.

Rendering problems in Android Studio v 1.1 / 1.2

Changing the Android Version when rendering layouts worked for me - I flipped it back to 21 and my "Hello World" app then rendered the basic activity_main.xml OK - at 22 I got this error. I borrowed the image from this posting to show you where to click in the Design tab of the XML preview. What is wierd is that when I flip back to 22 the problem is still gone :-).

enter image description here

How can I find out a file's MIME type (Content-Type)?

Try the file command with -i option.

-i option Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii rather than ASCII text.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

HTML table needs spacing between columns, not rows

This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.

The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th, td or something else.

_x000D_
_x000D_
tr > * + * {
  padding-left: 4em;
}
_x000D_
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

What's the difference between primitive and reference types?

Primitive Data Types :

  • Predefined by the language and named by a keyword
  • Total no = 8
    boolean
    char
    byte
    short
    integer
    long
    float
    double

Reference/Object Data Types :

  • Created using defined constructors of the classes
  • Used to access objects
  • Default value of any reference variable is null
  • Reference variable can be used to refer to any object of the declared type or any compatible type.

Powershell equivalent of bash ampersand (&) for forking/running background processes

You can do something like this.

$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru

And if you want to wait for it:

$a | wait-process

Bonus osx or linux version:

$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru 

Example pinger script I have. The args are passed as an array:

$1 = start -n powershell pinger,comp001 -pa

Django: How can I call a view function from template?

One option is, you can wrap the submit button with a form

Something like this:

<form action="{% url path.to.request_page %}" method="POST">
    <input id="submit" type="button" value="Click" />
</form>

(remove the onclick and method)

If you want to load a specific part of the page, without page reload - you can do

<input id="submit" type="button" value="Click" data_url/>

and on a submit listener

$(function(){
     $('form').on('submit', function(e){
         e.preventDefault();
         $.ajax({
             url: $(this).attr('action'),
             method: $(this).attr('method'),
             success: function(data){ $('#target').html(data) }
         });
     });
});

Type definition in object literal in TypeScript

// Use ..

const Per = {
  name: 'HAMZA',
  age: 20,
  coords: {
    tele: '09',
    lan: '190'
  },
  setAge(age: Number): void {
    this.age = age;
  },
  getAge(): Number {
    return age;
  }
};
const { age, name }: { age: Number; name: String } = Per;
const {
  coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;

console.log(Per.getAge());

Failed to find target with hash string 'android-25'

It seems like that it is only me who are so clumsy, because i have yet to found a solution that my case required.

I am developing a multi-modular project, thus base android module configuration is extracted in single gradle script. All the concrete versions of sdks/libs are also extracted in a script.

A script containing versions looked like this:

...

ext.androidVersions = [
    compile_sdk_version     : '27',
    min_sdk_version         : '19',
    target_sdk_version      : '27',
    build_tool_version      : '27.0.3',
    application_id          : 'com.test.test',
]

...

Not accustomed to groovy syntax my eye has not spotted that the values for compile, min and target sdks were not integers but STRINGS! Therefore a compiler rightfully complained about not being able to find an sdk a version of which would match HASH STRING '27'.

So the solution would be to make sdk's versions integers: ...

ext.androidVersions = [
    compile_sdk_version     : 27,
    min_sdk_version         : 19,
    target_sdk_version      : 27,
    build_tool_version      : '27.0.3',
    application_id          : 'com.test.test',
]

...

Delete directories recursively in Java

Well, let's assume an example,

import java.io.File;
import java.io.IOException;

public class DeleteDirectory
{
   private static final String folder = "D:/project/java";

   public static void main(String[] args) throws IOException
   {
      File fl = new File(folder);
      if(!fl.exists()) // checking if directory exists
      {
         System.out.println("Sorry!! directory doesn't exist.");
      }
      else
      {
         DeleteDirectory dd = new DeleteDirectory();
         dd.deleteDirectory(fl);
      }
   }

   public void deleteDirectory(File file) throws IOException
   {
      if(file.isDirectory())
      {
         if(file.list().length == 0)
         { 
            deleteEmptyDirectory(file); // here if directory is empty delete we are deleting
         }
         else
         {
            File fe[] = file.listFiles();
            for(File deleteFile : fe)
            {
               deleteDirectory(deleteFile); // recursive call
            }
            if(file.list().length == 0)
            {
               deleteEmptyDirectory(file);
            }
         }
      }
      else
      {
         file.delete();
         System.out.println("File deleted : " + file.getAbsolutePath());
      }
   }

   private void deleteEmptyDirectory(File fi)
   {
      fi.delete();
      System.out.println("Directory deleted : " + fi.getAbsolutePath());
   }
}

For more information refer below resources

Delete directory

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

For this situation you have to connect to database in Single-User mode.

Starting SQL Server in single-user mode enables any member of the computer's local Administrators group to connect to the instance of SQL Server as a member of the sysadmin fixed server role.

Here you can find step-by-step instruction to do this.

In short you must start the sqlserver instance with parameters -m, after start Sql Server Management Studio with windows authentication.

Now you are a sysadmin, assign the sysadmin role to your user, exit and remove the -m parameter and restart sql server.

Multiple modals overlay

Add global variable in modal.js

var modalBGIndex = 1040; // modal backdrop background
var modalConIndex = 1042; // modal container data 

// show function inside add variable - Modal.prototype.backdrop

var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

modalConIndex = modalConIndex + 2; // add this line inside "Modal.prototype.show"

that.$element
    .show()
    .scrollTop(0)
that.$element.css('z-index',modalConIndex) // add this line after show modal 

if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      modalBGIndex = modalBGIndex + 2; // add this line increase modal background index 2+

this.$backdrop.addClass('in')
this.$backdrop.css('z-index',modalBGIndex) // add this line after backdrop addclass

Getting the names of all files in a directory with PHP

On some OS you get . .. and .DS_Store, Well we can't use them so let's us hide them.

First start get all information about the files, using scandir()

// Folder where you want to get all files names from
$dir = "uploads/";

/* Hide this */
$hideName = array('.','..','.DS_Store');    

// Sort in ascending order - this is default
$files = scandir($dir);
/* While this to there no more files are */
foreach($files as $filename) {
    if(!in_array($filename, $hideName)){
       /* echo the name of the files */
       echo "$filename<br>";
    }
}

Splitting a string into separate variables

It is important to note the following difference between the two techniques:

$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT 

From this you can see that the string.split() method:

  • performs a case sensitive split (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
  • treats the string as a list of possible characters to split on

While the -split operator:

  • performs a case-insensitive comparison
  • only splits on the whole string

.NET: Simplest way to send POST with data and read response

Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. This class nicely abstracts the details. There's even a full code example in the MSDN documentation.

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

In your case, you want the UploadData() method. (Again, a code sample is included in the documentation)

http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx

UploadString() will probably work as well, and it abstracts it away one more level.

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

Sum across multiple columns with dplyr

If you want to sum certain columns only, I'd use something like this:

library(dplyr)
df=data.frame(
  x1=c(1,0,0,NA,0,1,1,NA,0,1),
  x2=c(1,1,NA,1,1,0,NA,NA,0,1),
  x3=c(0,1,0,1,1,0,NA,NA,0,1),
  x4=c(1,0,NA,1,0,0,NA,0,0,1),
  x5=c(1,1,NA,1,1,1,NA,1,0,1))
df %>% select(x3:x5) %>% rowSums(na.rm=TRUE) -> df$x3x5.total
head(df)

This way you can use dplyr::select's syntax.

Can I use Homebrew on Ubuntu?

October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -

(first, install pre-requisites using sudo apt-get install build-essential curl file git)

finally create a ~/.zprofile with the following contents: emulate sh -c '. ~/.profile'

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

How to ping an IP address

short recommendation: don't use isReachable(), call the system ping, as proposed in some of the answers above.

long explanation:

  • ping uses the ICMP network protcol. To use ICMP, a 'raw socket' is needed
  • standard users are not allowed by the operating system to use raw sockets
  • the following applies to a fedora 30 linux, windows systems should be similar
  • if java runs as root, isReachable() actually sends ICMP ping requests
  • if java does not run as root, isReachable() tries to connect to TCP port 7, known as the echo port. This service is commonly not used any more, trying to use it might yield improper results
  • any kind of answer to the connection request, also a reject (TCP flag RST) yields a 'true' from isReachable()
  • some firewalls send RST for any port that is not explicitly open. If this happens, you will get isReachable() == true for a host that does not even exist
  • further tries to assign the necessary capabilities to a java process:
  • setcap cap_net_raw+eip java executable (assign the right to use raw sockets)
  • test: getcap java executable -> 'cap_net_raw+eip' (capability is assigned)
  • the running java still sends a TCP request to port 7
  • check of the running java process with getpcaps pid shows that the running java does not have the raw socket capablity. Obviously my setcap has been overridden by some security mechanism
  • as security requirements are increasing, this is likely to become even more restricted, unless s.b. implements an exception especially for ping (but nothing found on the net so far)

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

Populate dropdown select with array using jQuery

function validateForm(){
    var success = true;
    resetErrorMessages();
    var myArray = [];
    $(".linkedServiceDonationPurpose").each(function(){
        myArray.push($(this).val())
    });

    $(".linkedServiceDonationPurpose").each(function(){
    for ( var i = 0; i < myArray.length; i = i + 1 ) {
        for ( var j = i+1; j < myArray.length; j = j + 1 )
            if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                $(this).next( "div" ).html('Duplicate item selected');
                success=false;
           }
        } 
    });
    if (success) {
        return true;
    } else {
        return false;
    }
    function resetErrorMessages() {
        $(".error").each(function(){
            $(this).html('');
        });``
    }
}

How to serialize an object to XML without getting xmlns="..."?

If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.

I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":

    public static string XmlSerialize<T>(T entity) where T : class
    {
        // removes version
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;

        XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
        using (StringWriter sw = new StringWriter())
        using (XmlWriter writer = XmlWriter.Create(sw, settings))
        {
            // removes namespace
            var xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);

            xsSubmit.Serialize(writer, entity, xmlns);
            return sw.ToString(); // Your XML
        }
    }

Creating random colour in Java?

import android.graphics.Color;

import java.util.Random;

public class ColorDiagram {
    // Member variables (properties about the object)
    public String[] mColors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975", // mauve
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7"  // light gray
    };

    // Method (abilities: things the object can do)
    public int getColor() {
        String color = "";

        // Randomly select a fact
        Random randomGenerator = new Random(); // Construct a new Random number generator
        int randomNumber = randomGenerator.nextInt(mColors.length);

        color = mColors[randomNumber];
        int colorAsInt = Color.parseColor(color);

        return colorAsInt;
    }
}

How to Calculate Execution Time of a Code Snippet in C++

You could also look at the [cxx-rtimers][1] on GitHub, which provide some header-only routines for gathering statistics on the run-time of any code-block where you can create a local variable. Those timers have versions that use std::chrono on C++11, or timers from the Boost library, or standard POSIX timer functions. These timers will report the average, maximum & minimum duration spent within a function, as well as the number of times it is called. They can be used as simply as follows:

#include <rtimers/cxx11.hpp>

void expensiveFunction() {
    static rtimers::cxx11::DefaultTimer timer("expensive");
    auto scopedStartStop = timer.scopedStart();
    // Do something costly...
}

How to add a footer in ListView?

I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.

Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment

Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":

<RelativeLayout>

<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/> 
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->

</RelativeLayout>

How to clean old dependencies from maven repositories?

  1. Download all actual dependencies of your projects

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  2. Move your local maven repository to temporary location

    mv ~/.m2 ~/saved-m2
    
  3. Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*

    find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
    
  4. To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):

    <settings>
     <mirrors>
      <mirror>
       <id>mycentral</id>
       <name>My Central</name>
       <url>file:/home/user/saved-m2/</url>
       <mirrorOf>central</mirrorOf>
      </mirror>
     </mirrors>
    </settings>
    
  5. Resolve your projects dependencies again:

    find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
    
  6. Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.

Eclipse interface icons very small on high resolution screen in Windows 8.1

There is a nice article in JaxEnter for an work around HiDPI for Eclipse

How to download a file from my server using SSH (using PuTTY on Windows)

If your server have a http service you can compress your directory and download the compressed file.

Compress:

tar -zcvf archive-name.tar.gz -C directory-name .

Download throught your browser:

http://the-server-ip/archive-name.tar.gz

If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.

How to delete files/subfolders in a specific directory at the command prompt in Windows

@ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

Dart/Flutter : Converting timestamp

All of that above can work but for a quick and easy fix you can use the time_formatter package.

Using this package you can convert the epoch to human-readable time.

String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you 
   String formatted = formatTime(timeStamp).toString();
   return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"

Here you can check the format of the output that is going to be displayed: Formats

write newline into a file

Solution:

in WINDOWS you should write "\r\n" for a new line.

Convert hex string to int in Python

with '0x' prefix, you might also use eval function

For example

>>a='0xff'
>>eval(a)
255

Android button background color

Create /res/drawable/button.xml with the following content :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
 <solid android:color="#90EE90"/> 
    <corners
     android:bottomRightRadius="3dp"
     android:bottomLeftRadius="3dp"
  android:topLeftRadius="3dp"
  android:topRightRadius="3dp"/>
</shape>

And then you can use the following :

<Button
    android:id="@+id/button_save_prefs"
    android:text="@string/save"
    android:background="@drawable/button"/>

What is the difference between React Native and React?

React Native is a framework to use React for building android and ios apps. React is a web framework used to build awesome websites.

pycharm running way slow

In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

Is it possible to break a long line to multiple lines in Python?

When trying to enter continuous text (say, a query) do not put commas at the end of the line or you will get a list of strings instead of one long string:

queryText= "SELECT * FROM TABLE1 AS T1"\
"JOIN TABLE2 AS T2 ON T1.SOMETHING = T2.SOMETHING"\
"JOIN TABLE3 AS T3 ON T3.SOMETHING = T2.SOMETHING"\
"WHERE SOMETHING BETWEEN <WHATEVER> AND <WHATEVER ELSE>"\
"ORDER BY WHATEVERS DESC"

kinda like that.

There is a comment like this from acgtyrant, sorry, didn't see that. :/

String to object in JS

I know this is an old post but didn't see the correct answer for the question.

var jsonStrig = '{';
      var items = string.split(',');
      for (var i = 0; i < items.length; i++) {
          var current = items[i].split(':');
          jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
      }
      jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
      jsonStrig += '}';
var obj = JSON.parse(jsonStrig);
console.log(obj.firstName, obj.lastName);

Now you can use obj.firstName and obj.lastName to get the values as you could do normally with an object.

Error: Cannot find module 'gulp-sass'

i was also facing the same issue, The possible solution is to install the gulp-sass module, but if you will run the below command npm install -g gulp-sass or npm install --save gulp-sass, This is not going to be updated on node-sass project's end.

This version of node-sass is missing (returns a 404) and google web-starter-kit v0.6.5 has depended on it for a long time, since Dec 2016. So, it has been working for a long time and must have just disappeared.

Downloading binary from https://github.com/sass/node-sass/releases/download/v3.13.1/win32-x64-57_binding.node Cannot download "https://github.com/sass/node-sass/releases/download/v3.13.1/win32-x64-57_binding.node":

HTTP error 404 Not Found

The only workaround is to upgrade node-sass: npm i gulp-sass@latest --save-dev to fix the issue.

You seem to not be depending on "@angular/core". This is an error

This happened to me when I was mixing package managers. My project was generated with Yarn, and after that, I added a couple of dependencies using npm install (this created the package-lock.json with only added dependencies).

Apparently, ng serve used package-lock.json and couldn't find Angular dependencies there. After I started using only Yarn, i.e. yarn add instead of npm install, the error was gone.

Properly Handling Errors in VBA (Excel)

I keep things simple:
At the module level I define two variables and set one to the name of the module itself.

    Private Const ThisModuleName            As String = "mod_Custom_Functions"
    Public sLocalErrorMsg                   As String

Within each Sub/Function of the module I define a local variable

    Dim ThisRoutineName                     As String

I set ThisRoutineName to the name of the sub or function

' Housekeeping
    On Error Goto ERR_RTN
    ThisRoutineName = "CopyWorksheet"

I then send all errors to an ERR_RTN: when they occur, but I first set the sLocalErrorMsg to define what the error actually is and provide some debugging info.

    If Len(Trim(FromWorksheetName)) < 1 Then
        sLocalErrorMsg = "Parameter 'FromWorksheetName' Is Missing."
        GoTo ERR_RTN
    End If

At the bottom of each sub/function, I direct the logic flow as follows

    '
    ' The "normal" logic goes here for what the routine does
    '
    GoTo EXIT_RTN

    ERR_RTN:

        On Error Resume Next

    ' Call error handler if we went this far.
        ErrorHandler ThisModuleName, ThisRoutineName, sLocalErrorMsg, Err.Description, Err.Number, False

    EXIT_RTN:

        On Error Resume Next
     '
     ' Some closing logic
     '
    End If

I then have a seperate module I put in all projects called "mod_Error_Handler".

    '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Subroutine Name:     ErrorHandler                                                     '
    '                                                                                       '
    ' Description:                                                                          '
    '   This module will handle the common error alerts.                                    '
    '                                                                                       '
    ' Inputs:                                                                               '
    '   ModuleName                String    'The name of the module error is in.            '
    '   RoutineName               String    'The name of the routine error in in.           '
    '   LocalErrorMsg             String    'A local message to assist with troubleshooting.'
    '   ERRDescription            String    'The Windows Error Description.                 '
    '   ERRCode                   Long      'The Windows Error Code.                        '
    '   Terminate                 Boolean   'End program if error encountered?              '
    '                                                                                       '
    ' Revision History:                                                                     '
    ' Date (YYYYMMDD) Author                Change                                          '
    ' =============== ===================== =============================================== '
    ' 20140529        XXXXX X. XXXXX        Original                                        '
    '                                                                                       '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    Public Sub ErrorHandler(ModuleName As String, RoutineName As String, LocalErrorMsg As String, ERRDescription As String, ERRCode As Long, Terminate As Boolean)
        Dim sBuildErrorMsg                 As String

    ' Build Error Message To Display
        sBuildErrorMsg = "Error Information:" & vbCrLf & vbCrLf

        If Len(Trim(ModuleName)) < 1 Then
            ModuleName = "Unknown"
        End If

        If Len(Trim(RoutineName)) < 1 Then
           RoutineName = "Unknown"
        End If

        sBuildErrorMsg = sBuildErrorMsg & "Module Name:        " & ModuleName & vbCrLf & vbCrLf
        sBuildErrorMsg = sBuildErrorMsg & "Routine Name:       " & RoutineName & vbCrLf & vbCrLf

        If Len(Trim(LocalErrorMsg)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Local Error Msg:    " & LocalErrorMsg & vbCrLf & vbCrLf
        End If

        If Len(Trim(ERRDescription)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Program Error Msg:  " & ERRDescription & vbCrLf & vbCrLf
            If IsNumeric(ERRCode) Then
                sBuildErrorMsg = sBuildErrorMsg & "Program Error Code: " & Trim(Str(ERRCode)) & vbCrLf & vbCrLf
            End If
        End If

        MsgBox sBuildErrorMsg, vbOKOnly + vbExclamation, "Error Detected!"

        If Terminate Then
            End
        End If

    End Sub

The end result is a pop-up error message teling me in what module, what soubroutine, and what the error message specifically was. In addition, it also will insert the Windows error message and code.

How to use private Github repo as npm dependency

With git there is a https format

https://github.com/equivalent/we_demand_serverless_ruby.git

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json


{
  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...
}

https://blog.eq8.eu/til/pull-git-private-repo-from-github-from-npm-modules-or-bundler.html

Developing for Android in Eclipse: R.java not regenerating

I had a problem with my AndroidManifest.xml file and the R.java was not generated.

I think the solution is to check ALL of your XML files, everywhere!

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

What is the list of valid @SuppressWarnings warning names in Java?

A new favorite for me is @SuppressWarnings("WeakerAccess") in IntelliJ, which keeps it from complaining when it thinks you should have a weaker access modifier than you are using. We have to have public access for some methods to support testing, and the @VisibleForTesting annotation doesn't prevent the warnings.

ETA: "Anonymous" commented, on the page @MattCampbell linked to, the following incredibly useful note:

You shouldn't need to use this list for the purpose you are describing. IntelliJ will add those SuppressWarnings for you automatically if you ask it to. It has been capable of doing this for as many releases back as I remember.

Just go to the location where you have the warning and type Alt-Enter (or select it in the Inspections list if you are seeing it there). When the menu comes up, showing the warning and offering to fix it for you (e.g. if the warning is "Method may be static" then "make static" is IntellJ's offer to fix it for you), instead of selecting "enter", just use the right arrow button to access the submenu, which will have options like "Edit inspection profile setting" and so forth. At the bottom of this list will be options like "Suppress all inspections for class", "Suppress for class", "Suppress for method", and occasionally "Suppress for statement". You probably want whichever one of these appears last on the list. Selecting one of these will add a @SuppressWarnings annotation (or comment in some cases) to your code suppressing the warning in question. You won't need to guess at which annotation to add, because IntelliJ will choose based on the warning you selected.

ClientScript.RegisterClientScriptBlock?

See if the below helps you:

I was using the following earlier:

ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");

After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:

ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);

This is working perfectly fine.

(It’s .NET 2.0 Framework, I am using)

Get Today's date in Java at midnight time

A solution in Java 8:

Date startOfToday = Date.from(ZonedDateTime.now().with(LocalTime.MIN).toInstant());

How does a PreparedStatement avoid or prevent SQL injection?

PreparedStatement:

1) Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

2) Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value.

Basic communication between two fragments

Update

Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.

Original Answer

Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,

FragmentB.java

private String inputString;
....
....

public void setInputString(String string){
   inputString = string;
}

FragmentA.java

//go to fragment B

FragmentB frag  = new FragmentB();
frag.setInputString(YOUR_STRING);
//create your fragment transaction object, set animation etc
fragTrans.replace(ITS_ARGUMENTS)

Or you can use Activity as you suggested in question..

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

Is this the proper way to do boolean test in SQL?

A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:

select * from users where active = 1 /* All Active Users */

or

select * from users where active = 0 /* All Inactive Users */

How do I change Bootstrap 3 column order on mobile layout?

October 2017

I would like to add another Bootstrap 4 solution. One that worked for me.

The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Adjust the screen size and you'll see the columns get stacked in a different order.

I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.

Windows batch: call more than one command in a FOR loop?

Using & is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.

FOR /r %%X IN (*.txt) DO (
    ECHO %%X
    DEL %%X
)

Placement of ( and ) matters. The round brackets after DO must be placed on the same line, otherwise the batch file will be incorrect.

See if /?|find /V "" for details.

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

jQuery show for 5 seconds then hide

You can use the below effect to animate, you can change the values as per your requirements

$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow'); 

Typescript - multidimensional array initialization

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}

Easy pretty printing of floats in python?

To control the number of significant digits, use the format specifier %g.

Let's name Emile's solution prettylist2f. Here is the modified one:

prettylist2g = lambda l : '[%s]' % ', '.join("%.2g" % x for x in l)

Usage:

>>> c_e_alpha_eps0 = [299792458., 2.718281828, 0.00729735, 8.8541878e-12]
>>> print(prettylist2f(c_e_alpha_eps0)) # [299792458.00, 2.72, 0.01, 0.00]
>>> print(prettylist2g(c_e_alpha_eps0)) # [3e+08, 2.7, 0.0073, 8.9e-12]

If you want flexibility in the number of significant digits, use f-string formatting instead:

prettyflexlist = lambda p, l : '[%s]' % ', '.join(f"{x:.{p}}" for x in l)
print(prettyflexlist(3,c_e_alpha_eps0)) # [3e+08, 2.72, 0.0073, 8.85e-12]

GitHub README.md center image

You can also resize the image to the desired width and height. For example:

<p align="center">
  <img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>

To add a centered caption to the image, just one more line:

<p align="center">This is a centered caption for the image<p align="center">

Fortunately, this works both for README.md and the GitHub Wiki pages.

Creating a simple XML file using python

Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).

It's using context manager and with keyword.

from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag('root'):
    with tag('doc'):
        with tag('field1', name='blah'):
            text('some value1')
        with tag('field2', name='asdfasd'):
            text('some value2')

result = indent(
    doc.getvalue(),
    indentation = ' '*4,
    newline = '\r\n'
)

print(result)

so you will get:

<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some value2</field2>
    </doc>
</root>

Hunk #1 FAILED at 1. What's that mean?

I got the "hunks failed" message when I wasn't applying the patch in the top directory of the associated git project. I was applying the patch (where I created it) in a subdirectory.

It seems patches can be created from subdirectories within a git project, but not applied.

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

How to convert int to char with leading zeros?

I found a good article here:

Padding a string with leading zeros

I've need to do this a lot of times when outputing a fixed length data export where for instance a numeric column is 9 characters long and you need to prefix with leading 0's.

Align nav-items to right side in bootstrap-4

This should work for alpha 6. The key is the class "mr-auto" on the left nav, which will push the right nav to the right. You also need to add navbar-toggleable-md or it will stack in a column instead of a row. Note I didn't add the remaining toggle items (e.g. toggle button), I added just enough to get it to formatted as requested. Here are more complete examples https://v4-alpha.getbootstrap.com/examples/navbars/.

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
        <div class="container">
            <a class="navbar-brand" href="#">Navbar</a>
            <ul class="nav navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
            </ul>
            <ul class="nav navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="#">Link on the Right</a>
                </li>
            </ul>
        </div>
    </nav>
</body>

How to redirect a URL path in IIS?

Taken from Microsoft Technet.

Redirecting Web Sites in IIS 6.0 (IIS 6.0)


When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.

You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.

Important

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Procedures

To redirect requests to another Web site or directory


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.

To redirect all requests to a single file


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination file.

  5. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

    You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.

    You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.

    To redirect requests to a program


  6. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  7. Click the Home Directory, Virtual Directory, or Directory tab.

  8. Under The content for this source should come from, click A redirection to a URL.

    In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.

  9. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

As in Swift 3.x for upload image with parameter we can use below alamofire upload method-

static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {

        let imageData = UIImageJPEGRepresentation(imageFile , 0.5)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")

            for key in parameters.keys{
                let name = String(key)
                if let val = parameters[name!] as? String{
                    multipartFormData.append(val.data(using: .utf8)!, withName: name!)
                }
            }
        }, to:inputUrl)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                })

                upload.responseJSON { response in

                    if let JSON = response.result.value {
                        completion(JSON)
                    }else{
                        completion(nilValue)
                    }
                }

            case .failure(let encodingError):
                completion(nilValue)
            }

        }

    }

Note: Additionally if our parameter is array of key-pairs then we can use

 var arrayOfKeyPairs = [[String:Any]]()
 let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
 let jsonPresentation = String(data: json!, encoding: .utf8)

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

Java null check why use == instead of .equals()

Object.equals is null safe, however be aware that if two objects are null, object.equals will return true so be sure to check that the objects you are comparing aren't null (or hold null values) before using object.equals for comparison.

String firstname = null;
String lastname = null;

if(Objects.equals(firstname, lastname)){
    System.out.println("equal!");
} else {
    System.out.println("not equal!");
}

Example snippet above will return equal!

How do I give text or an image a transparent background using CSS?

If you are a Photoshop guy, you can also use:

 #some-element {
  background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
 }

Or:

#some-element {
  background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
}

Removing fields from struct or hiding them in JSON Response

Another way to do this is to have a struct of pointers with the ,omitempty tag. If the pointers are nil, the fields won't be Marshalled.

This method will not require additional reflection or inefficient use of maps.

Same example as jorelli using this method: http://play.golang.org/p/JJNa0m2_nw

Open Url in default web browser

A simpler way which eliminates checking if the app can open the url.

  loadInBrowser = () => {
    Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
  };

Calling it with a button.

<Button title="Open in Browser" onPress={this.loadInBrowser} />

Lambda function in list comprehensions

People gave good answers but forgot to mention the most important part in my opinion: In the second example the X of the list comprehension is NOT the same as the X of the lambda function, they are totally unrelated. So the second example is actually the same as:

[Lambda X: X*X for I in range(10)]

The internal iterations on range(10) are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).

On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]

Select every Nth element in CSS

You need the correct argument for the nth-child pseudo class.

  • The argument should be in the form of an + b to match every ath child starting from b.

  • Both a and b are optional integers and both can be zero or negative.

    • If a is zero then there is no "every ath child" clause.
    • If a is negative then matching is done backwards starting from b.
    • If b is zero or negative then it is possible to write equivalent expression using positive b e.g. 4n+0 is same as 4n+4. Likewise 4n-1 is same as 4n+3.

Examples:

Select every 4th child (4, 8, 12, ...)

_x000D_
_x000D_
li:nth-child(4n) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 4th child starting from 1 (1, 5, 9, ...)

_x000D_
_x000D_
li:nth-child(4n+1) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)

_x000D_
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select first 4 items (4, 3, 2, 1)

_x000D_
_x000D_
/* when a is negative then matching is done backwards  */_x000D_
li:nth-child(-n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

popup form using html/javascript/css

But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.

Umm. Just change the string passed to the prompt() function.

While searching, I found that there we CANNOT change the content of popup Prompt Box

You can't change the title. You can change the content, it is the first argument passed to the prompt() function.

Select first and last row from grouped data

Not dplyr, but it's much more direct using data.table:

library(data.table)
setDT(df)
df[ df[order(id, stopSequence), .I[c(1L,.N)], by=id]$V1 ]
#    id stopId stopSequence
# 1:  1      a            1
# 2:  1      c            3
# 3:  2      b            1
# 4:  2      c            4
# 5:  3      b            1
# 6:  3      a            3

More detailed explanation:

# 1) get row numbers of first/last observations from each group
#    * basically, we sort the table by id/stopSequence, then,
#      grouping by id, name the row numbers of the first/last
#      observations for each id; since this operation produces
#      a data.table
#    * .I is data.table shorthand for the row number
#    * here, to be maximally explicit, I've named the variable V1
#      as row_num to give other readers of my code a clearer
#      understanding of what operation is producing what variable
first_last = df[order(id, stopSequence), .(row_num = .I[c(1L,.N)]), by=id]
idx = first_last$row_num

# 2) extract rows by number
df[idx]

Be sure to check out the Getting Started wiki for getting the data.table basics covered

WCF - How to Increase Message Size Quota

You'll want something like this to increase the message size quotas, in the App.config or Web.config file:

<bindings>
    <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000" 
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
            <readerQuotas maxDepth="32" 
                 maxArrayLength="200000000"
                 maxStringContentLength="200000000"/>
        </binding>
    </basicHttpBinding>
</bindings>

And use the binding name in your endpoint configuration e.g.

...
bindingConfiguration="basicHttp"
...

The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.

"Could not find Developer Disk Image"

If you want to develop with Xcode 7 on your iOS10 device :
(Note: you can adapt this command to other Xcode and iOS versions)

  1. Rename your Xcode.app to Xcode7.app and download Xcode 8 from the app store.
  2. Run Xcode 8 once to install it.
  3. Open the terminal and create a symbolic link from Xcode 8 Developer Disk Image 10.0 to Xcode 8 Developer Disk Image folder using this command:

    ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0\ \(14A345\)/ /Applications/Xcode7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
    

Source

Overcoming "Display forbidden by X-Frame-Options"

Try this thing, i dont think anyone suggested this in the Topic, this will resolve like 70% of your issue, for some other pages, you have to scrap, i have the full solution but not for public,

ADD below to your iframe

sandbox="allow-same-origin allow-scripts allow-popups allow-forms"

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should use semicolons after every statement in JavaScript.

Hex colors: Numeric representation for "transparent"?

I was also trying for transparency - maybe you could try leaving blank the value of background e.g. something like

bgcolor=" "

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Replace duplicate spaces with a single space in T-SQL

Method #1

The first method is to replace extra spaces between words with an uncommon symbol combination as a temporary marker. Then you can replace the temporary marker symbols using the replace function rather than a loop.

Here is a code example that replaces text within a String variable.

DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
SELECT REPLACE(REPLACE(REPLACE(@testString, ' ', '*^'), '^*', ''), '*^', ' ');

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.7 milliseconds and total execution time was 4.6 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.7 milliseconds and total execution time was 3.7 milliseconds.

Method #2

The second method is not quite as elegant as the first, but also gets the job done. This method works by nesting four (or optionally more) replace statements that replace two blank spaces with one blank space.

DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
SELECT REPLACE(REPLACE(REPLACE(REPLACE(@testString,' ',' '),' ',' '),' ',' '),' ',' ')

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.9 milliseconds and total execution time was 3.8 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.8 milliseconds and total execution time was 4.8 milliseconds.

Method #3

The third method of replacing extra spaces between words is to use a simple loop. You can do a check on extra spaces in a while loop and then use the replace function to reduce the extra spaces with each iteration of the loop.

DECLARE @testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
WHILE CHARINDEX(' ',@testString) > 0
SET @testString = REPLACE(@testString, ' ', ' ')
SELECT @testString

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.8 milliseconds and total execution time was 3.4 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.9 milliseconds and total execution time was 2.8 milliseconds.

mysql query result in php variable

I personally use prepared statements.

Why is it important?

Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.

Instead of using this code:

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);

You should use this

$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();

Learn more about prepared statements on:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI

http://php.net/manual/en/pdo.prepared-statements.php PDO

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

Maximum call stack size exceeded on npm install

Happened in docker (node:15-buster) for me.

Remember to use WORKDIR /<folder> so that it doesn't conflict with original npm libraries installed.

The folder can be anything but system folders, so that includes using /.

`col-xs-*` not working in Bootstrap 4

col-xs-* have been dropped in Bootstrap 4 in favor of col-*.

Replace col-xs-12 with col-12 and it will work as expected.

Also note col-xs-offset-{n} were replaced by offset-{n} in v4.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

Split an NSString to access one particular piece

Swift 3.0 version

let arr = yourString.components(separatedBy: "/")
let month = arr[0]

Convert a Unicode string to a string in Python (containing extra symbols)

See unicodedata.normalize

title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'

XAMPP Object not found error

First you have to check if FileZilla is running on xampp control panel Than such error can occur You have to stop the FileZilla service from Xampp control panel

Fetching data from MySQL database using PHP, Displaying it in a form for editing

please try these

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "User_name" value= "<?php echo $row['User_name']; ?> "size=10>
Password
<input type="text" name= "User_password" value= "<?php echo $row['User_password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

MySQL error: key specification without a key length

Another excellent way of dealing with this is to create your TEXT field without the unique constraint and add a sibling VARCHAR field that is unique and contains a digest (MD5, SHA1, etc.) of the TEXT field. Calculate and store the digest over the entire TEXT field when you insert or update the TEXT field then you have a uniqueness constraint over the entire TEXT field (rather than some leading portion) that can be searched quickly.

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

gpg decryption fails with no secret key error

When migrating from one machine to another-

  1. Check the gpg version and supported algorithms between the two systems.

    gpg --version

  2. Check the presence of keys on both systems.

    gpg --list-keys

    pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04

    gpg --list-secret-keys

    sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04

Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.

If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.

Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.

gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>

gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key

'React' must be in scope when using JSX react/react-in-jsx-scope?

For those who still don't get the accepted solution :

Add

import React from 'react'
import ReactDOM from 'react-dom'

at the top of the file.

C# importing class into another class doesn't work

If they are separate class files within the same project, then you do not need to have an 'import' statement. Just use the class straight off. If the files are in separate projects, you need to add a reference to the project first before you can use an 'import' statement on it.

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

Can two applications listen to the same port?

If at least one of the remote IPs is already known, static and dedicated to talk only to one of your apps, you may use iptables rule (table nat, chain PREROUTING) to redirect incomming traffic from this address to "shared" local port to any other port where the appropriate application actually listen.

How to iterate over the file in python

You should learn about EAFP vs LBYL.

from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
    if isinstance(infile, basestring):
        infile=open(infile,'r')
    if isinstance(outfile, basestring):
        outfile=open(outfile,'w')
    for lineno, line in enumerate(infile, 1):
        line = line.strip()
         try:
             print >>outfile, int(line,16)
         except ValueError:
             return "Bad value at line %i: %r" % (lineno, line)

if __name__ == "__main__":
    from sys import argv, exit
    exit(main(*argv[1:]))

How to run Rake tasks from within Rake tasks?

If you need the task to behave as a method, how about using an actual method?

task :build => [:some_other_tasks] do
  build
end

task :build_all do
  [:debug, :release].each { |t| build t }
end

def build(type = :debug)
  # ...
end

If you'd rather stick to rake's idioms, here are your possibilities, compiled from past answers:

  • This always executes the task, but it doesn't execute its dependencies:

    Rake::Task["build"].execute
    
  • This one executes the dependencies, but it only executes the task if it has not already been invoked:

    Rake::Task["build"].invoke
    
  • This first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all:

    Rake::Task["build"].reenable
    Rake::Task["build"].invoke
    
  • Note that dependencies already invoked are not automatically re-executed unless they are re-enabled. In Rake >= 10.3.2, you can use the following to re-enable those as well:

    Rake::Task["build"].all_prerequisite_tasks.each(&:reenable)
    

how to compare the Java Byte[] array?

Cause they're not equal, ie: they're different arrays with equal elements inside.

Try using Arrays.equals() or Arrays.deepEquals().

Traverse a list in reverse order in Python

How about without recreating a new list, you can do by indexing:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

OR

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>

String.Format alternative in C++

As already mentioned the C++ way is using stringstreams.

#include <sstream>

string a = "test";
string b = "text.txt";
string c = "text1.txt";

std::stringstream ostr;
ostr << a << " " << b << " > " << c;

Note that you can get the C string from the string stream object like so.

std::string formatted_string = ostr.str();
const char* c_str = formatted_string.c_str();

Java correct way convert/cast object to Double

new Double(object.toString());

But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there.

Note that this is a conversion, not casting.

Get list of a class' instance methods

You actually want TestClass.instance_methods, unless you're interested in what TestClass itself can do.

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]

Or you can call methods (not instance_methods) on the object:

test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]

What's the difference between a null pointer and a void pointer?

Null pointer is a special reserved value of a pointer. A pointer of any type has such a reserved value. Formally, each specific pointer type (int *, char * etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.

Void pointer is a specific pointer type - void * - a pointer that points to some data location in storage, which doesn't have any specific type.

So, once again, null pointer is a value, while void pointer is a type. These concepts are totally different and non-comparable. That essentially means that your question, as stated, is not exactly valid. It is like asking, for example, "What is the difference between a triangle and a car?".

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

What values for checked and selected are false?

There are no values that will cause the checkbox to be unchecked. If the checked attribute exists, the checkbox will be checked regardless of what value you set it to.

_x000D_
_x000D_
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
_x000D_
_x000D_

Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).

Angular2 Material Dialog css, dialog size

With current version of Angular Material (6.4.7) you can use a custom class:

let dialogRef = dialog.open(UserProfileComponent, {
  panelClass: 'my-class'
});

Now put your class somewhere global (haven't been able to make this work elsewhere), e.g. in styles.css:

.my-class .mat-dialog-container{
  height: 400px;
  width: 600px;
  border-radius: 10px;
  background: lightcyan;
  color: #039be5;
}

Done!

How to change the floating label color of TextInputLayout

In my case I added this "app:hintTextAppearance="@color/colorPrimaryDark"in my TextInputLayout widget.

The entity type <type> is not part of the model for the current context

I've seen this error when an existing table in the database doesn't appropriately map to a code first model. Specifically I had a char(1) in the database table and a char in C#. Changing the model to a string resolved the problem.

pgadmin4 : postgresql application server could not be contacted.

I ran into this issue as well. Windows 10. I had older version of pgAdmin 4 (1.6) and 2.0. I guess both are older now.

In any case a complete uninstall of both versions and a reinstall of 2.0 worked.

How to sort findAll Doctrine's method?

I use an alternative to the solution that wrote nifr.

$resultRows = $repository->fetchAll();
uasort($resultRows, function($a, $b){
    if ($a->getProperty() == $b->getProperty()) {
        return 0;
    }
    return ($a->getProperty()< $b->getProperty()) ? -1 : 1;
});

It's quicker than the ORDER BY clause, and without the overhead of the Iterator.

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

Python: avoiding pylint warnings about too many arguments

Python has some nice functional programming tools that are likely to fit your needs well. Check out lambda functions and map. Also, you're using dicts when it seems like you'd be much better served with lists. For the simple example you provided, try this idiom. Note that map would be better and faster but may not fit your needs:

def mysum(d):
   s = 0  
   for x in d:
        s += x
   return s

def mybigfunction():
   d = (x1, x2, x3, x4, x5, x6, x7, x8, x9)
   return mysum(d)

You mentioned having a lot of local variables, but frankly if you're dealing with lists (or tuples), you should use lists and factor out all those local variables in the long run.

How to send email to multiple recipients using python smtplib?

I figured this out a few months back and blogged about it. The summary is:

If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

Efficient way to do batch INSERTS with JDBC

You'll have to benchmark, obviously, but over JDBC issuing multiple inserts will be much faster if you use a PreparedStatement rather than a Statement.

What do 'real', 'user' and 'sys' mean in the output of time(1)?

real: The actual time spent in running the process from start to finish, as if it was measured by a human with a stopwatch

user: The cumulative time spent by all the CPUs during the computation

sys: The cumulative time spent by all the CPUs during system-related tasks such as memory allocation.

Notice that sometimes user + sys might be greater than real, as multiple processors may work in parallel.

How to stop app that node.js express 'npm start'

On MAC OS X(/BSD): you can try to use the lsof (list open files) command

$ sudo lsof -nPi -sTCP:LISTEN

enter image description here

and so

$ kill -9 3320

Set timeout for webClient.DownloadFile()

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

and you can use it just like the base WebClient class.

Static Block in Java

It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.

It is also possible to write non-static initializers, which look even stranger:

public class Foo {
    {
        // This code will be executed before every constructor
        // but after the call to super()
    }

    Foo() {

    }
}

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

How to highlight text using javascript

Fast forward to 2019, Web API now has natively support for highlighting texts:

const selection = document.getSelection();
selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);

And you are good to go! anchorNode is the selection starting node, focusNode is the selection ending node. And, if they are text nodes, offset is the index of the starting and ending character in the respective nodes. Here is the documentation

They even have a live demo

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

Source: CodePath - UI Testing With Espresso

  1. Finally, we need to pull in the Espresso dependencies and set the test runner in our app build.gradle:
// build.gradle
...
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

dependencies {
    ...
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        // Necessary if your app targets Marshmallow (since Espresso
        // hasn't moved to Marshmallow yet)
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test:runner:0.5') {
        // Necessary if your app targets Marshmallow (since the test runner
        // hasn't moved to Marshmallow yet)
        exclude group: 'com.android.support', module: 'support-annotations'
    }
}

I've added that to my gradle file and the warning disappeared.

Also, if you get any other dependency listed as conflicting, such as support-annotations, try excluding it too from the androidTestCompile dependencies.

How to escape indicator characters (i.e. : or - ) in YAML

What also works and is even nicer for long, multiline texts, is putting your text indented on the next line, after a pipe or greater-than sign:

text: >
    Op dit plein stond het hoofdkantoor van de NIROM: Nederlands Indische 
    Radio Omroep

A pipe preserves newlines, a gt-sign turns all the following lines into one long string.

Android translate animation - permanently move View to new position using AnimationListener

Just Do like this

view.animate()
            .translationY(-((root.height - (view.height)) / 2).toFloat())
            .setInterpolator(AccelerateInterpolator()).duration = 1500

Here, view is your View which is animating from its origin position. root is root View of your XML file.

Calculation inside translationY is made for moving your view to the top but keeping it inside the screen, otherwise, it will go partially outside of the screen if you keep its value 0.

How to hide close button in WPF window?

Let the user "close" the window but really just hide it.

In the window's OnClosing event, hide the window if already visible:

    If Me.Visibility = Windows.Visibility.Visible Then
        Me.Visibility = Windows.Visibility.Hidden
        e.Cancel = True
    End If

Each time the Background thread is to be executed, re-show background UI window:

    w.Visibility = Windows.Visibility.Visible
    w.Show()

When terminating execution of program, make sure all windows are/can-be closed:

Private Sub CloseAll()
    If w IsNot Nothing Then
        w.Visibility = Windows.Visibility.Collapsed ' Tell OnClosing to really close
        w.Close()
    End If
End Sub

How do I configure PyCharm to run py.test tests?

Here is how I made it work with pytest 3.7.2 (installed via pip) and pycharms 2017.3:

  1. Go to edit configurations

  1. Add a new run config and select py.test

  1. In the run config details, you need to set target=python and the unnamed field below to tests. It looks like this is the name of your test folder. Not too sure tough. I also recommend the -s argument so that if you debug your tests, the console will behave properly. Without the argument pytest captures the output and makes the debug console buggy.

  1. My tests folder looks like that. This is just below the root of my project (my_project/tests).

  1. My foobar_test.py file: (no imports needed):
def test_foobar():
    print("hello pytest")
    assert True
  1. Run it with the normal run command

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

How do I get the file extension of a file in Java?

Here's a method that handles .tar.gz properly, even in a path with dots in directory names:

private static final String getExtension(final String filename) {
  if (filename == null) return null;
  final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
  final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
  final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
  return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}

afterLastSlash is created to make finding afterLastBackslash quicker since it won't have to search the whole string if there are some slashes in it.

The char[] inside the original String is reused, adding no garbage there, and the JVM will probably notice that afterLastSlash is immediately garbage in order to put it on the stack instead of the heap.

How do I enable logging for Spring Security?

By default Spring Security redirects user to the URL that he originally requested (/Load.do in your case) after login.

You can set always-use-default-target to true to disable this behavior:

 <security:http auto-config="true">

    <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
    <security:form-login login-page="/Load.do"
        default-target-url="/Admin.do?m=loadAdminMain"
        authentication-failure-url="/Load.do?error=true"
        always-use-default-target = "true"
        username-parameter="j_username"
        password-parameter="j_password"
        login-processing-url="/j_spring_security_check"/>
    <security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>

How do I get textual contents from BLOB in Oracle SQL

I struggled with this for a while and implemented the PL/SQL solution, but later realized that in Toad you can simply double click on the results grid cell, and it brings up an editor with contents in text. (i'm on Toad v11)

enter image description here

Good Patterns For VBA Error Handling

Beware the elephant trap:

I saw no mention of this in this discussion. [Access 2010]

How ACCESS/VBA handles errors in CLASS objects is determined by a configurable option:

VBA Code Editor > Tools > Options > General > Error Trapping:

enter image description here

How do I know which version of Javascript I'm using?

Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".

For IE :

alert(@_jscript_version);      //IE

Refer Squeegy's answer for non-IE versions :)

React navigation goBack() and update parent state

I was facing a similar issue, so here is how I solved it by going more into details.

Option one is to navigate back to parent with parameters, just define a callback function in it like this in parent component:

updateData = data => {
  console.log(data);
  alert("come back status: " + data);
  // some other stuff
};

and navigate to the child:

onPress = () => {
  this.props.navigation.navigate("ParentScreen", {
    name: "from parent",
    updateData: this.updateData
  });
};

Now in the child it can be called:

 this.props.navigation.state.params.updateData(status);
 this.props.navigation.goBack();

Option two. In order to get data from any component, as the other answer explained, AsyncStorage can be used either synchronously or not.

Once data is saved it can be used anywhere.

// to get
AsyncStorage.getItem("@item")
  .then(item => {
    item = JSON.parse(item);
    this.setState({ mystate: item });
  })
  .done();
// to set
AsyncStorage.setItem("@item", JSON.stringify(someData));

or either use an async function to make it self-update when it gets new value doing like so.

this.state = { item: this.dataUpdate() };
async function dataUpdate() {
  try {
    let item = await AsyncStorage.getItem("@item");
    return item;
  } catch (e) {
    console.log(e.message);
  }
}

See the AsyncStorage docs for more details.

How to use border with Bootstrap

If you are using Bootstrap 4 and higher try this to put borders around your empty divs use border border-primary here is an example of my code:

<div class="row border border-primary">
        <div class="col border border-primary">logo</div>
        <div class="col border border-primary">navbar</div>
    </div>

Here is the link to the border utility in Bootstrap 4: https://getbootstrap.com/docs/4.2/utilities/borders/

Identifying country by IP address

Amazon's CloudFront content delivery network can now be configured to pass this information through as a header. Given Amazon's size (they're big and stable, not going anywhere) and this is configuration over code (no third-party API to learn or code to maintain), all around believe this to be the best option.

If you do not use AWS CloudFront, I'd look into seeing if your CDN has a similar header option that can be turned on. Usually the large providers are quick to push for feature parity. And if you are not using a CDN, you could put CloudFront in front of your infrastructure and simply set the origin to resolve to whatever you are currently using.

Additionally, it also makes sense to resolve this at the CDN level. Your CDN is already having to figure out geo location to route the user to the nearest content node, might as well pass this information along and not figure it out twice through a third party API (this becomes chokepoint for your app, waiting for a geo location lookup to resolve). No need to do this work twice (and the second time, arguably less resilient [e.g., 3rd party geo lookup]).

https://aws.amazon.com/blogs/aws/enhanced-cloudfront-customization/

Geo-Targeting – CloudFront will detect the user’s country of origin and pass along the county code to you in the CloudFront-Viewer-Country header. You can use this information to customize your responses without having to use URLs that are specific to each country.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had the same in IIS 10.

I fixed it by importing the .pfx file using IIS manager.

Select server root (above the sites-node), click 'Server Certificates' in the right hand pane and import pfx there. Then I could select it from the dropdown when creating ssl binding for a website under sites

xampp MySQL does not start

Try this: really quick + worked for me:

  1. Open Task Manager > Services Tab
  2. Find "mysqlweb" service > right-click it to stop service
  3. Launch Xampp again

ps: excuse image below for different language :)

enter image description here

How to handle notification when app in background in Firebase

Using this code you can get the notification in background/foreground and also put action:

//Data should come in this format from the notification
{
  "to": "/xyz/Notifications",
  "data": {
      "key1": "title notification",
      "key2": "description notification"
  }
}

In-App use this code:

  @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
      String key1Data = remoteMessage.getData().get("key1");
      // use key1Data to according to your need
    }

overlay opaque div over youtube iframe

Is the opaque overlay for aesthetic purposes?

If so, you can use:

#overlay {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 50;
        background: #000;
        pointer-events: none;
        opacity: 0.8;
        color: #fff;
}

'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.

Setting the correct encoding when piping stdout in Python

export PYTHONIOENCODING=utf-8

do the job, but can't set it on python itself ...

what we can do is verify if isn't setting and tell the user to set it before call script with :

if __name__ == '__main__':
    if (sys.stdout.encoding is None):
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
        exit(1)

Update to reply to the comment: the problem just exist when piping to stdout . I tested in Fedora 25 Python 2.7.13

python --version
Python 2.7.13

cat b.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys

print sys.stdout.encoding

running ./b.py

UTF-8

running ./b.py | less

None

Linux: is there a read or recv from socket with timeout?

// works also after bind operation for WINDOWS

DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

byte[] to hex string

I thought I would attempt to compare the speed of each of the methods listed here for the hell of it. I based the speed testing code off this.

The result is that BitConverter+String.Replace seems to be faster than most other simple ways. But the speed can be improved with algorithms like Nathan Moinvaziri's ByteArrayToHexString or Kurt's ToHex.

I also found it interesting that string.Concat and string.Join are much slower than StringBuilder implementations for long strings, but similar for shorter arrays. Probably due to expanding the StringBuilder on the longer strings, so setting the initial size should negate this difference.

  • Took each bit of code from an answer here:
  • BitConvertRep = Answer by Guffa, BitConverter and String.Replace (I'd recommend for most cases)
  • StringBuilder = Answer by Quintin Robinson, foreach char StringBuilder.Append
  • LinqConcat = Answer by Michael Buen, string.Concat of Linq built array
  • LinqJoin = Answer by mloskot, string.Join of Linq built array
  • LinqAgg = Answer by Matthew Whited, IEnumerable.Aggregate with StringBuilder
  • ToHex = Answer by Kurt, sets chars in an array, using byte values to get hex
  • ByteArrayToHexString = Answer by Nathan Moinvaziri, approx same speed as the ToHex above, and is probably easier to read (I'd recommend for speed)
  • ToHexFromTable = Linked in answer by Nathan Moinvaziri, for me this is near the same speed as the above 2 but requires an array of 256 strings to always exist

With: LONG_STRING_LENGTH = 1000 * 1024;

  • BitConvertRep calculation Time Elapsed 27,202 ms (fastest built in/simple)
  • StringBuilder calculation Time Elapsed 75,723 ms (StringBuilder no reallocate)
  • LinqConcat calculation Time Elapsed 182,094 ms
  • LinqJoin calculation Time Elapsed 181,142 ms
  • LinqAgg calculation Time Elapsed 93,087 ms (StringBuilder with reallocating)
  • ToHex calculation Time Elapsed 19,167 ms (fastest)

With: LONG_STRING_LENGTH = 100 * 1024;, Similar results

  • BitConvertReplace calculation Time Elapsed 3431 ms
  • StringBuilder calculation Time Elapsed 8289 ms
  • LinqConcat calculation Time Elapsed 21512 ms
  • LinqJoin calculation Time Elapsed 19433 ms
  • LinqAgg calculation Time Elapsed 9230 ms
  • ToHex calculation Time Elapsed 1976 ms

With: int MANY_STRING_COUNT = 1000; int MANY_STRING_LENGTH = 1024; (Same byte count as first test but in different arrays)

  • BitConvertReplace calculation Time Elapsed 25,680 ms
  • StringBuilder calculation Time Elapsed 78,411 ms
  • LinqConcat calculation Time Elapsed 101,233 ms
  • LinqJoin calculation Time Elapsed 99,311 ms
  • LinqAgg calculation Time Elapsed 84,660 ms
  • ToHex calculation Time Elapsed 18,221 ms

With: int MANY_STRING_COUNT = 2000; int MANY_STRING_LENGTH = 20;

  • BitConvertReplace calculation Time Elapsed 1347 ms
  • StringBuilder calculation Time Elapsed 3234 ms
  • LinqConcat calculation Time Elapsed 5013 ms
  • LinqJoin calculation Time Elapsed 4826 ms
  • LinqAgg calculation Time Elapsed 3589 ms
  • ToHex calculation Time Elapsed 772 ms

Testing code I used:

void Main()
{
    int LONG_STRING_LENGTH = 100 * 1024;
    int MANY_STRING_COUNT = 1024;
    int MANY_STRING_LENGTH = 100;

    var source = GetRandomBytes(LONG_STRING_LENGTH);

    List<byte[]> manyString = new List<byte[]>(MANY_STRING_COUNT);
    for (int i = 0; i < MANY_STRING_COUNT; ++i)
    {
        manyString.Add(GetRandomBytes(MANY_STRING_LENGTH));
    }

    var algorithms = new Dictionary<string,Func<byte[], string>>();
    algorithms["BitConvertReplace"] = BitConv;
    algorithms["StringBuilder"] = StringBuilderTest;
    algorithms["LinqConcat"] = LinqConcat;
    algorithms["LinqJoin"] = LinqJoin;
    algorithms["LinqAgg"] = LinqAgg;
    algorithms["ToHex"] = ToHex;
    algorithms["ByteArrayToHexString"] = ByteArrayToHexString;

    Console.WriteLine(" === Long string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            pair.Value(source);
        });
    }

    Console.WriteLine(" === Many string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            foreach (var str in manyString)
            {
                pair.Value(str);
            }
        });
    }
}

// Define other methods and classes here
static void TimeAction(string description, int iterations, Action func) {
    var watch = new Stopwatch();
    watch.Start();
    for (int i = 0; i < iterations; i++) {
        func();
    }
    watch.Stop();
    Console.Write(description);
    Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}

//static byte[] GetRandomBytes(int count) {
//  var bytes = new byte[count];
//  (new Random()).NextBytes(bytes);
//  return bytes;
//}
static Random rand = new Random();
static byte[] GetRandomBytes(int count) {
    var bytes = new byte[count];
    rand.NextBytes(bytes);
    return bytes;
}


static string BitConv(byte[] data)
{
    return BitConverter.ToString(data).Replace("-", string.Empty);
}
static string StringBuilderTest(byte[] data)
{
    StringBuilder sb = new StringBuilder(data.Length*2);
    foreach (byte b in data)
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}
static string LinqConcat(byte[] data)
{
    return string.Concat(data.Select(b => b.ToString("X2")).ToArray());
}
static string LinqJoin(byte[] data)
{
    return string.Join("",
        data.Select(
            bin => bin.ToString("X2")
            ).ToArray());
}
static string LinqAgg(byte[] data)
{
    return data.Aggregate(new StringBuilder(),
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();
}
static string ToHex(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');
    }

    return new string(c);
}
public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length*2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
        {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
        }

    return Result.ToString();
}

Also another answer with a similar process, I haven't compared our results yet.

How to break long string to multiple lines

If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.

Download Mz-tools

If your string looks like below

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines

enter image description here

How to change Android version and code version number?

Press Ctrl+Alt+Shift+S in android studio or go to File > Project Structure... Select app on left side and select falvors tab on right side on default config change version code , name and etc... enter image description here

How to export the Html Tables data into PDF using Jspdf

Try to put

doc.fromHTML($('#target').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

instead of

doc.fromHTML($('#target').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

How does one check if a table exists in an Android SQLite database?

Although there are already a lot of good answers to this question, I came up with another solution that I think is more simple. Surround your query with a try block and the following catch:

catch (SQLiteException e){
    if (e.getMessage().contains("no such table")){
            Log.e(TAG, "Creating table " + TABLE_NAME + "because it doesn't exist!" );
            // create table
            // re-run query, etc.
    }
}

It worked for me!

How do I run a Java program from the command line on Windows?

Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java

You do not need to compile using separately using javac anymore.

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Response Buffer Limit Exceeded

One other answer to the same error message (this just fixed my problem) is that the System drive was low on disk space. Meaning about 700kb free. Deleting a lot of unused stuff on this really old server and then restarting IIS and the website (probably only IIS was necessary) cause the problem to disappear for me.

I'm sure the other answers are more useful for most people, but for a quick fix, just make sure that the System drive has some free space.

Design Patterns web based applications

I have used the struts framework and find it fairly easy to learn. When using the struts framework each page of your site will have the following items.

1) An action which is used is called every time the HTML page is refreshed. The action should populate the data in the form when the page is first loaded and handles interactions between the web UI and the business layer. If you are using the jsp page to modify a mutable java object a copy of the java object should be stored in the form rather than the original so that the original data doesn't get modified unless the user saves the page.

2) The form which is used to transfer data between the action and the jsp page. This object should consist of a set of getter and setters for attributes that need to be accessible to the jsp file. The form also has a method to validate data before it gets persisted.

3) A jsp page which is used to render the final HTML of the page. The jsp page is a hybrid of HTML and special struts tags used to access and manipulate data in the form. Although struts allows users to insert Java code into jsp files you should be very cautious about doing that because it makes your code more difficult to read. Java code inside jsp files is difficult to debug and can not be unit tested. If you find yourself writing more than 4-5 lines of java code inside a jsp file the code should probably be moved to the action.

angular-cli server - how to specify default port

As far as Angular CLI: 7.1.4, there are two common ways to achieve changing the default port.

No. 1

In the angular.json, add the --port option to serve part and use ng serve to start the server.

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "demos:build",
    "port": 1337
  },
  "configurations": {
    "production": {
      "browserTarget": "demos:build:production"
    }
  }
},

No. 2

In the package.json, add the --port option to ng serve and use npm start to start the server.

  "scripts": {
    "ng": "ng",
    "start": "ng serve --port 8000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }, 

Find a value in an array of objects in Javascript

Are you looking for generic Search(Filter) across the item in the object list without specifying the item key

Input

var productList = [{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
    let flag;
    for(let prop in product){
        flag = false;
        flag = product[prop].toString().indexOf(text) > -1;
        if(flag)
        break;
    }
return flag;
});}

Execute

customFilter(productList, '$9');

enter image description here

Merging arrays with the same keys

I just wrote this function, it should do the trick for you, but it does left join

public function mergePerKey($array1,$array2)
    {
        $mergedArray = [];

        foreach ($array1 as $key => $value) 
        {
            if(isset($array2[$key]))
             {
               $mergedArray[$value] = null;

               continue;
             }
            $mergedArray[$value] = $array2[$key];
        }

        return $mergedArray;
    }

Android: Proper Way to use onBackPressed() with Toast

This is the best way, because if user not back more than two seconds then reset backpressed value.

declare one global variable.

 private boolean backPressToExit = false;

Override onBackPressed Method.

@Override
public void onBackPressed() {

    if (backPressToExit) {
        super.onBackPressed();
        return;
    }
    this.backPressToExit = true;
    Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            backPressToExit = false;
        }
    }, 2000);
}

How do I find a stored procedure containing <text>?

In case you needed schema as well:

SELECT   DISTINCT SCHEMA_NAME(o.schema_id),o.name,[text]
FROM     syscomments AS c
         INNER JOIN sys.objects AS o ON c.id = o.[object_id]
         INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
WHERE    text LIKE '%foo%'
ORDER BY  SCHEMA_NAME(o.schema_id),o.name 

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

Can someone explain __all__ in Python?

From (An Unofficial) Python Reference Wiki:

The public names defined by a module are determined by checking the module's namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character ("_"). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

In my case (using XCode 10.0) nothing worked but this:

File > Project Settings... > Shared Project Settings: > Build System --> Selected "Legacy Build System" instead of the default "New Build System (Default)".

Swift: Sort array of objects alphabetically

*import Foundation
import CoreData


extension Messages {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Messages> {
        return NSFetchRequest<Messages>(entityName: "Messages")
    }

    @NSManaged public var text: String?
    @NSManaged public var date: Date?
    @NSManaged public var friends: Friends?

}

    //here arrMessage is the array you can sort this array as under bellow 

    var arrMessages = [Messages]()

    arrMessages.sort { (arrMessages1, arrMessages2) -> Bool in
               arrMessages1.date! > arrMessages2.date!
    }*

What's the correct way to convert bytes to a hex string in Python 3?

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@