Programs & Examples On #Java bytecode asm

ASM is a Java library used for JVM bytecode manipulation and creation.

PowerShell: Run command from script's directory

If you're calling native apps, you need to worry about [Environment]::CurrentDirectory not about PowerShell's $PWD current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.

In a script, you can do this:

$CWD = [Environment]::CurrentDirectory

Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
##  Your script code calling a native executable
Pop-Location

# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD

There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.

Two notes about the reason why this is not set by PowerShell automatically:

  1. PowerShell can be multi-threaded. You can have multiple Runspaces (see RunspacePool, and the PSThreadJob module) running simultaneously withinin a single process. Each runspace has it's own $PWD present working directory, but there's only one process, and only one Environment.
  2. Even when you're single-threaded, $PWD isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).

If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:

[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Clicking a button within a form causes page refresh

You can try to prevent default handler:

html:

<button ng-click="saveUser($event)">

js:

$scope.saveUser = function (event) {
  event.preventDefault();
  // your code
}

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Google Play on Android 4.0 emulator

  1. Download the gapps package from http://goo.im/gapps
  2. extract GoogleLoginService.apk,GoogleServicesFramework.apk and Vending.apk Go to cmd window type adb shell
    1. on the shell type mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
    2. then press Ctrl+c to exit. cd to the directory where apks has been extracted,
    3. type adb push <appname>.apk /system/app
    4. then type adb reboot

Private pages for a private Github repo

The page.github.com does mention:

Github Pages are hosted free and easily published through our site,

Without ever mentioning access control.

The GitHub page help doesn't mention any ACL either.
They are best managed in a gh-pages branch, and can be managed in their own submodule.
But again, without any restriction in term of visibility once published by GitHub.

How can I update my ADT in Eclipse?

You have updated the android sdk but not updated the adt to match with it.

You can update the adt from here

You might need to update the software source for your adt update

Go to eclipse > help > Check for updates.

It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:

It will list the updates available- which should ideally be adt 20.xx

Eclipse will restart and hopefully everything should work fine for you.

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

SQLite DateTime comparison

Right now i am developing using System.Data.SQlite NuGet package (version 1.0.109.2). Which using SQLite version 3.24.0.

And this works for me.

SELECT * FROM tables WHERE datetime 
BETWEEN '2018-10-01 00:00:00' AND '2018-10-10 23:59:59';

I don't net to use the datetime() function. Perhaps they already updated the SQL query on that SQLite version.

Can a PDF file's print dialog be opened with Javascript?

I use named action instead of javascript because javascript often is disabled, and if it isn't it gives a warning.

My web application creates a postscript file that then is converted with ghostscript to a pdf. I want it to print automatically because the user has already clicked on print inside my application. With the information about named actions from @DSimon above, I researched how to solve this. It all boils down to insert the string /Type /Action /S /Named /N /Print at the right place in the pdf.

I was thinking of writing a small utility, but it has to parse the pdf to find the root node, insert /OpenAction with a reference an object with the action, and recalculate the byte-offsets in xref.

But then I found out about pdfmark which is an extension to postscript to express, in postscript syntax, idioms that are converted to pdf by Adobes distiller or by ghostscript.

Since I'm already using ghostscript, all I have to do is append the following to the end of my postscript file:

%AUTOPRINT
[ /_objdef {PrintAction} /type /dict /OBJ pdfmark
[ {PrintAction} << /Type /Action /S /Named /N /Print >> /PUT pdfmark
[ {Catalog} << /OpenAction {PrintAction} >> /PUT pdfmark

and ghostscript will create the action, link it, and calculate the xref offsets. (In postscript % is a comment and PrintAction is my name for the object)

By looking at the PDF I see that it has created this:

1 0 obj
<</Type /Catalog /Pages 3 0 R
/OpenAction  9 0 R
/Metadata 10 0 R
>>
endobj

9 0 obj
<</S/Named
/Type/Action
/N/Print>>endobj

1 0 is object 1, revision 0, and 9 0 is object 9, revision 0. In the pdf-trailer is says that it is object 1 that is the root node. As you can see there is a reference from object 1, /OpenAction to run object 9 revision 0.

With ghostscript it's possible to convert a pdf to postscript (pdf2ps), append the text above, and convert it back to pdf with ps2pdf. It should be noted that meta-information about the pdf is lost in this conversion. I haven't searched more into this.

JFrame background image

This is a simple example for adding the background image in a JFrame:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame()
    {
        setTitle("Background Color for JFrame");
        setSize(400,400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        /*
        One way
        -----------------
        setLayout(new BorderLayout());
        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
        add(background);
        background.setLayout(new FlowLayout());
        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");
        background.add(l1);
        background.add(b1);
        */

        // Another way
        setLayout(new BorderLayout());
        setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
        setLayout(new FlowLayout());
        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");
        add(l1);
        add(b1);
        // Just for refresh :) Not optional!
        setSize(399,399);
        setSize(400,400);
    }

    public static void main(String args[])
    {
        new BackgroundImageJFrame();
    }
} 
  • Click here for more info

Java naming convention for static final variables

The dialog on this seems to be the antithesis of the conversation on naming interface and abstract classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final.

Abstract and Interface

When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class or interface with any identifying information that would indicate it is anything other than a class.

public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}

The developer is said not to need to know that the above classes are abstract or an interface.

Static Final

My personal preference and belief is that we should follow similar logic when referring to static final variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.

Question of Intention

We should ask ourselves what is the function of static final in our own context. Here are three examples of how static final may be used in different contexts:

public class ChatMessage {
    //Used like a private variable
    private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);

    //Used like an Enum
    public class Error {
        public static final int Success = 0;
        public static final int TooLong = 1;
        public static final int IllegalCharacters = 2;
    }

    //Used to define some static, constant, publicly visible property
    public static final int MAX_SIZE = Integer.MAX_VALUE;
}

Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.


Purpose: Private Variable

In the case of the Logger example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected or package visibility, its usage is the same:

public void send(final String message) {
    logger.info("Sending the following message: '" + message + "'.");
    //Send the message
}

Here, we don't care that logger is a static final member variable. It could simply be a final instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.

public class ChatMessage {
    private final Logger logger = LoggerFactory.getLogger(getClass());
}

You wouldn't name it LOGGER in this scenario, so why should you name it all uppercase if it was static final? Its context, or intention, is the same in both circumstances.

Note: I reversed my position on package visibility because it is more like a form of public access, restricted to package level.


Purpose: Enum

Now you might say, why are you using static final integers as an enum? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);

    private final int value;

    private Error(final int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Error fromValue(final int value) {
        switch (value) {
        case 0:
            return Error.Success;
        case 1:
            return Error.TooLong;
        case 2:
            return Error.IllegalCharacters;
        default:
            throw new IllegalArgumentException("Unknown Error value.");
        }
    }
}

There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int and int->enum. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int, short, or byte could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum vs static final int involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.

The bottom line is this, sometimes static final int will be used as an enum style structure.

If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum, the accepted style says that we don't do the following:

public enum Error {
    SUCCESS(0),
    TOOLONG(1),
    ILLEGALCHARACTERS(2);
}

Instead, we do the following:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);
}

If your static final block of integers serves as a loose enum, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.


Purpose: Static, Constant, Public Property

This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof(), but there are times when it is important to know how many bytes a data structure will occupy.

For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:

File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]

This file contains a list of MyObject objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject objects, but without knowing the size of each MyObject you have no way of knowing which bytes belong to each MyObject. So, you define the size of MyObject on MyObject:

public class MyObject {
    private final long id; //It has a 64bit identifier (+8 bytes)
    private final int value; //It has a 32bit integer value (+4 bytes)
    private final boolean special; //Is it special? (+1 byte)

    public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}

The MyObject data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject objects follow in the file:

int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;

This seems to be the typical usage case and argument for all uppercase static final constants, and I agree that in this context, all uppercase makes sense. Here's why:

Java doesn't have a struct class like the C language, but a struct is simply a class with all public members and no constructor. It's simply a data structure. So, you can declare a class in struct like fashion:

public class MyFile {
    public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!

    //The struct
    public static class MyFileHeader {
        public int fileType = MYFM;
        public int version = 0;
        public int dataSize = 0;
        public int checksumSize = 0;
    }
}

Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer or all 4 variables as constructor arguments. That said, accessing (setting in this case) this structs members would look something like:

MyFileHeader header = new MyFileHeader();
header.fileType     = buffer.getInt();
header.version      = buffer.getInt();
header.dataSize     = buffer.getInt();
header.checksumSize = buffer.getInt();

These aren't static or final, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.

Note: Even in this case, if a developer attempted to set a final variable, they would be met with either an IDE or compiler error.


Summary

In conclusion, the convention you choose for static final variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:

Methodology 1: Evaluate Context and Intention [highly subjective; logical]

  • If it's a private variable that should be indistinguishable from a private instance variable, then name them the same. all lowercase
  • If it's intention is to serve as a type of loose enum style block of static values, then name it as you would an enum. pascal case: initial-cap each word
  • If it's intention is to define some publicly accessible, constant, and static property, then let it stand out by making it all uppercase

Methodology 2: Private vs Public [objective; logical]

Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.

  • If it's private or protected then it should be all lowercase.
  • If it's public or package then it should be all uppercase.

Conclusion

This is how I view the naming convention of static final variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.

However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.

(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)

Right Align button in horizontal LinearLayout

I know this is old but here is another one in a Linear Layout would be:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">

<TextView
    android:id="@+id/lblExpenseCancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cancel"
    android:textColor="#404040"
    android:layout_marginLeft="10dp"
    android:textSize="20sp"
    android:layout_marginTop="9dp" />

<Button
    android:id="@+id/btnAddExpense"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:background="@drawable/stitch_button"
    android:layout_marginLeft="10dp"
    android:text="@string/add"
    android:layout_gravity="center_vertical|bottom|right|top"
    android:layout_marginRight="15dp" />

Please note the layout_gravity as opposed to just gravity.

HTML anchor tag with Javascript onclick event

If your onclick function returns false the default browser behaviour is cancelled. As such:

<a href='http://www.google.com' onclick='return check()'>check</a>

<script type='text/javascript'>

function check()
{
    return false;
}

</script>

Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

Installation of SQL Server Business Intelligence Development Studio

This worked for me:

Start /wait setup.exe /qb  ADDLOCAL=SQL_DTS,Client_Components,Connectivity,SQL_Tools90,SQL_WarehouseDevWorkbench,SQLXML,Tools_Legacy,SQL_Documentation,SQL_BooksOnline

Based off this TechNet Article:

https://technet.microsoft.com/en-us/library/ms144259(v=sql.90).aspx

Reading Properties file in Java

Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }

Note the instantiating of the file input stream in try-with-resources block. Since a FileInputStream is autocloseable, it will be automatically closed after the try-with-resources block is exited. If you want to use a simple try block, you must explicitly close it using fis.close(); in the finally block.

Rownum in postgresql

I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:

select row_number() over() as id, t.*
from information_schema.tables t;

Rounding to two decimal places in Python 2.7?

When we use the round() function, it will not give correct values.

you can check it using, round (2.735) and round(2.725)

please use

import math
num = input('Enter a number')
print(math.ceil(num*100)/100)

Text in a flex container doesn't wrap in IE11

As Tyler has suggested in one of the comments here, using

max-width: 100%;

on the child may work (worked for me). Using align-self: stretch only works if you aren't using align-items: center (which I did). width: 100% only works if you haven't multiple childs inside your flexbox which you want to show side by side.

How to compare files from two different branches?

If you want to make a diff against current branch you can ommit it and use:

git diff $BRANCH -- path/to/file

this way it will diff from current branch to the referenced branch ($BRANCH).

Spring Boot, Spring Data JPA with multiple DataSources

here is my solution. base on spring-boot.1.2.5.RELEASE.

application.properties

first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
first.datasource.username=
first.datasource.password=
first.datasource.validation-query=select 1

second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
second.datasource.username=
second.datasource.password=
second.datasource.validation-query=select 1

DataSourceConfig.java

@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="first.datasource")
    public DataSource firstDataSource() {
        DataSource ds =  DataSourceBuilder.create().build();
        return ds;
    }

    @Bean
    @ConfigurationProperties(prefix="second.datasource")
    public DataSource secondDataSource() {
        DataSource ds =  DataSourceBuilder.create().build();
        return ds;
    }
}

Extreme wait-time when taking a SQL Server database offline

To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.

How to get an Android WakeLock to work?

Do you have the required permission set in your Manifest?

<uses-permission android:name="android.permission.WAKE_LOCK" />

Render a string in HTML and preserve spaces and linebreaks

Wrap the description in a textarea element.

JSON post to Spring Controller

Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.

How can I add a class to a DOM element in JavaScript?

var newItem = document.createElement('div');
newItem.style = ('background-color:red'); 
newItem.className = ('new_class');
newItem.innerHTML = ('<img src="./profitly_files/TimCover1_bigger.jpg" width=50 height=50> some long text with ticker $DDSSD');
var list = document.getElementById('x-auto-1');
list.insertBefore(newItem, list.childNodes[0]);

"Application tried to present modally an active controller"?

In my case, I was presenting the rootViewController of an UINavigationController when I was supposed to present the UINavigationController itself.

align an image and some text on the same line without using div width?

I built on the last answer and used display:table for an outer div, and display:table-cell for inner divs.

This was the only thing that worked for me using CSS.

Update query PHP MySQL

you must write single quotes then double quotes then dot before name of field and after like that

mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

How to call a View Controller programmatically?

You need to instantiate the view controller from the storyboard and then show it:

ViewControllerInfo* infoController = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerInfo"];
[self.navigationController pushViewController:infoController animated:YES];

This example assumes that you have a navigation controller in order to return to the previous view. You can of course also use presentViewController:animated:completion:. The main point is to have your storyboard instantiate your target view controller using the target view controller's ID.

How to change the interval time on bootstrap carousel?

The best way to get rid on it is adding or modifying the data-interval attribute like this:

<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">

It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.

By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.

<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

removing the scope tag in pom.xml for junit worked..

Nuget connection attempt failed "Unable to load the service index for source"

I was getting the same error while trying to browse the NuGet Package, to resolve the same followed below step

1- go to %appdata%\NuGet\NuGet.config

2- Verify the urls mentioned in that config

3- Remove the url which is not required

4- Restart visual studio and check

Bootstrap change carousel height

From Bootstrap 4

.carousel-item{
    height: 200px;
} 
.carousel-item img{
    height: 200px;
}

java.net.SocketException: Software caused connection abort: recv failed

The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.

How to determine a Python variable's type?

Just do not do it. Asking for something's type is wrong in itself. Instead use polymorphism. Find or if necessary define by yourself the method that does what you want for any possible type of input and just call it without asking about anything. If you need to work with built-in types or types defined by a third-party library, you can always inherit from them and use your own derivatives instead. Or you can wrap them inside your own class. This is the object-oriented way to resolve such problems.

If you insist on checking exact type and placing some dirty ifs here and there, you can use __class__ property or type function to do it, but soon you will find yourself updating all these ifs with additional cases every two or three commits. Doing it the OO way prevents that and lets you only define a new class for a new type of input instead.

Output data from all columns in a dataframe in pandas

There is too much data to be displayed on the screen, therefore a summary is displayed instead.

If you want to output the data anyway (it won't probably fit on a screen and does not look very well):

print paramdata.values

converts the dataframe to its numpy-array matrix representation.

paramdata.columns

stores the respective column names and

paramdata.index

stores the respective index (row names).

How to strip all whitespace from string

Try a regex with re.sub. You can search for all whitespace and replace with an empty string.

\s in your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.

How to source virtualenv activate in a Bash script

Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

How to remove ASP.Net MVC Default HTTP Headers?

As shown on Removing standard server headers on Windows Azure Web Sites page, you can remove headers with the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
      </customHeaders>
    </httpProtocol>
    <security>
      <requestFiltering removeServerHeader="true"/>
    </security>
  </system.webServer>
  <system.web>
    <httpRuntime enableVersionHeader="false" />
  </system.web>
</configuration>

This removes the Server header, and the X- headers.

This worked locally in my tests in Visual Studio 2015.

Running Facebook application on localhost

You need to setup your app to run over https for localhost

You can follow steps given in this to setup HTTPS on ubuntu

https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-12-04

You need to do following steps:

install apache (if you do not have)

sudo apt-get install apache2

Step One—Activate the SSL Module

sudo a2enmod ssl
sudo service apache2 restart

Step Two—Create a New Directory

sudo mkdir /etc/apache2/ssl

Step Three—Create a Self Signed SSL Certificate

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache/ssl/apache.key -out /etc/apache2/ssl/apache.crt

With this command, we will be both creating the self-signed SSL certificate and the server key that protects it, and placing both of them into the new directory. The most important line is "Common Name". Enter your official domain name here or, if you don't have one yet, your site's IP address.

Common Name (e.g. server FQDN or YOUR name) []:example.com or localhost

Step Four—Set Up the Certificate

sudo vim /etc/apache2/sites-available/default-ssl

Find following lines and edit those with your settings

ServerName localhost or example.com

SSLEngine on SSLCertificateFile /etc/apache2/ssl/apache.crt

SSLCertificateKeyFile /etc/apache2/ssl/apache.key

Step Five—Activate the New Virtual Host

sudo a2ensite default-ssl
sudo service apache2 reload

Multi-threading in VBA

Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.

INFO: Descriptions and Workings of OLE Threading Models

Add an element to an array in Swift

Use += and + operators :

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

How to stop the Timer in android?

It says timer() is not available on android? You might find this article useful.

http://developer.android.com/resources/articles/timed-ui-updates.html


I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:

schedule(TimerTask task, Date when) // Schedule a task for single execution.

Or you cancel it after the first execution:

cancel()  // Cancels the Timer and all scheduled tasks.

http://developer.android.com/reference/java/util/Timer.html

How to implement debounce in Vue2?

Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this. https://www.npmjs.com/package/vue-lazy-input

It applies to @input and v-model, supports custom components and DOM elements, debounce and throttle.

_x000D_
_x000D_
Vue.use(VueLazyInput)_x000D_
  new Vue({_x000D_
    el: '#app', _x000D_
    data() {_x000D_
      return {_x000D_
        val: 42_x000D_
      }_x000D_
    },_x000D_
    methods:{_x000D_
      onLazyInput(e){_x000D_
        console.log(e.target.value)_x000D_
      }_x000D_
    }_x000D_
  })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->_x000D_
<script src="https://unpkg.com/vue-lazy-input@latest"></script> _x000D_
_x000D_
<div id="app">_x000D_
  <input type="range" v-model="val" @input="onLazyInput" v-lazy-input /> {{val}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

Handle Button click inside a row in RecyclerView

Just put an override method named getItemId Get it by right click>generate>override methods>getItemId Put this method in the Adapter class

How to implement authenticated routes in React Router 4?

I was also looking for some answer. Here all answers are quite good, but none of them give answers how we can use it if user starts application after opening it back. (I meant to say using cookie together).

No need to create even different privateRoute Component. Below is my code

    import React, { Component }  from 'react';
    import { Route, Switch, BrowserRouter, Redirect } from 'react-router-dom';
    import { Provider } from 'react-redux';
    import store from './stores';
    import requireAuth from './components/authentication/authComponent'
    import SearchComponent from './components/search/searchComponent'
    import LoginComponent from './components/login/loginComponent'
    import ExampleContainer from './containers/ExampleContainer'
    class App extends Component {
    state = {
     auth: true
    }


   componentDidMount() {
     if ( ! Cookies.get('auth')) {
       this.setState({auth:false });
     }
    }
    render() {
     return (
      <Provider store={store}>
       <BrowserRouter>
        <Switch>
         <Route exact path="/searchComponent" component={requireAuth(SearchComponent)} />
         <Route exact path="/login" component={LoginComponent} />
         <Route exact path="/" component={requireAuth(ExampleContainer)} />
         {!this.state.auth &&  <Redirect push to="/login"/> }
        </Switch>
       </BrowserRouter>
      </Provider>);
      }
     }
    }
    export default App;

And here is authComponent

import React  from 'react';
import { withRouter } from 'react-router';
import * as Cookie from "js-cookie";
export default function requireAuth(Component) {
class AuthenticatedComponent extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   auth: Cookie.get('auth')
  }
 }
 componentDidMount() {
  this.checkAuth();
 }
 checkAuth() {
  const location = this.props.location;
  const redirect = location.pathname + location.search;
  if ( ! Cookie.get('auth')) {
   this.props.history.push(`/login?redirect=${redirect}`);
  }
 }
render() {
  return Cookie.get('auth')
   ? <Component { ...this.props } />
   : null;
  }
 }
 return  withRouter(AuthenticatedComponent)
}

Below I have written blog, you can get more depth explanation there as well.

Create Protected routes in ReactJS

Using column alias in WHERE clause of MySQL query produces an error

You can use SUBSTRING(locations.raw,-6,4) for where conditon

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
 'australia'
)
)

C++ getters/setters coding style

Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:

class Foo {
    public:
        const std::string& getName() const {return name_;}
    private:
        const std::string& name_;
};

Note that if you were to change getName() to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)

how to add button click event in android studio

public class EditProfile extends AppCompatActivity {

    Button searchBtn;
    EditText userName_editText;
    EditText password_editText;
    EditText dob_editText;
    RadioGroup genderRadioGroup;
    RadioButton genderRadioBtn;
    Button editBtn;
    Button deleteBtn;
    Intent intent;
    DBHandler dbHandler;

    public static final String USERID_EDITPROFILE = "userID";

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

        searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
        userName_editText = (EditText)findViewById(R.id.editprof_userName);
        password_editText = (EditText)findViewById(R.id.editprof_password);
        dob_editText = (EditText)findViewById(R.id.editprof_dob);
        genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
        editBtn = (Button)findViewById(R.id.editprof_editbtn);
        deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
        intent = getIntent();


        dbHandler = new DBHandler(EditProfile.this);

        setUserDetails();

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = userName_editText.getText().toString();

                if(username == null){
                    Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
                }
                else{
                    UserProfile.Users users = dbHandler.readAllInfor(username);

                    if(users == null){
                        Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        dbHandler.deleteInfo(username);
                        Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
                        startActivity(redirectintent_home);
                    }
                }
            }
        });

        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String userID_String = intent.getStringExtra(Home.USERID);
                if(userID_String == null){
                    Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
                    Intent redirectintent_home =  new Intent(getApplicationContext(),Home.class);
                    startActivity(redirectintent_home);
                }
                int userID = Integer.parseInt(userID_String);

                String username = userName_editText.getText().toString();
                String password = password_editText.getText().toString();
                String dob = dob_editText.getText().toString();
                int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
                genderRadioBtn = (RadioButton)findViewById(selectedGender);
                String gender = genderRadioBtn.getText().toString();

                UserProfile.Users users = UserProfile.getProfile().getUser();
                users.setUsername(username);
                users.setPassword(password);
                users.setDob(dob);
                users.setGender(gender);
                users.setId(userID);

                dbHandler.updateInfor(users);
                Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
                Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
                startActivity(redirectintent_home);
            }
        });

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String username = userName_editText.getText().toString();
               if (username == null){
                   Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
               }
               else{
                   UserProfile.Users users_search = dbHandler.readAllInfor(username);


                   if(users_search == null){
                       Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
                   }
                   else{
                       userName_editText.setText(users_search.getUsername());
                       password_editText.setText(users_search.getPassword());
                       dob_editText.setText(users_search.getDob());
                       int id = users_search.getId();
                       Intent redirectintent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
                       redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
                       startActivity(redirectintent);
                   }
               }
            }
        });


    }

    public void setUserDetails(){

        String userID_String = intent.getStringExtra(Home.USERID);
        if(userID_String == null){
            Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
            Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
            startActivity(redirectintent_home);
        }
        int userID = Integer.parseInt(userID_String);
        UserProfile.Users users = dbHandler.readAllInfor(userID);
        userName_editText.setText(users.getUsername());
        password_editText.setText(users.getPassword());
        dob_editText.setText(users.getDob());
    }
}

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

How can I break from a try/catch block without throwing an exception in Java

In this sample in catch block i change the value of counter and it will break while block:

class TestBreak {
    public static void main(String[] a) {
        int counter = 0;

        while(counter<5) {
            try {
                counter++;
                int x = counter/0;
            }
            catch(Exception e) {
                counter = 1000;    
            }
        }
    }
}k

Purge or recreate a Ruby on Rails database

Just issue the sequence of the steps: drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:

rake db:drop db:create db:migrate db:seed

Since the default environment for rake is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:

RAILS_ENV=test rake db:drop db:create db:migrate

In most cases the test database is being sowed during the test procedures, so db:seed task action isn't required to be passed. Otherwise, you shall to prepare the database:

rake db:test:prepare

or

RAILS_ENV=test rake db:seed

Additionally, to use the recreate task you can add into Rakefile the following code:

namespace :db do
   task :recreate => [ :drop, :create, :migrate ] do
      if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
         Rake::Task[ 'db:seed' ].invoke
      end
   end
end

Then issue:

rake db:recreate

How to call two methods on button's onclick method in HTML or JavaScript?

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" />
    
  2. Or, call second function at the end of first function:

       function func1(){
         //--- some logic
         func2();
       }
    
       function func2(){
        //--- some logic
       }
    

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" />
    

How do I create a list of random numbers without duplicates?

From the CLI in win xp:

python -c "import random; print(sorted(set([random.randint(6,49) for i in range(7)]))[:6])"

In Canada we have the 6/49 Lotto. I just wrap the above code in lotto.bat and run C:\home\lotto.bat or just C:\home\lotto.

Because random.randint often repeats a number, I use set with range(7) and then shorten it to a length of 6.

Occasionally if a number repeats more than 2 times the resulting list length will be less than 6.

EDIT: However, random.sample(range(6,49),6) is the correct way to go.

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files

GetPrivateProfileString

Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

[Application]
UseLiveData=1
;coke=zero
pepsi=diet   ;gag
#stackoverflow=splotchy

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

Java8: sum values from specific field of the objects in a list

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

OpenCV Python rotate image by X degrees around specific point

def rotate(image, angle, center = None, scale = 1.0):
    (h, w) = image.shape[:2]

    if center is None:
        center = (w / 2, h / 2)

    # Perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, M, (w, h))

    return rotated

Python Variable Declaration

This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:

variable_name: type_name

or this:

variable_name # type: shinyType

So in your case(if you have a CustomObject class defined), you can do:

customObj: CustomObject

See this or that for more info.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

ORA-28000: the account is locked error getting frequently

Way to unlock the user :

$ sqlplus  /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;

and open new terminal

SQL > sqlplus / as sysdba
connected
SQL > conn username/password  //which username u gave before unlock
  • it will ask new password:password
  • it will ask re-type password:password
  • press enter u will get loggedin

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

ObjectiveC Parse Integer from String

I really don't know what was so hard about this question, but I managed to do it this way:

[myStringContainingInt intValue];

It should be noted that you can also do:

myStringContainingInt.intValue;

Bootstrap 3 collapsed menu doesn't close on click

I did

$(".navbar-toggle").click(function(event) {
    $(".navbar-collapse").toggle('in');
});

Markdown `native` text alignment

native markdown doesn't support text alignment without html + css.

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

What is the difference between `sorted(list)` vs `list.sort()`?

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

How can I dynamically add items to a Java array?

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

A bit similar to the PHP behaviour is this:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

ESLint - "window" is not defined. How to allow global variables in package.json

Add .eslintrc in the project root.

{
  "globals": {
    "document": true,
    "foo": true,
    "window": true
  }
}

Call a function after previous function is complete

Or you can trigger a custom event when one function completes, then bind it to the document:

function a() {
    // first function code here
    $(document).trigger('function_a_complete');
}

function b() {
    // second function code here
}

$(document).bind('function_a_complete', b);

Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.

How to jump to top of browser page

Pure Javascript solution

theId.onclick = () => window.scrollTo({top: 0})

If you want smooth scrolling

theId.onclick = () => window.scrollTo({ top: 0, behavior: `smooth` })

How to sort List of objects by some property

In java8+ this can be written in single line as follows:

collectionObjec.sort(comparator_lamda) or comparator.comparing(CollectionType::getterOfProperty)

code:

ListOfActiveAlarmObj.sort((a,b->a.getTimeStarted().compareTo(b.getTimeStarted())))
 

or

ListOfActiveAlarmObj.sort(Comparator.comparing(ActiveAlarm::getTimeStarted))

How to determine the last Row used in VBA including blank spaces in between

Better:

if cells(i,1)="" then 
nextEmpty=i: 
exit for

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

Can I map a hostname *and* a port with /etc/hosts?

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How do I write a Windows batch script to copy the newest file from a directory?

This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.

Obviously, replace new_file_loc with whatever your new file location will be.

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done

Count number of rows by group using dplyr

There's a special function n() in dplyr to count rows (potentially within groups):

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

But dplyr also offers a handy count function which does exactly the same with less typing:

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

Minimal web server using netcat

Donno how or why but i manage to find this around and it works for me, i had the problem I wanted to return the result of executing a bash

$ while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; sh test; } | nc -l 8080; done

NOTE: This command was taken from: http://www.razvantudorica.com/08/web-server-in-one-line-of-bash

this executes bash script test and return the result to a browser client connecting to the server running this command on port 8080

My script does this ATM

$ nano test

#!/bin/bash

echo "************PRINT SOME TEXT***************\n"
echo "Hello World!!!"
echo "\n"

echo "Resources:"
vmstat -S M
echo "\n"

echo "Addresses:"
echo "$(ifconfig)"
echo "\n"


echo "$(gpio readall)"

and my web browser is showing

************PRINT SOME TEXT***************

Hello World!!!


Resources:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0      0    314     18     78    0    0     2     1  306   31  0  0 100  0


Addresses:
eth0      Link encap:Ethernet  HWaddr b8:27:eb:86:e8:c5  
          inet addr:192.168.1.83  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:27734 errors:0 dropped:0 overruns:0 frame:0
          TX packets:26393 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1924720 (1.8 MiB)  TX bytes:3841998 (3.6 MiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)


GPIOs:
+----------+-Rev2-+------+--------+------+-------+
| wiringPi | GPIO | Phys | Name   | Mode | Value |
+----------+------+------+--------+------+-------+
|      0   |  17  |  11  | GPIO 0 | IN   | Low   |
|      1   |  18  |  12  | GPIO 1 | IN   | Low   |
|      2   |  27  |  13  | GPIO 2 | IN   | Low   |
|      3   |  22  |  15  | GPIO 3 | IN   | Low   |
|      4   |  23  |  16  | GPIO 4 | IN   | Low   |
|      5   |  24  |  18  | GPIO 5 | IN   | Low   |
|      6   |  25  |  22  | GPIO 6 | IN   | Low   |
|      7   |   4  |   7  | GPIO 7 | IN   | Low   |
|      8   |   2  |   3  | SDA    | IN   | High  |
|      9   |   3  |   5  | SCL    | IN   | High  |
|     10   |   8  |  24  | CE0    | IN   | Low   |
|     11   |   7  |  26  | CE1    | IN   | Low   |
|     12   |  10  |  19  | MOSI   | IN   | Low   |
|     13   |   9  |  21  | MISO   | IN   | Low   |
|     14   |  11  |  23  | SCLK   | IN   | Low   |
|     15   |  14  |   8  | TxD    | ALT0 | High  |
|     16   |  15  |  10  | RxD    | ALT0 | High  |
|     17   |  28  |   3  | GPIO 8 | ALT2 | Low   |
|     18   |  29  |   4  | GPIO 9 | ALT2 | Low   |
|     19   |  30  |   5  | GPIO10 | ALT2 | Low   |
|     20   |  31  |   6  | GPIO11 | ALT2 | Low   |
+----------+------+------+--------+------+-------+

simply amazing!

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _claim;

    public ClaimAuthorizeAttribute(string Claim)
    {
        _claim = Claim;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
        {
            return;
        }

        context.Result = new ForbidResult();
    }
}

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

How do I update/upsert a document in Mongoose?

I needed to update/upsert a document into one collection, what I did was to create a new object literal like this:

notificationObject = {
    user_id: user.user_id,
    feed: {
        feed_id: feed.feed_id,
        channel_id: feed.channel_id,
        feed_title: ''
    }
};

composed from data that I get from somewhere else in my database and then call update on the Model

Notification.update(notificationObject, notificationObject, {upsert: true}, function(err, num, n){
    if(err){
        throw err;
    }
    console.log(num, n);
});

this is the ouput that I get after running the script for the first time:

1 { updatedExisting: false,
    upserted: 5289267a861b659b6a00c638,
    n: 1,
    connectionId: 11,
    err: null,
    ok: 1 }

And this is the output when I run the script for the second time:

1 { updatedExisting: true, n: 1, connectionId: 18, err: null, ok: 1 }

I'm using mongoose version 3.6.16

How do I print the elements of a C++ vector in GDB?

A little late to the party, so mostly a reminder to me next time I do this search!

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].

YouTube embedded video: set different thumbnail

Just copy and paste the code in HTML file. and enjoy the happy coding. Using Youtube api to manage the thumbnail of youtube embedded video.

<!DOCTYPE html>
<html>
<body>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: 'M7lc1UVf-VE',
                events: {
                    'onReady': onPlayerReady,
                }
            });
        }

        function onPlayerReady(event) {
            $('#play_vid').click(function() {
                event.target.playVideo();
            });
        }

        $(document).ready(function() {
            $('#player').hide();
            $('#play_vid').click(function() {
                $('#player').show();
                $('#play_vid').hide();
            });
        });
    </script>

    <div id="player"></div>
    <img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

How to replace a string in an existing file in Perl?

Anything wrong with a one-liner?

$ perl -pi.bak -e 's/blue/red/g' *_classification.dat

Explanation

  • -p processes, then prints <> line by line
  • -i activates in-place editing. Files are backed up using the .bak extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line

How to print GETDATE() in SQL Server with milliseconds in time?

Create a function with return format yyyy-mm-hh hh:mi:ss.sss

create function fn_retornaFecha (@i_fecha datetime)
returns varchar(23)
as
begin
declare 
@w_fecha varchar(23),
@w_anio  varchar(4),
@w_mes   varchar(2),
@w_dia   varchar(2),
@w_hh    varchar(2),
@w_nn    varchar(2),
@w_ss    varchar(2),
@w_sss   varchar(3)

select @w_fecha = null

if ltrim(rtrim(@i_fecha)) is not null 
begin
   select
   @w_anio = replicate('0',4-char_length( convert(varchar(4), year(@i_fecha)) )) + convert(varchar(4), year(@i_fecha)),
   @w_mes  = replicate('0',2-char_length( convert(varchar(2),month(@i_fecha)) )) + convert(varchar(2),month(@i_fecha)),
   @w_dia  = replicate('0',2-char_length( convert(varchar(2),  day(@i_fecha)) )) + convert(varchar(2),  day(@i_fecha))  ,
   @w_hh   = replicate('0',2-char_length( convert(varchar(2),datepart( hh, @i_fecha ) ) )) + convert(varchar(2),datepart( hh, @i_fecha ) ),
   @w_nn   = replicate('0',2-char_length( convert(varchar(2),datepart( mi, @i_fecha ) ) )) + convert(varchar(2),datepart( mi, @i_fecha ) ),
   @w_ss   = replicate('0',2-char_length( convert(varchar(2),datepart( ss, @i_fecha ) ) )) + convert(varchar(2),datepart( ss, @i_fecha ) ),
   @w_sss  = convert(varchar(3),datepart( ms, @i_fecha ) ) + replicate('0',3-DATALENGTH( convert(varchar(3),datepart( ms, @i_fecha ) )  ))


   select @w_fecha = @w_anio + '-' + @w_mes + '-' + @w_dia + ' ' + @w_hh + ':' + @w_nn + ':' + @w_ss + '.' + @w_sss
end

return @w_fecha

end
go

Example

select fn_retornaFecha(getdate())

and the result is: 2016-12-21 10:12:50.123

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

Where do I find some good examples for DDD?

This is a good example based on domain driven design and explains why it is important to have separate domain layer.
Microsoft spain - DDD N Layer Architecture

Get WooCommerce product categories from WordPress

In my opinion this is the simplest solution

$orderby = 'name';
                $order = 'asc';
                $hide_empty = false ;
                $cat_args = array(
                    'orderby'    => $orderby,
                    'order'      => $order,
                    'hide_empty' => $hide_empty,
                );

                $product_categories = get_terms( 'product_cat', $cat_args );

                if( !empty($product_categories) ){
                    echo '

                <ul>';
                    foreach ($product_categories as $key => $category) {
                        echo '

                <li>';
                        echo '<a href="'.get_term_link($category).'" >';
                        echo $category->name;
                        echo '</a>';
                        echo '</li>';
                    }
                    echo '</ul>


                ';
                }

How should I tackle --secure-file-priv in MySQL?

@vhu I did the SHOW VARIABLES LIKE "secure_file_priv"; and it returned C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ so when I plugged that in, it still didn't work.

When I went to the my.ini file directly I discovered that the path is formatted a bit differently:

C:/ProgramData/MySQL/MySQL Server 8.0/Uploads

Then when I ran it with that, it worked. The only difference was the direction of the slashes.

What is the dual table in Oracle?

From Wikipedia

History

The DUAL table was created by Chuck Weiss of Oracle corporation to provide a table for joining in internal views:

I created the DUAL table as an underlying object in the Oracle Data Dictionary. It was never meant to be seen itself, but instead used inside a view that was expected to be queried. The idea was that you could do a JOIN to the DUAL table and create two rows in the result for every one row in your table. Then, by using GROUP BY, the resulting join could be summarized to show the amount of storage for the DATA extent and for the INDEX extent(s). The name, DUAL, seemed apt for the process of creating a pair of rows from just one. 1

It may not be obvious from the above, but the original DUAL table had two rows in it (hence its name). Nowadays it only has one row.

Optimization

DUAL was originally a table and the database engine would perform disk IO on the table when selecting from DUAL. This disk IO was usually logical IO (not involving physical disk access) as the disk blocks were usually already cached in memory. This resulted in a large amount of logical IO against the DUAL table.

Later versions of the Oracle database have been optimized and the database no longer performs physical or logical IO on the DUAL table even though the DUAL table still actually exists.

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

Fatal error: Call to a member function bind_param() on boolean

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

File upload along with other object in Jersey restful web service

I used file upload example from,

http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/

in my resource class i have below method

@POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response  attachupload(@FormDataParam("file") byte[] is,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("fileName") String flename){
attachService.saveAttachment(flename,is);
}

in my attachService.java i have below method

 public void saveAttachment(String flename,  byte[] is) {
            // TODO Auto-generated method stub
         attachmentDao.saveAttachment(flename,is);

        }

in Dao i have

attach.setData(is);
attach.setFileName(flename);

in my HBM mapping is like

<property name="data" type="binary" >
            <column name="data" />
</property>

This working for all type of files like .PDF,.TXT, .PNG etc.,

How to find index of an object by key and value in an javascript array

Using jQuery .each()

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
$.each(peoples, function(index, obj) {_x000D_
   $.each(obj, function(attr, value) {_x000D_
      console.log( attr + ' == ' + value );_x000D_
   });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Using for-loop:

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
for (var i = 0; i < peoples.length; i++) {_x000D_
  for (var key in peoples[i]) {_x000D_
    console.log(key + ' == ' + peoples[i][key]);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

html5 - canvas element - Multiple layers

but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.

_x000D_
_x000D_
    <div style="position: relative;"> _x000D_
      <canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
      </canvas> _x000D_
      <canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_
      </canvas>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I check if a property exists on a dynamic anonymous type in c#?

In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

public static bool PropertyExists(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        if (obj is IDictionary<string, object> dict1)
            return dict1.ContainsKey(name);
        if (obj is IDictionary<string, JToken> dict2)
            return dict2.ContainsKey(name);
        return obj.GetType().GetProperty(name) != null;
    }

Save matplotlib file to a directory

You can use the following code

name ='mypic'
plt.savefig('path_to_file/{}'.format(name))

If you want to save in same folder where your code lies,ignore the path_to_file and just format with name. If you have folder name 'Images' in the just one level outside of your python script, you can use,

name ='mypic'
plt.savefig('Images/{}'.format(name))

The default file type in saving is '.png' file format. If you want to save in loop, then you can use the unique name for each file such as counter of the for loop. If i is the counter,

plt.savefig('Images/{}'.format(i))

Hope this helps.

Get the Application Context In Fragment In Android?

Add this to onCreate

// Getting application context
        Context context = getActivity();

find if an integer exists in a list of integers

Here is a extension method, this allows coding like the SQL IN command.

public static bool In<T>(this T o, params T[] values)
{
    if (values == null) return false;

    return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
    if (values == null) return false;

    return values.Contains(o);
}

This allows stuff like that:

List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);

Or:

int i = 5;
bool isIn = i.In(1,2,3,4,5);

Is it possible to use "return" in stored procedure?

CREATE PROCEDURE pr_emp(dept_id IN NUMBER,vv_ename out varchar2  )
 AS
 v_ename emp%rowtype;
CURSOR c_emp IS
    SELECT ename
    FROM emp where deptno=dept_id;
 BEGIN
     OPEN c;
     loop
        FETCH c_emp INTO v_ename;
        return v_ename; 
        vv_ename := v_ename 
        exit when c_emp%notfound;
     end loop;
     CLOSE c_emp;


 END pr_emp;

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

This project references NuGet package(s) that are missing on this computer

I easily solve this problem by right clicking on my solution and then clicking on the Enable NuGet Package Restore option

(P.S: Ensure that you have the Nuget Install From Tools--> Extensions and Update--> Nuget Package Manager for Visual Studio 2013. If not install this extention first)

Hope it helps.

css absolute position won't work with margin-left:auto margin-right: auto

Working JSFiddle below. When using position absolute, margin: 0 auto will not work, but you can do like this (will also scale):

left: 50%;
transform: translateX(-50%);

Update: Working JSFiddle

Unable to get spring boot to automatically create database schema

@SpringBootApplication
@EnableConfigurationProperties
@EntityScan(basePackages = {"com.project.ppaa.model"})  // scan JPA entities
public class Application {

  private static ConfigurableApplicationContext applicationContext;

  public static void main(String[] args) {
    Application.applicationContext = SpringApplication.run(Application.class, args);
  }
}

it should work automatically but if it does not, you can enter the base package

@EntityScan(basePackages = {"com.project.ppaa.model"})  // scan JPA entities manually

Protect .NET code from reverse engineering?

There's Salamander, which is a native .NET compiler and linker from Remotesoft that can deploy applications without the .NET framework. I don't know how well it lives up to its claims.

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

How to create an array containing 1...N

This question has a lot of complicated answers, but a simple one-liner:

[...Array(255).keys()].map(x => x + 1)

Also, although the above is short (and neat) to write, I think the following is a bit faster (for a max length of:

127, Int8,

255, Uint8,

32,767, Int16,

65,535, Uint16,

2,147,483,647, Int32,

4,294,967,295, Uint32.

(based on the max integer values), also here's more on Typed Arrays):

(new Uint8Array(255)).map(($,i) => i + 1);

Although this solution is also not so ideal, because it creates two arrays, and uses the extra variable declaration "$" (not sure any way to get around that using this method). I think the following solution is the absolute fastest possible way to do this:

for(var i = 0, arr = new Uint8Array(255); i < arr.length; i++) arr[i] = i + 1;

Anytime after this statement is made, you can simple use the variable "arr" in the current scope;

If you want to make a simple function out of it (with some basic verification):

_x000D_
_x000D_
function range(min, max) {_x000D_
    min = min && min.constructor == Number ? min : 0;_x000D_
    !(max && max.constructor == Number && max > min) && // boolean statements can also be used with void return types, like a one-line if statement._x000D_
        ((max = min) & (min = 0));  //if there is a "max" argument specified, then first check if its a number and if its graeter than min: if so, stay the same; if not, then consider it as if there is no "max" in the first place, and "max" becomes "min" (and min becomes 0 by default)_x000D_
_x000D_
    for(var i = 0, arr = new (_x000D_
        max < 128 ? Int8Array : _x000D_
        max < 256 ? Uint8Array :_x000D_
        max < 32768 ? Int16Array : _x000D_
        max < 65536 ? Uint16Array :_x000D_
        max < 2147483648 ? Int32Array :_x000D_
        max < 4294967296 ? Uint32Array : _x000D_
        Array_x000D_
    )(max - min); i < arr.length; i++) arr[i] = i + min;_x000D_
    return arr;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
//and you can loop through it easily using array methods if you want_x000D_
range(1,11).forEach(x => console.log(x));_x000D_
_x000D_
//or if you're used to pythons `for...in` you can do a similar thing with `for...of` if you want the individual values:_x000D_
for(i of range(2020,2025)) console.log(i);_x000D_
_x000D_
//or if you really want to use `for..in`, you can, but then you will only be accessing the keys:_x000D_
_x000D_
for(k in range(25,30)) console.log(k);_x000D_
_x000D_
console.log(_x000D_
    range(1,128).constructor.name,_x000D_
    range(200).constructor.name,_x000D_
    range(400,900).constructor.name,_x000D_
    range(33333).constructor.name,_x000D_
    range(823, 100000).constructor.name,_x000D_
    range(10,4) // when the "min" argument is greater than the "max", then it just considers it as if there is no "max", and the new max becomes "min", and "min" becomes 0, as if "max" was never even written_x000D_
);
_x000D_
_x000D_
_x000D_


so, with the above function, the above super-slow "simple one-liner" becomes the super-fast, even-shorter:

range(1,14000);

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How to sort an array in descending order in Ruby

What about:

 a.sort {|x,y| y[:bar]<=>x[:bar]}

It works!!

irb
>> a = [
?>   { :foo => 'foo', :bar => 2 },
?>   { :foo => 'foo', :bar => 3 },
?>   { :foo => 'foo', :bar => 5 },
?> ]
=> [{:bar=>2, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>5, :foo=>"foo"}]

>>  a.sort {|x,y| y[:bar]<=>x[:bar]}
=> [{:bar=>5, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>2, :foo=>"foo"}]

How can I convert JSON to CSV?

A generic solution which translates any json list of flat objects to csv.

Pass the input.json file as first argument on command line.

import csv, json, sys

input = open(sys.argv[1])
data = json.load(input)
input.close()

output = csv.writer(sys.stdout)

output.writerow(data[0].keys())  # header row

for row in data:
    output.writerow(row.values())

How can I mock requests and the response?

This is how you can do it (you can run this file as-is):

import requests
import unittest
from unittest import mock

# This is the class we want to test
class MyGreatClass:
    def fetch_json(self, url):
        response = requests.get(url)
        return response.json()

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    class MockResponse:
        def __init__(self, json_data, status_code):
            self.json_data = json_data
            self.status_code = status_code

        def json(self):
            return self.json_data

    if args[0] == 'http://someurl.com/test.json':
        return MockResponse({"key1": "value1"}, 200)
    elif args[0] == 'http://someotherurl.com/anothertest.json':
        return MockResponse({"key2": "value2"}, 200)

    return MockResponse(None, 404)

# Our test case class
class MyGreatClassTestCase(unittest.TestCase):

    # We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
    @mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Assert requests.get calls
        mgc = MyGreatClass()
        json_data = mgc.fetch_json('http://someurl.com/test.json')
        self.assertEqual(json_data, {"key1": "value1"})
        json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
        self.assertEqual(json_data, {"key2": "value2"})
        json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
        self.assertIsNone(json_data)

        # We can even assert that our mocked method was called with the right parameters
        self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
        self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)

        self.assertEqual(len(mock_get.call_args_list), 3)

if __name__ == '__main__':
    unittest.main()

Important Note: If your MyGreatClass class lives in a different package, say my.great.package, you have to mock my.great.package.requests.get instead of just 'request.get'. In that case your test case would look like this:

import unittest
from unittest import mock
from my.great.package import MyGreatClass

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    # Same as above


class MyGreatClassTestCase(unittest.TestCase):

    # Now we must patch 'my.great.package.requests.get'
    @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Same as above

if __name__ == '__main__':
    unittest.main()

Enjoy!

Finding the last index of an array

say your array is called arr

do

arr[arr.Length - 1]

CSS Transition doesn't work with top, bottom, left, right

Are there properties that aren't 'transitional'?

Answer: Yes.

If the property is not listed here it is not 'transitional'.

Reference: Animatable CSS Properties

How to change the text on the action bar

ActionBar ab = getActionBar();
TextView tv = new TextView(getApplicationContext());

LayoutParams lp = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, // Width of TextView
        LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setTextColor(Color.RED);
ab.setCustomView(tv);

For more information check this link :

http://android--code.blogspot.in/2015/09/android-how-to-change-actionbar-title_21.html

How to test enum types?

you can test if have exactly some values, by example:

for(MyBoolean b : MyBoolean.values()) {
    switch(b) {
    case TRUE:
        break;
    case FALSE:
        break;
    default:
        throw new IllegalArgumentException(b.toString());
}

for(String s : new String[]{"TRUE", "FALSE" }) {
    MyBoolean.valueOf(s);
}

If someone removes or adds a value, some of test fails.

What is the difference between XAMPP or WAMP Server & IIS?

WAMP: acronym for Windows Operating System, Apache(Web server), MySQL Database and PHP Language.

XAMPP: acronym for X (any Operating System), Apache (Web server), MySQL Database, PHP Language and PERL.


XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people.

Their differences are in the format/structure of the package, the configurations, and the included management applications.

In short: XAMPP supports more OSes and includes more features

Jquery If radio button is checked

if($('#test2').is(':checked')) {
    $(this).append('stuff');
} 

Extract text from a string

If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This worked for me

On the Zipped folder of the ADT you initially downloaded unzip and navigate to:

adt-bundle-windows-x86_64-20140702\eclipse\plugins

Copy all the executable jar files and paste them on the

C:\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\eclipse\plugins

directory (or wherever your adt is located).
Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse

Comparing arrays for equality in C++

If you are willing to use std::array instead of built-in arrays, you may use:

std::array<int, 5> iar1 = {1,2,3,4,5};
std::array<int, 5> iar2 = {1,2,3,4,5};

if (iar1 == iar2)

how to play video from url

pDialog = new ProgressDialog(this);

    // Set progressbar message
    pDialog.setMessage("Buffering...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    // Show progressbar
    pDialog.show();

    try {
        // Start the MediaController
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoView);      

        Uri videoUri = Uri.parse(videoUrl);
        mVideoView.setMediaController(mediacontroller);
        mVideoView.setVideoURI(videoUri);

    } catch (Exception e) {

        e.printStackTrace();
    }

    mVideoView.requestFocus();
    mVideoView.setOnPreparedListener(new OnPreparedListener() {
        // Close the progress bar and play the video
        public void onPrepared(MediaPlayer mp) {
            pDialog.dismiss();
            mVideoView.start();
        }
    });
    mVideoView.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            finish();               
        }
    });

How to set data attributes in HTML elements

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.

If you'd like to update your data-attributes with some spread, use --

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text'); will work just fine.

Another way you could accomplish this is using --

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.

Transparent scrollbar with css

Embed this code in your css.

::-webkit-scrollbar {
    width: 0px;
}

/* Track */

::-webkit-scrollbar-track {
    -webkit-box-shadow: none;
}

/* Handle */

::-webkit-scrollbar-thumb {
    background: white;
    -webkit-box-shadow: none;
}

::-webkit-scrollbar-thumb:window-inactive {
    background: none;
}

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

Get a list of URLs from a site

The best on I have found is http://www.auditmypc.com/xml-sitemap.asp which uses Java, and has no limit on pages, and even lets you export results as a raw URL list.

It also uses sessions, so if you are using a CMS, make sure you are logged out before you run the crawl.

Is there any JSON Web Token (JWT) example in C#?

After all these months have passed after the original question, it's now worth pointing out that Microsoft has devised a solution of their own. See http://blogs.msdn.com/b/vbertocci/archive/2012/11/20/introducing-the-developer-preview-of-the-json-web-token-handler-for-the-microsoft-net-framework-4-5.aspx for details.

Proper indentation for Python multiline strings

If you want a quick&easy solution and save yourself from typing newlines, you could opt for a list instead, e.g.:

def func(*args, **kwargs):
    string = '\n'.join([
        'first line of very long string and',
        'second line of the same long thing and',
        'third line of ...',
        'and so on...',
        ])
    print(string)
    return

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

What is the purpose of the return statement?

Just to add to @Nathan Hughes's excellent answer:

The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

Here's an example:

>>> def make_3_characters_long(some_string):
...     if len(some_string) == 3:
...         return False
...     if str(some_string) != some_string:
...         return "Not a string!"
...     if len(some_string) < 3:
...         return ''.join(some_string,'x')[:,3]
...     return some_string[:,3]
... 
>>> threechars = make_3_characters_long('xyz')    
>>> if threechars:
...     print threechars
... else:
...     print "threechars is already 3 characters long!"
... 
threechars is already 3 characters long!

See the Code Style section of the Python Guide for more advice on this way of using return.

Python script header

First, any time you run a script using the interpreter explicitly, as in

$ python ./my_script.py
$ ksh ~/bin/redouble.sh
$ lua5.1 /usr/local/bin/osbf3

the #! line is always ignored. The #! line is a Unix feature of executable scripts only, and you can see it documented in full on the man page for execve(2). There you will find that the word following #! must be the pathname of a valid executable. So

#!/usr/bin/env python

executes whatever python is on the users $PATH. This form is resilient to the Python interpreter being moved around, which makes it somewhat more portable, but it also means that the user can override the standard Python interpreter by putting something ahead of it in $PATH. Depending on your goals, this behavior may or may not be OK.

Next,

#!/usr/bin/python

deals with the common case that a Python interpreter is installed in /usr/bin. If it's installed somewhere else, you lose. But this is a good way to ensure you get exactly the version you want or else nothing at all ("fail-stop" behavior), as in

#!/usr/bin/python2.5

Finally,

#!python

works only if there is a python executable in the current directory when the script is run. Not recommended.

When is the @JsonProperty property used and what is it used for?

As you know, this is all about serialize and desalinize an object. Suppose there is an object:

public class Parameter {
  public String _name;
  public String _value; 
}

The serialization of this object is:

{
  "_name": "...",
  "_value": "..."
}

The name of variable is directly used to serialize data. If you are about to remove system api from system implementation, in some cases, you have to rename variable in serialization/deserialization. @JsonProperty is a meta data to tell serializer how to serial object. It is used to:

  • variable name
  • access (READ, WRITE)
  • default value
  • required/optional

from example:

public class Parameter {
  @JsonProperty(
        value="Name",
        required=true,
        defaultValue="No name",
        access= Access.READ_WRITE)
  public String _name;
  @JsonProperty(
        value="Value",
        required=true,
        defaultValue="Empty",
        access= Access.READ_WRITE)
  public String _value; 
}

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I have the same problem and i think the firewall is blocking the git protocol. So in the end I have to resort to using https:// to fetch and push. However this will always prompt the user to enter the password...

here is the example what working for me (just to share with those cant use git:// protocol :)

git fetch https://[user-name]@github.com/[user-name]/[project].git

if the above works, you can remove the origin and replace with

git remote rm origin  
git remote add origin https://[user-name]@github.com/[user-name]/[project].git

Check if element is clickable in Selenium Java

the class attribute contains disabled when the element is not clickable.

WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
    webElement.click();
}

numpy: most efficient frequency counts for unique values in an array

multi-dimentional frequency count, i.e. counting arrays.

>>> print(color_array    )
  array([[255, 128, 128],
   [255, 128, 128],
   [255, 128, 128],
   ...,
   [255, 128, 128],
   [255, 128, 128],
   [255, 128, 128]], dtype=uint8)


>>> np.unique(color_array,return_counts=True,axis=0)
  (array([[ 60, 151, 161],
    [ 60, 155, 162],
    [ 60, 159, 163],
    [ 61, 143, 162],
    [ 61, 147, 162],
    [ 61, 162, 163],
    [ 62, 166, 164],
    [ 63, 137, 162],
    [ 63, 169, 164],
   array([     1,      2,      2,      1,      4,      1,      1,      2,
         3,      1,      1,      1,      2,      5,      2,      2,
       898,      1,      1,  

AsyncTask Android example

Sample Async Task with POST request:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key1", "value2"));
new WEBSERVICEREQUESTOR(URL, params).execute();

class WEBSERVICEREQUESTOR extends AsyncTask<String, Integer, String>
{
    String URL;
    List<NameValuePair> parameters;

    private ProgressDialog pDialog;

    public WEBSERVICEREQUESTOR(String url, List<NameValuePair> params)
    {
        this.URL = url;
        this.parameters = params;
    }

    @Override
    protected void onPreExecute()
    {
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Processing Request...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            HttpPost httpPost = new HttpPost(URL);

            if (parameters != null)
            {
                httpPost.setEntity(new UrlEncodedFormEntity(parameters));
            }
            httpResponse = httpClient.execute(httpPost);

            httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);

        }  catch (Exception e)
        {

        }
        return "";
    }

    @Override
    protected void onPostExecute(String result)
    {
        pDialog.dismiss();

        try
        {

        }
        catch (Exception e)
        {

        }
        super.onPostExecute(result);
    }
}

trigger body click with jQuery

I've used the following code a few times and it works sweet:

$("body").click(function(e){ 
    // Check what has been clicked:
    var target = $(e.target); 
    if(target.is("#target")){
    // The target was clicked
    // Do something...
  }
});

Centering a button vertically in table cell, using Twitter Bootstrap

FOR BOOTSTRAP 3.X:

Bootstrap now has the following style for table cells:

.table tbody > tr > td{
    vertical-align: top;
}

The way to go is to add your own class, adding more specificity to the previous selector:

.table tbody > tr > td.vert-aligned {
    vertical-align: middle;
}

And then add the class to your tds:

<tr>
    <td class="vert-aligned"></td>
    ...
</tr>

FOR BOOTSTRAP 2.X

There is no way to do this with Bootstrap.

When used in table cells, vertical-align does what most people expect it to, which is to mimic the (old, deprecated) valign attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:

<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>

Check your fiddle updated

Further

Also, you can't refer to the td class using .vert because Bootstrap already has this class:

.table td {
   padding: 8px;
   line-height: 20px;
   text-align: left;
   vertical-align: top; // The problem!
   border-top: 1px solid #dddddd;
}

And is overloading the vertical-align: middle in '.vert' class, so you have to define this class as td.vert.

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

C# Connecting Through Proxy

If you want the app to use the system default proxy, add this to your Application.exe.config (where application.exe is the name of your application):

<system.net>
   <defaultProxy enabled="true" useDefaultCredentials="true">
   <proxy usesystemdefault="true" bypassonlocal="true" />
   </defaultProxy>
</system.net>

More details can be found on in the MSDN article on System.Net

Replace all spaces in a string with '+'

You need the /g (global) option, like this:

var replaced = str.replace(/ /g, '+');

You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

AngularJS $location not changing the path

In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.

Usually, when the $location doesn't work it means that something was not implemented the angular way.

In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.

The old code:

taskService.createTask(data).then(function(code){
            $location.path("task/" + code);
        }, function(error){});

Note: taskService.createTask returns a promise.

$q - the angular way to use promises:

let dataPromises = [taskService.createTask(data)];
        $q.all(dataPromises).then(function(response) {
                let code = response[0];
                $location.path("task/" + code);
            }, 
            function(error){});

Using $q to resolve the promise solved the redirection problem.

More on the $q service: https://docs.angularjs.org/api/ng/service/$q

gcc error: wrong ELF class: ELFCLASS64

It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

How to get AM/PM from a datetime in PHP

<?php 
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata')); 
echo $dateTime->format("d/m/y  H:i A"); 
?>

You can use this to display the date like this

22/06/15 10:46 AM

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

SQL Combine Two Columns in Select Statement

If you don't want to change your database schema (and I would not for this simple query) you can just combine them in the filter like this: WHERE (Address1 + Address2) LIKE '%searchstring%'

Using margin:auto to vertically-align a div

I think you can fix that with Flexbox

_x000D_
_x000D_
.black {
  height : 200px;
  width : 200px;
  background-color : teal;
  border: 5px solid rgb(0, 53, 53);
  /* This is the important part */
  display : flex;
  justify-content: center;
  align-items: center;
}

.message {
  background-color :  rgb(119, 128, 0);
  border: 5px solid rgb(0, 53, 53);
  height : 50%;
  width : 50%;
  padding : 5px;
}
_x000D_
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to check if a service is running via batch file and start it, if it is not running?

Language independent version.

@Echo Off
Set ServiceName=Jenkins


SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
    echo %ServiceName% not running 
    echo Start %ServiceName%

    Net start "%ServiceName%">nul||(
        Echo "%ServiceName%" wont start 
        exit /b 1
    )
    echo "%ServiceName%" started
    exit /b 0
)||(
    echo "%ServiceName%" working
    exit /b 0
)

Android Camera : data intent returns null

I´ve had experienced this problem, the intent is not null but the information sent via this intent is not received in onActionActivit()

enter image description here

This is a better solution using getContentResolver() :

    private Uri imageUri;
    private ImageView myImageView;
    private Bitmap thumbnail;

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

      ...
      ...    
      ...
      myImageview = (ImageView) findViewById(R.id.pic); 

      values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "MyPicture");
      values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
      startActivityForResult(intent, PICTURE_RESULT);

  }

the onActivityResult() get a bitmap stored by getContentResolver() :

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                myImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

Check my example in github:

https://github.com/Jorgesys/TakePicture

MySQL - Replace Character in Columns

If you have "something" and need 'something', use replace(col, "\"", "\'") and viceversa.

How to remove newlines from beginning and end of a string?

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0

String contains another two strings

You could write an extension method with linq.

public static bool MyContains(this string str, params string[] p) {
 return !p.Cast<string>().Where(s => !str.Contains(s)).Any();
}

EDIT (thx to sirid):

public static bool MyContains(this string str, params string[] p) {
 return !p.Any(s => !str.Contains(s));
}

Append data frames together in a for loop

Here are some tidyverse and custom function options that might work depending on your needs:

library(tidyverse)

# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
 data_frame(x = rnorm(5), y = runif(5)) %>% 
    filter(x < y) %>% 
    mutate(x_plus_y = x + y) %>% 
    mutate(i = i)
}

df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
       x      y x_plus_y     i
   <dbl>  <dbl>    <dbl> <int>
1 -0.973 0.673    -0.300     1
2 -0.553 0.0463   -0.507     1
3  0.250 0.716     0.967     2
4 -0.745 0.0640   -0.681     2
5 -0.736 0.228    -0.508     2
6 -0.365 0.496     0.131     3

You could do something similar if you had a directory of files that needed to be combined:

dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)

combine_files <- function(path, file){
  read_csv(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.csv$') %>% 
  map_df(~combine_files(dir_path, .))

# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
  readxl::read_xlsx(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.xlsx$') %>% 
  map_df(~combine_xl_files(dir_path, .))

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

HTTPS connections over proxy servers

If it's still of interest, here is an answer to a similar question: Convert HTTP Proxy to HTTPS Proxy in Twisted

To answer the second part of the question:

If yes, what kind of proxy server allows this?

Out of the box, most proxy servers will be configured to allow HTTPS connections only to port 443, so https URIs with custom ports wouldn't work. This is generally configurable, depending on the proxy server. Squid and TinyProxy support this, for example.

Why does .NET foreach loop throw NullRefException when collection is null?

Because a null collection is not the same thing as an empty collection. An empty collection is a collection object with no elements; a null collection is a nonexistent object.

Here's something to try: Declare two collections of any sort. Initialize one normally so that it's empty, and assign the other the value null. Then try adding an object to both collections and see what happens.

Detect and exclude outliers in Pandas data frame

Another option is to transform your data so that the effect of outliers is mitigated. You can do this by winsorizing your data.

import pandas as pd
from scipy.stats import mstats
%matplotlib inline

test_data = pd.Series(range(30))
test_data.plot()

Original data

# Truncate values to the 5th and 95th percentiles
transformed_test_data = pd.Series(mstats.winsorize(test_data, limits=[0.05, 0.05])) 
transformed_test_data.plot()

Winsorized data

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

How to dynamic filter options of <select > with jQuery?

Much simpler code then most of the other solutions. Look for the text (case insensitive) and use CSS to hide/show the contents. Much better than storing a copy of the data.

Pass into this method the id of the select box, and id of the input containing a filter.

function FilterSelectList(selectListId, filterId)
{
    var filter = $("#" + filterId).val();
    filter = filter.toUpperCase();

    var options = $("#" + selectListId + " option");
    for (var i = 0; i < options.length; i++)
    {
       if (options[i].text.toUpperCase().indexOf(filter) < 0)
           $(options[i]).css("display", "none");
       else
           $(options[i]).css("display", "block");
    }
};

Disable Input fields in reactive form

If to use disabled form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!

(And if you are using on submit button like [disabled]="!form.valid"it will exclude your field from validation)

enter image description here

How do I send an HTML Form in an Email .. not just MAILTO

I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.

Are you running PHP or ASP.NET?

ASP.NET Example

PHP Example

Plotting multiple time series on the same plot using ggplot()

An alternative is to bind the dataframes, and assign them the type of variable they represent. This will let you use the full dataset in a tidier way

library(ggplot2)
library(dplyr)

df1 <- data.frame(dates = 1:10,Variable = rnorm(mean = 0.5,10))
df2 <- data.frame(dates = 1:10,Variable = rnorm(mean = -0.5,10))

df3 <- df1 %>%
  mutate(Type = 'a') %>%
  bind_rows(df2 %>%
              mutate(Type = 'b'))


ggplot(df3,aes(y = Variable,x = dates,color = Type)) + 
  geom_line()

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

dplyr change many data types

You can use the standard evaluation version of mutate_each (which is mutate_each_) to change the column classes:

dat %>% mutate_each_(funs(factor), l1) %>% mutate_each_(funs(as.numeric), l2)

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

Succeeded installing but could not start apache 2.4 on my windows 7 system

Port 80 maybe used by Microsoft HTTPAPI

Try to stop the following service:
  Web Deployment Agent Service
  SQL Server Reporting Service
  SQL Server VSS Writer

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

If you’re using TortoiseSVN…

From your commit window in the “Changes Made” section you can select all the offending files, then right-click and select delete. Finish the commit and the files will be removed from the scheduled additions.

Change/Get check state of CheckBox

var val = $("#checkboxId").is(":checked");

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

Get the string representation of a DOM node

Use Element#outerHTML:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

console.log(el.outerHTML);

It can also be used to write DOM elements. From Mozilla's documentation:

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

how to increase sqlplus column output length?

Actually, even that didn't work for me. When I executed "select dbms_metadata.get_ddl('TABLESPACE','TABLESPACE_NAME') from dual;" I again got only the first three lines, but this time each line was padded out to 15,000 characters. I was able to work around this with:

select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),80) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),160) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),240) from dual;

It sure seemed like there ought to be an easier way, but I couldn't seem to find it.

How to force open links in Chrome not download them?

To open docs automatically in Chrome without them being saved;

  1. Go to the the three vertical dots on your top far right corner in Chrome.

  2. Scroll down to Settings and click.

  3. Scroll down to Show advance settings...

  4. Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.

  5. Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.

  6. When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.

Right query to get the current number of connections in a PostgreSQL DB

Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

How to redirect the output of a PowerShell to a file during its execution

Maybe Start-Transcript would work for you. First stop it if it's already running, then start it, and stop it when done.

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\output.txt -append
# Do some stuff
Stop-Transcript

You can also have this running while working on stuff and have it saving your command line sessions for later reference.

If you want to completely suppress the error when attempting to stop a transcript that is not transcribing, you could do this:

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}