Programs & Examples On #Path combine

javac error: Class names are only accepted if annotation processing is explicitly requested

i think this is also because of incorrect compilation..

so for linux (ubuntu).....

javac file.java

java file

Check if a key exists inside a json object

you can do like this:

if("merchant_id" in thisSession){ /** will return true if exist */
 console.log('Exist!');
}

or

if(thisSession["merchant_id"]){ /** will return its value if exist */
 console.log('Exist!');
}

MySQL - Rows to Columns

I'm sorry to say this and maybe I'm not solving your problem exactly but PostgreSQL is 10 years older than MySQL and is extremely advanced compared to MySQL and there's many ways to achieve this easily. Install PostgreSQL and execute this query

CREATE EXTENSION tablefunc;

then voila! And here's extensive documentation: PostgreSQL: Documentation: 9.1: tablefunc or this query

CREATE EXTENSION hstore;

then again voila! PostgreSQL: Documentation: 9.0: hstore

Eclipse Error: "Failed to connect to remote VM"

Increase the memory value of the properties

  • MEM_PERM_SIZE_64BIT
  • MEM_MAX_PERM_SIZE_64BIT

in setDomainEnv.cmd file from %weblogic_home%\user_projects\domains\your_domain\bin

Center an item with position: relative

Another option is to create an extra wrapper to center the element vertically.

_x000D_
_x000D_
#container{_x000D_
  border:solid 1px #33aaff;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
}_x000D_
_x000D_
#helper{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:50%;_x000D_
  border:dotted 1px #ff55aa;_x000D_
}_x000D_
_x000D_
#centered{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:-50%;_x000D_
  border:solid 1px #ff55aa;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="helper">_x000D_
    <div id="centered"></div>_x000D_
  </div>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

in mvc 5

              @Html.EditorFor(x => x.Address, 
              new {htmlAttributes = new {@class = "form-control", 
                   @placeholder = "Complete Address", @cols = 10, @rows = 10 } })

Spring Boot - How to get the running port

Is it also possible to access the management port in a similar way, e.g.:

  @SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
  public class MyTest {

    @LocalServerPort
    int randomServerPort;

    @LocalManagementPort
    int randomManagementPort;

LINQ Contains Case Insensitive

StringComparison.InvariantCultureIgnoreCase just do the job for me:

.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));

CSS Printing: Avoiding cut-in-half DIVs between pages?

I got this problem while using Bootstrap and I had multiple columns in each rows.

I was trying to give page-break-inside: avoid; or break-inside: avoid; to the col-md-6 div elements. That was not working.

I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;.

Instead, I had to give page-break-inside: avoid; or break-inside: avoid; to the <div class="row"> element. And I had multiple rows in my print page.

That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.

In another example case, if you want 4 columns in each row, then use col-md-3.

Assembly code vs Machine code vs Object code?

The other answers gave a good description of the difference, but you asked for a visual also. Here is a diagram showing they journey from C code to an executable.

How to clear the logs properly for a Docker container?

On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:

docker logs -f --tail 100

This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...

(And thus, deleting the log is probably unnecessary)

JAX-RS / Jersey how to customize error handling?

I was facing the same issue.

I wanted to catch all the errors at a central place and transform them.

Following is the code for how I handled it.

Create the following class which implements ExceptionMapper and add @Provider annotation on this class. This will handle all the exceptions.

Override toResponse method and return the Response object populated with customised data.

//ExceptionMapperProvider.java
/**
 * exception thrown by restful endpoints will be caught and transformed here
 * so that client gets a proper error message
 */
@Provider
public class ExceptionMapperProvider implements ExceptionMapper<Throwable> {
    private final ErrorTransformer errorTransformer = new ErrorTransformer();

    public ExceptionMapperProvider() {

    }

    @Override
    public Response toResponse(Throwable throwable) {
        //transforming the error using the custom logic of ErrorTransformer 
        final ServiceError errorResponse = errorTransformer.getErrorResponse(throwable);
        final ResponseBuilder responseBuilder = Response.status(errorResponse.getStatus());

        if (errorResponse.getBody().isPresent()) {
            responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
            responseBuilder.entity(errorResponse.getBody().get());
        }

        for (Map.Entry<String, String> header : errorResponse.getHeaders().entrySet()) {
            responseBuilder.header(header.getKey(), header.getValue());
        }

        return responseBuilder.build();
    }
}

// ErrorTransformer.java
/**
 * Error transformation logic
 */
public class ErrorTransformer {
    public ServiceError getErrorResponse(Throwable throwable) {
        ServiceError serviceError = new ServiceError();
        //add you logic here
        serviceError.setStatus(getStatus(throwable));
        serviceError.setBody(getBody(throwable));
        serviceError.setHeaders(getHeaders(throwable));

    }
    private String getStatus(Throwable throwable) {
        //your logic
    }
    private Optional<String> getBody(Throwable throwable) {
        //your logic
    }
    private Map<String, String> getHeaders(Throwable throwable) {
        //your logic
    }
}

//ServiceError.java
/**
 * error data holder
 */
public class ServiceError {
    private int status;
    private Map<String, String> headers;
    private Optional<String> body;
    //setters and getters
}

How do I edit an incorrect commit message in git ( that I've pushed )?

If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:

enter image description here

How to install packages offline?

Download the wheel file (for example dlb-0.5.0-py3-none-any.whl) from Pypi and

pip install dlb-0.5.0-py3-none-any.whl

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This can be caused by a full disk (Ubuntu/Nginx).

My situation:

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

How to set a JavaScript breakpoint from code in Chrome?

On the "Scripts" tab, go to where your code is. At the left of the line number, click. This will set a breakpoint.

Screenshot:

screenshot of breakpoint in chrome

You will then be able to track your breakpoints within the right tab (as shown in the screenshot).

Bootstrap 3 .col-xs-offset-* doesn't work?

The bootstrap css used in the jsfiddle link, dont have the css for col-xs-offset-*, thats why the css are not been applied. Refer the latest bootstrap css.

Basic communication between two fragments

Update

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

Original Answer

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

FragmentB.java

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

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

FragmentA.java

//go to fragment B

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

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

Checkout one file from Subversion

I'd just browse it and export the single file. If you have HTTP access, just use the web browser to find the file and grab it.

If you need to get it back in after editing it, that might be slightly more tedious, but I'm sure there might be an svn import function...

Tomcat Server not starting with in 45 seconds

If you are using any Databases such as Oracle/Mysql then first check this databases services are start

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

how to implement a pop up dialog box in iOS

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

C++ delete vector, objects, free memory

If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I encountered a similar problem using windows command line for R script, Rscript.exe, which is very sensitive to spaces in the path. The solution was to create a virtual path to the binary folder using the windows subst command.

The following fails: "C:\Program Files\R\R-3.4.0\bin\Rscript.exe"

Doing following succeeds:

subst Z: "C:\Program Files\R\R-3.4.0"
Z:\bin\Rscript.exe

The reason the above-proposed solutions didn't work, evidently, has to do with the Rscript.exe executable's own internal path resolution from its working directory (which has a space in it) rather the windows command line being confused with the space. So using ~ or " to resolve the issue at the command line is moot. The executable must be called within a path lacking spaces.

Seeding the random number generator in Javascript

I've implemented a number of good, short and fast Pseudorandom number generator (PRNG) functions in plain JavaScript. All of them can be seeded and provide good quality numbers.

First of all, take care to initialize your PRNGs properly. Most of the generators below have no built-in seed generating procedure (for sake of simplicity), but accept one or more 32-bit values as the initial state of the PRNG. Similar seeds (e.g. a simple seed of 1 and 2) can cause correlations in weaker PRNGs, resulting in the output having similar properties (such as randomly generated levels being similar). To avoid this, it is best practice to initialize PRNGs with a well-distributed seed.

Thankfully, hash functions are very good at generating seeds for PRNGs from short strings. A good hash function will generate very different results even when two strings are similar. Here's an example based on MurmurHash3's mixing function:

function xmur3(str) {
    for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
        h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
        h = h << 13 | h >>> 19;
    return function() {
        h = Math.imul(h ^ h >>> 16, 2246822507);
        h = Math.imul(h ^ h >>> 13, 3266489909);
        return (h ^= h >>> 16) >>> 0;
    }
}

Each subsequent call to the return function of xmur3 produces a new "random" 32-bit hash value to be used as a seed in a PRNG. Here's how you might use it:

// Create xmur3 state:
var seed = xmur3("apples");
// Output four 32-bit hashes to provide the seed for sfc32.
var rand = sfc32(seed(), seed(), seed(), seed());

// Output one 32-bit hash to provide the seed for mulberry32.
var rand = mulberry32(seed());

// Obtain sequential random numbers like so:
rand();
rand();

Alternatively, simply choose some dummy data to pad the seed with, and advance the generator a few times (12-20 iterations) to mix the initial state thoroughly. This is often seen in reference implementations of PRNGs, but it does limit the number of initial states.

var seed = 1337 ^ 0xDEADBEEF; // 32-bit seed with optional XOR value
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
var rand = sfc32(0x9E3779B9, 0x243F6A88, 0xB7E15162, seed);
for (var i = 0; i < 15; i++) rand();

The output of these PRNG functions produce a positive 32-bit number (0 to 232-1) which is then converted to a floating-point number between 0-1 (0 inclusive, 1 exclusive) equivalent to Math.random(), if you want random numbers of a specific range, read this article on MDN. If you only want the raw bits, simply remove the final division operation.

Another thing to note are the limitations of JS. Numbers can only represent whole integers up to 53-bit resolution. And when using bitwise operations, this is reduced to 32. This makes it difficult to implement algorithms written in C or C++, that use 64-bit numbers. Porting 64-bit code requires shims that can drastically reduce performance. So for the sake of simplicity and efficiency, I've only considered algorithms that use 32-bit math, as it is directly compatible with JS.

Now, onward to the the generators. (I maintain the full list with references here)


sfc32 (Simple Fast Counter)

sfc32 is part of the PractRand random number testing suite (which it passes of course). sfc32 has a 128-bit state and is very fast in JS.

function sfc32(a, b, c, d) {
    return function() {
      a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0; 
      var t = (a + b) | 0;
      a = b ^ b >>> 9;
      b = c + (c << 3) | 0;
      c = (c << 21 | c >>> 11);
      d = d + 1 | 0;
      t = t + d | 0;
      c = c + t | 0;
      return (t >>> 0) / 4294967296;
    }
}

Mulberry32

Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has good quality (author states it passes all tests of gjrand testing suite and has a full 232 period, but I haven't verified).

function mulberry32(a) {
    return function() {
      var t = a += 0x6D2B79F5;
      t = Math.imul(t ^ t >>> 15, t | 1);
      t ^= t + Math.imul(t ^ t >>> 7, t | 61);
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    }
}

I would recommend this if you just need a simple but decent PRNG and don't need billions of random numbers (see Birthday problem).

xoshiro128**

As of May 2018, xoshiro128** is the new member of the Xorshift family, by Vigna & Blackman (professor Vigna was also responsible for the Xorshift128+ algorithm powering most Math.random implementations under the hood). It is the fastest generator that offers a 128-bit state.

function xoshiro128ss(a, b, c, d) {
    return function() {
        var t = b << 9, r = a * 5; r = (r << 7 | r >>> 25) * 9;
        c ^= a; d ^= b;
        b ^= c; a ^= d; c ^= t;
        d = d << 11 | d >>> 21;
        return (r >>> 0) / 4294967296;
    }
}

The authors claim it passes randomness tests well (albeit with caveats). Other researchers have pointed out that fails some tests in TestU01 (particularly LinearComp and BinaryRank). In practice, it should not cause issues when floats are used (such as these implementations), but may cause issues if relying on the raw low bits.

JSF (Jenkins' Small Fast)

This is JSF or 'smallprng' by Bob Jenkins (2007), the guy who made ISAAC and SpookyHash. It passes PractRand tests and should be quite fast, although not as fast as SFC.

function jsf32(a, b, c, d) {
    return function() {
        a |= 0; b |= 0; c |= 0; d |= 0;
        var t = a - (b << 27 | b >>> 5) | 0;
        a = b ^ (c << 17 | c >>> 15);
        b = c + d | 0;
        c = d + t | 0;
        d = a + t | 0;
        return (d >>> 0) / 4294967296;
    }
}

LCG (aka Lehmer/Park-Miller RNG or MCG)

LCG is extremely fast and simple, but the quality of its randomness is so low, that improper use can actually cause bugs in your program! Nonetheless, it is significantly better than some answers suggesting to use Math.sin or Math.PI! It's a one-liner though, which is nice :).

var LCG=s=>()=>(2**31-1&(s=Math.imul(48271,s)))/2**31;

This implementation is called the minimal standard RNG as proposed by Park–Miller in 1988 & 1993 and implemented in C++11 as minstd_rand. Keep in mind that the state is 31-bit (31 bits give 2 billion possible states, 32 bits give double that). This is the very type of PRNG that others are trying to replace!

It will work, but I wouldn't use it unless you really need speed and don't care about randomness quality (what is random anyway?). Great for a game jam or a demo or something. LCGs suffer from seed correlations, so it is best to discard the first result of an LCG. And if you insist on using an LCG, adding an increment value may improve results, but it is probably an exercise in futility when much better options exist.

There seems to be other multipliers offering a 32-bit state (increased state-space):

var LCG=s=>()=>(s=Math.imul(741103597,s)>>>0)/2**32;
var LCG=s=>()=>(s=Math.imul(1597334677,s)>>>0)/2**32;

These LCG values are from: P. L'Ecuyer: A table of Linear Congruential Generators of different sizes and good lattice structure, April 30 1997.

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

How to switch between frames in Selenium WebDriver using Java

WebDriver's driver.switchTo().frame() method takes one of the three possible arguments:

  • A number.

    Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index 0, the second at index 1 and the third at index 2. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

  • A name or ID.

    Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.

  • A previously found WebElement.

    Select a frame using its previously located WebElement.

Get the frame by it's id/name or locate it by driver.findElement() and you'll be good.

Close Window from ViewModel

My proffered way is Declare event in ViewModel and use blend InvokeMethodAction as below.

Sample ViewModel

public class MainWindowViewModel : BindableBase, ICloseable
{
    public DelegateCommand SomeCommand { get; private set; }
    #region ICloseable Implementation
    public event EventHandler CloseRequested;        

    public void RaiseCloseNotification()
    {
        var handler = CloseRequested;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
    #endregion

    public MainWindowViewModel()
    {
        SomeCommand = new DelegateCommand(() =>
        {
            //when you decide to close window
            RaiseCloseNotification();
        });
    }
}

I Closeable interface is as below but don't require to perform this action. ICloseable will help in creating generic view service, so if you construct view and ViewModel by dependency injection then what you can do is

internal interface ICloseable
{
    event EventHandler CloseRequested;
}

Use of ICloseable

var viewModel = new MainWindowViewModel();
        // As service is generic and don't know whether it can request close event
        var window = new Window() { Content = new MainView() };
        var closeable = viewModel as ICloseable;
        if (closeable != null)
        {
            closeable.CloseRequested += (s, e) => window.Close();
        }

And Below is Xaml, You can use this xaml even if you don't implement interface, it will only need your view model to raise CloseRquested.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
xmlns:ViewModels="clr-namespace:WPFRx.ViewModels" x:Name="window" x:Class="WPFRx.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525" 
d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}">

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding Mode=OneWay}" EventName="CloseRequested" >
        <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid>
    <Button Content="Some Content" Command="{Binding SomeCommand}" Width="100" Height="25"/>
</Grid>

CSS: Force float to do a whole new line

This is an old post and the links are no longer valid but because it came up early in a search I was doing I thought I should comment to help others understand the problem better.

By using float you are asking the browser to arrange your controls automatically. It responds by wrapping when the controls don't fit the width for their specified float arrangement. float:left, float:right or clear:left,clear:right,clear:both.

So if you want to force a bunch of float:left items to float uniformly into one left column then you need to make the browser decide to wrap/unwrap them at the same width. Because you don't want to do any scripting you can wrap all of the controls you want to float together in a single div. You would want to add a new wrapping div with a class like:

.LeftImages{
    float:left;
}

html

<div class="LeftImages">   
  <img...>   
  <img...> 
</div>

This div will automatically adjust to the width of the largest image and all the images will be floated left with the div all the time (no wrapping).

If you still want them to wrap you can give the div a width like width:30% and each of the images the float:left; style. Rather than adjust to the largest image it will vary in size and allow the contained images to wrap.

What data type to use for money in Java?

JSR 354: Money and Currency API

JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link:

JSR 354: Money and Currency API Download

The specification consists of the following things:

  1. An API for handling e. g. monetary amounts and currencies
  2. APIs to support interchangeable implementations
  3. Factories for creating instances of the implementation classes
  4. Functionality for calculations, conversion and formatting of monetary amounts
  5. Java API for working with Money and Currencies, which is planned to be included in Java 9.
  6. All specification classes and interfaces are located in the javax.money.* package.

Sample Examples of JSR 354: Money and Currency API:

An example of creating a MonetaryAmount and printing it to the console looks like this::

MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

When using the reference implementation API, the necessary code is much simpler:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

The API also supports calculations with MonetaryAmounts:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));

CurrencyUnit and MonetaryAmount

// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);

MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:

MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();

int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5

// NumberValue extends java.lang.Number. 
// So we assign numberValue to a variable of type Number
Number number = numberValue;

MonetaryAmounts can be rounded using a rounding operator:

CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35

When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.

List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));

Custom MonetaryAmount operations

// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
  BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
  BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
  return Money.of(tenPercent, amount.getCurrency());
};

MonetaryAmount dollars = Money.of(12.34567, "USD");

// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567

Resources:

Handling money and currencies in Java with JSR 354

Looking into the Java 9 Money and Currency API (JSR 354)

See Also: JSR 354 - Currency and Money

How do you reinstall an app's dependencies using npm?

Follow this step to re install node modules and update them

works even if node_modules folder does not exist. now execute the following command synchronously. you can also use "npm update" but I think this'd preferred way

npm outdated // not necessary to run this command, but this will show outdated dependencies

npm install -g npm-check-updates // to install the "ncu" package

ncu -u --packageFile=package.json // to update dependencies version in package.json...don't run this command if you don't need to update the version

npm install: will install dependencies in your package.json file.

if you're okay with the version of your dependencies in your package.json file, no need to follow those steps just run

 npm install

SQL 'LIKE' query using '%' where the search criteria contains '%'

To escape a character in sql you can use !:


EXAMPLE - USING ESCAPE CHARACTERS

It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.

Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.

Please note that you can only define an escape character as a single character (length of 1).

For example:

SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';

This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.

Here is another more complicated example using escape characters in the SQL LIKE condition.

SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.

You can also use the escape character with the _ character in the SQL LIKE condition.

For example:

SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.


Reference: sql/like

How can I get the current time in C#?

DateTime.Now.ToString("HH:mm:ss tt");

this gives it to you as a string.

How to get Maven project version to the bash command line

this is an edit from above

cat pom.xml | grep "" | head -n 1 | sed -e "s/version//g" | sed -e "s/\s*[<>/]*//g"

I tested it out on on the cmdline works well

grep "" pom.xml | head -n 1 | sed -e "s/version//g" | sed -e "s/\s*[<>/]*//g"

is another version of the same. I have a need to get the version number in Jenkins CI in k8s without mvn installed so this is most helpful

thanks all.

How to create a inset box-shadow only on one side?

This is what you are looking for. It has examples for each side you want with a shadow.

.top-box
{
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.4);
}
.left-box
{
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.4);
}
.right-box
{
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.4);
}
.bottom-box
{
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.4);
}

See the snippet for more examples:

_x000D_
_x000D_
body {
    background-color:#0074D9;
}
div {
    background-color:#ffffff;
    padding:20px;
    margin-top:10px;
}
.top-box {
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.7);
}
.left-box {
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.7);
}
.right-box {
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.7);
}
.bottom-box {
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.7);
}
.top-gradient-box {
    background: linear-gradient(to bottom, #999 0, #ffffff 7px, #ffffff 100%);
}
.left-gradient-box {
    background: linear-gradient(to right, #999 0, #ffffff 7px, #ffffff 100%);
}
.right-gradient-box {
    background: linear-gradient(to left, #999 0, #ffffff 7px, #ffffff 100%);
}
.bottom-gradient-box {
    background: linear-gradient(to top, #999 0, #ffffff 7px, #ffffff 100%);
}
_x000D_
<div class="top-box">
        This area has a top shadow using box-shadow
</div>

<div class="left-box">
        This area has a left shadow using box-shadow
</div>

<div class="right-box">
        This area has a right shadow using box-shadow
</div>

<div class="bottom-box">
        This area has a bottom shadow using box-shadow
</div>

<div class="top-gradient-box">
        This area has a top shadow using gradients
</div>
<div class="left-gradient-box">
        This area has a left shadow using gradients
</div>
<div class="right-gradient-box">
        This area has a right shadow using gradients
</div>
<div class="bottom-gradient-box">
        This area has a bottom shadow using gradients
</div>
_x000D_
_x000D_
_x000D_

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Equals(=) vs. LIKE

Different Operators

LIKE and = are different operators. Most answers here focus on the wildcard support, which is not the only difference between these operators!

= is a comparison operator that operates on numbers and strings. When comparing strings, the comparison operator compares whole strings.

LIKE is a string operator that compares character by character.

To complicate matters, both operators use a collation which can have important effects on the result of the comparison.

Motivating Example

Let's first identify an example where these operators produce obviously different results. Allow me to quote from the MySQL manual:

Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator:

mysql> SELECT 'ä' LIKE 'ae' COLLATE latin1_german2_ci;
+-----------------------------------------+
| 'ä' LIKE 'ae' COLLATE latin1_german2_ci |
+-----------------------------------------+
|                                       0 |
+-----------------------------------------+
mysql> SELECT 'ä' = 'ae' COLLATE latin1_german2_ci;
+--------------------------------------+
| 'ä' = 'ae' COLLATE latin1_german2_ci |
+--------------------------------------+
|                                    1 |
+--------------------------------------+

Please note that this page of the MySQL manual is called String Comparison Functions, and = is not discussed, which implies that = is not strictly a string comparison function.

How Does = Work?

The SQL Standard § 8.2 describes how = compares strings:

The comparison of two character strings is determined as follows:

a) If the length in characters of X is not equal to the length in characters of Y, then the shorter string is effectively replaced, for the purposes of comparison, with a copy of itself that has been extended to the length of the longer string by concatenation on the right of one or more pad characters, where the pad character is chosen based on CS. If CS has the NO PAD attribute, then the pad character is an implementation-dependent character different from any character in the character set of X and Y that collates less than any string under CS. Otherwise, the pad character is a .

b) The result of the comparison of X and Y is given by the collating sequence CS.

c) Depending on the collating sequence, two strings may compare as equal even if they are of different lengths or contain different sequences of characters. When the operations MAX, MIN, DISTINCT, references to a grouping column, and the UNION, EXCEPT, and INTERSECT operators refer to character strings, the specific value selected by these operations from a set of such equal values is implementation-dependent.

(Emphasis added.)

What does this mean? It means that when comparing strings, the = operator is just a thin wrapper around the current collation. A collation is a library that has various rules for comparing strings. Here's an example of a binary collation from MySQL:

static int my_strnncoll_binary(const CHARSET_INFO *cs __attribute__((unused)),
                               const uchar *s, size_t slen,
                               const uchar *t, size_t tlen,
                               my_bool t_is_prefix)
{
  size_t len= MY_MIN(slen,tlen);
  int cmp= memcmp(s,t,len);
  return cmp ? cmp : (int)((t_is_prefix ? len : slen) - tlen);
}

This particular collation happens to compare byte-by-byte (which is why it's called "binary" — it doesn't give any special meaning to strings). Other collations may provide more advanced comparisons.

For example, here is a UTF-8 collation that supports case-insensitive comparisons. The code is too long to paste here, but go to that link and read the body of my_strnncollsp_utf8mb4(). This collation can process multiple bytes at a time and it can apply various transforms (such as case insensitive comparison). The = operator is completely abstracted from the vagaries of the collation.

How Does LIKE Work?

The SQL Standard § 8.5 describes how LIKE compares strings:

The <predicate>

M LIKE P

is true if there exists a partitioning of M into substrings such that:

i) A substring of M is a sequence of 0 or more contiguous <character representation>s of M and each <character representation> of M is part of exactly one substring.

ii) If the i-th substring specifier of P is an arbitrary character specifier, the i-th substring of M is any single <character representation>.

iii) If the i-th substring specifier of P is an arbitrary string specifier, then the i-th substring of M is any sequence of 0 or more <character representation>s.

iv) If the i-th substring specifier of P is neither an arbitrary character specifier nor an arbitrary string specifier, then the i-th substring of M is equal to that substring specifier according to the collating sequence of the <like predicate>, without the appending of <space> characters to M, and has the same length as that substring specifier.

v) The number of substrings of M is equal to the number of substring specifiers of P.

(Emphasis added.)

This is pretty wordy, so let's break it down. Items ii and iii refer to the wildcards _ and %, respectively. If P does not contain any wildcards, then only item iv applies. This is the case of interest posed by the OP.

In this case, it compares each "substring" (individual characters) in M against each substring in P using the current collation.

Conclusions

The bottom line is that when comparing strings, = compares the entire string while LIKE compares one character at a time. Both comparisons use the current collation. This difference leads to different results in some cases, as evidenced in the first example in this post.

Which one should you use? Nobody can tell you that — you need to use the one that's correct for your use case. Don't prematurely optimize by switching comparison operators.

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

HTML5 Video Autoplay not working correctly

Working solution October 2018, for videos including audio channel

 $(document).ready(function() {
     $('video').prop('muted',true).play()
 });

Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675

How do I crop an image in Java?

There are two potentially major problem with the leading answer to this question. First, as per the docs:

public BufferedImage getSubimage(int x, int y, int w, int h)

Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.

Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.

Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.

Try this:

BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = copyOfImage.createGraphics();
g.drawImage(img, 0, 0, null);
return copyOfImage; //or use it however you want

This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)

403 Forbidden error when making an ajax Post request in Django framework

Another approach is to add X-CSRFTOKEN header with the "{{ csrf_token }}" value like in the following example:

$.ajax({
            url: "{% url 'register_lowresistancetyres' %}",
            type: "POST",
            headers: {//<==
                        "X-CSRFTOKEN": "{{ csrf_token }}"//<==
                },
            data: $(example_form).serialize(),
            success: function(data) {
                //Success code
            },
            error: function () {
                //Error code
            }
        });

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

Get query from java.sql.PreparedStatement

I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.

Given URL is not allowed by the Application configuration Facebook application error

You need to add the URL to your app:

  1. Go to the app, you want for user login, on the Facebook Developers page
  2. Click on the settings tab
  3. Click add platform
  4. Select Website
  5. After selection it will ask for some details such as URL for your website which uses login with facebook feature, fill the form and submit it

That's all and you are done. Make sure that the app's URL is the same from where you're logging in.

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

How to sort a List<Object> alphabetically using Object name field

This is assuming a list of YourClass instead of Object, as explained by amit.

You can use this bit from the Google Guava library:

Collections.sort(list, Ordering.natural()
  .onResultOf(new Function<String,YourClass>() {
  public String call(YourClass o) {
     return o.getName();
  }))
  .nullsLast();

The other answers which mention Comparator are not incorrect, since Ordering implements Comparator. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".

Copied shamelessly from this answer on my own question.

sudo in php exec()

Run sudo visudo command then set -%sudo ALL=(ALL:ALL) to %sudo ALL=(ALL:ALL) NOPASSWD: ALL it will work.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

My version of the loop ;)

var lowEnd = 1;
var highEnd = 25;
var arr = [];
while(lowEnd <= highEnd){
   arr.push(lowEnd++);
}

Do I really need to encode '&' as '&amp;'?

Yes, you should try to serve valid code if possible.

Most browsers will silently correct this error, but there is a problem with relying on the error handling in the browsers. There is no standard for how to handle incorrect code, so it's up to each browser vendor to try to figure out what to do with each error, and the results may vary.

Some examples where browsers are likely to react differently is if you put elements inside a table but outside the table cells, or if you nest links inside each other.

For your specific example it's not likely to cause any problems, but error correction in the browser might for example cause the browser to change from standards compliant mode into quirks mode, which could make your layout break down completely.

So, you should correct errors like this in the code, if not for anything else so to keep the error list in the validator short, so that you can spot more serious problems.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>

TypeError: Converting circular structure to JSON in nodejs

I also ran into this issue. It was because I forgot to await for a promise.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

The error is because you have not saved the files after creating them.

Try saving all the file by clicking "Save All" on the Editor.

You can see the number of files which are not saved by looking below the "File" menu shown using blue color.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Alt + Shift + F10 will show the menu associated with the smart tag.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Fill an array with random numbers

I tried to make this as simple as possible in Java. This makes an integer array of 100 variables and fill it with integers between 0 and 10 using only three lines of code. You can easily change the bounds of the random number too!

int RandNumbers[]=new int[100];
for (int i=0;i<RandNumbers.length;i++)
    RandNumbers[i]=ThreadLocalRandom.current().nextInt(0,10);

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

Is there a way to use PhantomJS in Python?

If using Anaconda, install with:

conda install PhantomJS

in your script:

from selenium import webdriver
driver=webdriver.PhantomJS()

works perfectly.

AngularJS - difference between pristine/dirty and touched/untouched

It's worth mentioning that the validation properties are different for forms and form elements (note that touched and untouched are for fields only):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

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

Run:

docker version

If docker is running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Server: Docker Engine - Community
 Engine:
  Version:          ...
 [omitted]

If docker is not running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Error response from daemon: Bad response from Docker engine

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

Unique random string generation

Update 2016/1/23

If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:

Install-Package MlkPwgen

Then you can generate random strings just like in the answer below:

var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics);

One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.

Original Answer

Since no one has provided secure code yet, I post the following in case anyone finds it useful.

string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
    if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

    const int byteSize = 0x100;
    var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
    if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

    // Guid.NewGuid and System.Random are not particularly random. By using a
    // cryptographically-secure random number generator, the caller is always
    // protected, regardless of use.
    using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
        var result = new StringBuilder();
        var buf = new byte[128];
        while (result.Length < length) {
            rng.GetBytes(buf);
            for (var i = 0; i < buf.Length && result.Length < length; ++i) {
                // Divide the byte into allowedCharSet-sized groups. If the
                // random value falls into the last group and the last group is
                // too small to choose from the entire allowedCharSet, ignore
                // the value in order to avoid biasing the result.
                var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                if (outOfRangeStart <= buf[i]) continue;
                result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
            }
        }
        return result.ToString();
    }
}

Thanks to Ahmad for pointing out how to get the code working on .NET Core.

Share application "link" in Android

Actually the best way to sheared you app between users , google (firebase) proved new technology Firebase Dynamic Link Through several lines you can make it this is documentation https://firebase.google.com/docs/dynamic-links/ and the code is

  Uri dynamicLinkUri = dynamicLink.getUri();
      Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
            .setLink(Uri.parse("https://www.google.jo/"))
            .setDynamicLinkDomain("rw4r7.app.goo.gl")
            .buildShortDynamicLink()
            .addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
                @Override
                public void onComplete(@NonNull Task<ShortDynamicLink> task) {
                    if (task.isSuccessful()) {
                        // Short link created
                        Uri shortLink = task.getResult().getShortLink();
                        Uri flowchartLink = task.getResult().getPreviewLink();
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND);
                        intent.putExtra(Intent.EXTRA_TEXT,  shortLink.toString());
                        intent.setType("text/plain");
                        startActivity(intent);
                    } else {
                        // Error
                        // ...
                    }
                }
            });

SQL Server Convert Varchar to Datetime

You could do it this way but it leaves it as a varchar

declare @s varchar(50)

set @s = '2011-09-28 18:01:00'

select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)

or

select convert(varchar(20), @s, 105)

how to replace characters in hive?

Custom SerDe might be a way to do it. Or you could use some kind of mediation process with regex_replace:

create table tableB as 
select 
    columnA
    regexp_replace(description, '\\t', '') as description
from tableA
;

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Retrieve the maximum length of a VARCHAR column in SQL Server

SELECT MAX(LEN(Desc)) as MaxLen FROM table

SimpleXML - I/O warning : failed to load external entity

simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.

You have two options:

  • Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():

    $feed = file_get_contents('...');
    $items = simplexml_load_string($feed);
    
  • Load the XML feed directly using simplexml_load_file():

    $items = simplexml_load_file('...');
    

PHP: Inserting Values from the Form into MySQL

When you click the Button

if(isset($_POST['save'])){
        $sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
        VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
    **if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }**
}

This will execute the Query in the variable $sql

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

How to delete specific rows and columns from a matrix in a smarter way?

You can use

t1<- t1[-4:-6,-7:-9]  

or

t1 <- t1[-(4:6), -(7:9)]

or

t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]

You can pass vectors to select rows/columns to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns.

> t1 <- array(1:20, dim=c(10,10));

> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   12    2   12    2   12
[2,]    3   13    3   13    3   13
[3,]    5   15    5   15    5   15
[4,]    8   18    8   18    8   18
[5,]   10   20   10   20   10   20

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

If you are looking for TypeScript working functions then follow

public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;

public alphaValue = (numericDigit: any) => 
   String.fromCharCode(64 + numericDigit) : '';

You can make several checks like (numericDigit >= 1 && numericDigit <= 26) ? inside function body as per the requirements.

Find by key deep in a nested array

I'd like to suggest an amendment to Zach/RegularMike's answer (but don't have the "reputation" to be able to comment!). I found there solution a very useful basis, but suffered in my application because if there are strings within arrays it would recursively call the function for every character in the string (which caused IE11 & Edge browsers to fail with "out of stack space" errors). My simple optimization was to add the same test used in the "object" clause recursive call to the one in the "array" clause:

if (arrayElem instanceof Object || arrayElem instanceof Array) {

Thus my full code (which is now looking for all instances of a particular key, so slightly different to the original requirement) is:

// Get all instances of specified property deep within supplied object
function getPropsInObject(theObject, targetProp) {
    var result = [];
    if (theObject instanceof Array) {
        for (var i = 0; i < theObject.length; i++) {
            var arrayElem = theObject[i];
            if (arrayElem instanceof Object || arrayElem instanceof Array) {
                result = result.concat(getPropsInObject(arrayElem, targetProp));
            }
        }
    } else {
        for (var prop in theObject) {
            var objProp = theObject[prop];
            if (prop == targetProp) {
                return theObject[prop];
            }
            if (objProp instanceof Object || objProp instanceof Array) {
                result = result.concat(getPropsInObject(objProp, targetProp));
            }
        }
    }
    return result;
}

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

mysql_fetch_array() expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server. u will get the answer..

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

How does ApplicationContextAware work in Spring?

When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked. E.g. (very simplified)

Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
    ((ApplicationContextAware) bean).setApplicationContext(ctx);
}

Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:

@Inject // or @Autowired
private ApplicationContext ctx;

Display all views on oracle database

SELECT * 
FROM DBA_OBJECTS  
WHERE OBJECT_TYPE = 'VIEW'

Can JavaScript connect with MySQL?

Typically, you need a server side scripting language like PHP to connect to MySQL, however, if you're just doing a quick mockup, then you can use http://www.mysqljs.com to connect to MySQL from Javascript using code as follows:

MySql.Execute(
    "mysql.yourhost.com", 
    "username", 
    "password", 
    "database", 
    "select * from Users", 
    function (data) {
        console.log(data)
});

It has to be mentioned that this is not a secure way of accessing MySql, and is only suitable for private demos, or scenarios where the source code cannot be accessed by end users, such as within Phonegap iOS apps.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

how to run mysql in ubuntu through terminal

You have to give a valid username. For example, to run query with user root you have to type the following command and then enter password when prompted:

mysql -u root -p

Once you are connected, prompt will be something like:

mysql>

Here you can write your query, after database selection, for example:

mysql> USE your_database;
mysql> SELECT * FROM your_table;

How do I access store state in React Redux?

If you want to do some high-powered debugging, you can subscribe to every change of the state and pause the app to see what's going on in detail as follows.

store.js
store.subscribe( () => {
  console.log('state\n', store.getState());
  debugger;
});

Place that in the file where you do createStore.

To copy the state object from the console to the clipboard, follow these steps:

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

https://stackoverflow.com/a/25140576

https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html

You can view the object in a json viewer like this one: http://jsonviewer.stack.hu/

You can compare two json objects here: http://www.jsondiff.com/

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...
  }
});

How to pass parameters to a Script tag?

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

http://jsfiddle.net/xqr77dLt/

How to enter in a Docker container already running with a new TTY

docker exec -t -i container_name /bin/bash

Will take you to the containers console.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Expanded(
  child: Align(
    alignment: FractionalOffset.bottomCenter,
      child: Padding(
        padding: EdgeInsets.only(bottom: 10.0),
          child: //Your widget here,
    ),
  ),
),

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

Descending order by date filter in AngularJs

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You can use JavaScript as well, in case the textfield is dithered.

WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);

How do I check particular attributes exist or not in XML?

If your code is dealing with XmlElements objects (rather than XmlNodes) then there is the method XmlElement.HasAttribute(string name).

So if you are only looking for attributes on elements (which it looks like from the OP) then it may be more robust to cast as an element, check for null, and then use the HasAttribute method.

foreach (XmlNode xNode in nodeListName)
{
  XmlElement xParentEle = xNode.ParentNode as XmlElement;
  if((xParentEle != null) && xParentEle.HasAttribute("split"))
  {
     parentSplit = xParentEle.Attributes["split"].Value;
  }
}

Get individual query parameters from Uri

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

I used String.prototype.match(regex) which returns a string array of all found matches of the given regex in the string (more info see here):

_x000D_
_x000D_
function getLastIndex(text, regex, limit = text.length) {_x000D_
  const matches = text.match(regex);_x000D_
_x000D_
  // no matches found_x000D_
  if (!matches) {_x000D_
    return -1;_x000D_
  }_x000D_
_x000D_
  // matches found but first index greater than limit_x000D_
  if (text.indexOf(matches[0] + matches[0].length) > limit) {_x000D_
    return -1;_x000D_
  }_x000D_
_x000D_
  // reduce index until smaller than limit_x000D_
  let i = matches.length - 1;_x000D_
  let index = text.lastIndexOf(matches[i]);_x000D_
  while (index > limit && i >= 0) {_x000D_
    i--;_x000D_
    index = text.lastIndexOf(matches[i]);_x000D_
  }_x000D_
  return index > limit ? -1 : index;_x000D_
}_x000D_
_x000D_
// expect -1 as first index === 14_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g, 10));_x000D_
_x000D_
// expect 29_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g));
_x000D_
_x000D_
_x000D_

How to replace a character with a newline in Emacs?

inline just: C-M-S-% (if binding keys still default) than replace-string^J

Visual Studio Code always asking for git credentials

Solve the issue by following steps.

Uninstalled softwares Vscode and git and reinstalled the same. Changed the git repository clone url from ssh to https.

Chrome: console.log, console.debug are not working

Make sure the filter box is empty

Change application's starting activity

Just go to your AndroidManifest.xml file and add like below

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

then save and run your android project.

How can I check if a var is a string in JavaScript?

check for null or undefined in all cases a_string

if (a_string && typeof a_string === 'string') {
    // this is a string and it is not null or undefined.
}

Pass multiple optional parameters to a C# function

C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.

php stdClass to array

The lazy one-liner method

You can do this in a one liner using the JSON methods if you're willing to lose a tiny bit of performance (though some have reported it being faster than iterating through the objects recursively - most likely because PHP is slow at calling functions). "But I already did this" you say. Not exactly - you used json_decode on the array, but you need to encode it with json_encode first.

Requirements

The json_encode and json_decode methods. These are automatically bundled in PHP 5.2.0 and up. If you use any older version there's also a PECL library (that said, in that case you should really update your PHP installation. Support for 5.1 stopped in 2006.)


Converting an array/stdClass -> stdClass

$stdClass = json_decode(json_encode($booking));

Converting an array/stdClass -> array

The manual specifies the second argument of json_decode as:

assoc
When TRUE, returned objects will be converted into associative arrays.

Hence the following line will convert your entire object into an array:

$array = json_decode(json_encode($booking), true);

How to change an input button image using CSS?

If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.

Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.

Custom domain for GitHub project pages

As of Aug 29, 2013, Github's documentation claim that:

Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.

.htaccess redirect http to https

Update 2016

As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL

<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>

Old answer, hacky thing given that your ssl-port is not set to 80, this will work:

RewriteEngine on

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Note that this should be your first rewrite rule.

Edit: This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*) and redirect it to a https-url. %{SERVER_NAME} may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI} is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.

How to add parameters to HttpURLConnection using POST using NameValuePair

In my case I have created function like this to make Post request which takes String url and hashmap of parameters

 public  String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
    String response="";
    try {
        URL url = new URL(mainUrl);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : parameterList.entrySet())
        {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");




        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; )
            sb.append((char) c);
        response = sb.toString();


    return  response;
    }catch (Exception excep){
        excep.printStackTrace();}
    return response;
}

How to print the value of a Tensor object in TensorFlow?

While other answers are correct that you cannot print the value until you evaluate the graph, they do not talk about one easy way of actually printing a value inside the graph, once you evaluate it.

The easiest way to see a value of a tensor whenever the graph is evaluated (using run or eval) is to use the Print operation as in this example:

# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()

# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

# Add print operation
a = tf.Print(a, [a], message="This is a: ")

# Add more elements of the graph using a
b = tf.add(a, a)

Now, whenever we evaluate the whole graph, e.g. using b.eval(), we get:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

Who sets response content-type in Spring MVC (@ResponseBody)

Just in case you can also set encoding by the following way:

@RequestMapping(value = "ajax/gethelp")
public ResponseEntity<String> handleGetHelp(Locale loc, String code, HttpServletResponse response) {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/html; charset=utf-8");

    log.debug("Getting help for code: " + code);
    String help = messageSource.getMessage(code, null, loc);
    log.debug("Help is: " + help);

    return new ResponseEntity<String>("returning: " + help, responseHeaders, HttpStatus.CREATED);
}

I think using StringHttpMessageConverter is better than this.

jQuery.ajax returns 400 Bad Request

Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.

As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs

e.g.

$('#my_get_related_keywords').click(function() {

    var ajaxRequest = $.ajax({
        type: "POST",
        url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
        data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json"});

    //When the request successfully finished, execute passed in function
    ajaxRequest.done(function(msg){
           //do something
    });

    //When the request failed, execute the passed in function
    ajaxRequest.fail(function(jqXHR, status){
        //do something else
    });
});

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

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

What does the ">" (greater-than sign) CSS selector mean?

The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.

An example:

article > p { }

Means only style a paragraph that comes after an article.

How to create a remote Git repository from a local one?

I think you make a bare repository on the remote side, git init --bare, add the remote side as the push/pull tracker for your local repository (git remote add origin URL), and then locally you just say git push origin master. Now any other repository can pull from the remote repository.

How to overlay image with color in CSS?

Here's a creative idea using box-shadow:

#header {
    background-image: url("apple.jpg");
    box-shadow: inset 0 0 99999px rgba(0, 120, 255, 0.5);
}

What's happening

  1. The background sets the background for your element.

  2. The box-shadow is the important bit. It basically sets a really big shadow on the inside of the element, on top of the background, that is semi-transparent

Copy rows from one table to another, ignoring duplicates

Something like this?:

INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL

Automatically create an Enum based on values in a database lookup table?

Just showing the answer of Pandincus with "of the shelf" code and some explanation: You need two solutions for this example ( I know it could be done via one also ; ), let the advanced students present it ...

So here is the DDL SQL for the table :

USE [ocms_dev]
    GO

CREATE TABLE [dbo].[Role](
    [RoleId] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [varchar](50) NULL
) ON [PRIMARY]

So here is the console program producing the dll:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;

namespace DynamicEnums
{
    class EnumCreator
    {
        // after running for first time rename this method to Main1
        static void Main ()
        {
            string strAssemblyName = "MyEnums";
            bool flagFileExists = System.IO.File.Exists (
                   AppDomain.CurrentDomain.SetupInformation.ApplicationBase + 
                   strAssemblyName + ".dll"
            );

            // Get the current application domain for the current thread
            AppDomain currentDomain = AppDomain.CurrentDomain;

            // Create a dynamic assembly in the current application domain,
            // and allow it to be executed and saved to disk.
            AssemblyName name = new AssemblyName ( strAssemblyName );
            AssemblyBuilder assemblyBuilder = 
                    currentDomain.DefineDynamicAssembly ( name,
                            AssemblyBuilderAccess.RunAndSave );

            // Define a dynamic module in "MyEnums" assembly.
            // For a single-module assembly, the module has the same name as
            // the assembly.
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule (
                    name.Name, name.Name + ".dll" );

            // Define a public enumeration with the name "MyEnum" and
            // an underlying type of Integer.
            EnumBuilder myEnum = moduleBuilder.DefineEnum (
                    "EnumeratedTypes.MyEnum",
                    TypeAttributes.Public,
                    typeof ( int )
            );

            #region GetTheDataFromTheDatabase
            DataTable tableData = new DataTable ( "enumSourceDataTable" );

            string connectionString = "Integrated Security=SSPI;Persist " +
                    "Security Info=False;Initial Catalog=ocms_dev;Data " +
                    "Source=ysg";

            using (SqlConnection connection = 
                    new SqlConnection ( connectionString ))
            {

                SqlCommand command = connection.CreateCommand ();
                command.CommandText = string.Format ( "SELECT [RoleId], " + 
                        "[RoleName] FROM [ocms_dev].[dbo].[Role]" );

                Console.WriteLine ( "command.CommandText is " + 
                        command.CommandText );

                connection.Open ();
                tableData.Load ( command.ExecuteReader ( 
                        CommandBehavior.CloseConnection
                ) );
            } //eof using

            foreach (DataRow dr in tableData.Rows)
            {
                myEnum.DefineLiteral ( dr[1].ToString (),
                        Convert.ToInt32 ( dr[0].ToString () ) );
            }
            #endregion GetTheDataFromTheDatabase

            // Create the enum
            myEnum.CreateType ();

            // Finally, save the assembly
            assemblyBuilder.Save ( name.Name + ".dll" );
        } //eof Main 
    } //eof Program
} //eof namespace 

Here is the Console programming printing the output ( remember that it has to reference the dll ). Let the advance students present the solution for combining everything in one solution with dynamic loading and checking if there is already build dll.

// add the reference to the newly generated dll
use MyEnums ; 

class Program
{
    static void Main ()
    {
        Array values = Enum.GetValues ( typeof ( EnumeratedTypes.MyEnum ) );

        foreach (EnumeratedTypes.MyEnum val in values)
        {
            Console.WriteLine ( String.Format ( "{0}: {1}",
                    Enum.GetName ( typeof ( EnumeratedTypes.MyEnum ), val ),
                    val ) );
        }

        Console.WriteLine ( "Hit enter to exit " );
        Console.ReadLine ();
    } //eof Main 
} //eof Program

Python - How do you run a .py file?

Usually you can double click the .py file in Windows explorer to run it. If this doesn't work, you can create a batch file in the same directory with the following contents:

C:\python23\python YOURSCRIPTNAME.py

Then double click that batch file. Or, you can simply run that line in the command prompt while your working directory is the location of your script.

How get permission for camera in android.(Specifically Marshmallow)

First check if the user has granted the permission:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
    == PackageManager.PERMISSION_DENIED)

Then, you could use this to request to the user:

ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

And in Marshmallow, it will appear in a dialog

git am error: "patch does not apply"

This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.

To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.

NB git am applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr, as per this answer.

Convert decimal to hexadecimal in UNIX shell script

In zsh you can do this sort of thing:

% typeset -i 16 y
% print $(( [#8] x = 32, y = 32 ))
8#40
% print $x $y
8#40 16#20
% setopt c_bases
% print $y
0x20

Example taken from zsh docs page about Arithmetic Evaluation.

I believe Bash has similar capabilities.

How can I have Github on my own server?

Atlassian's Stash (Now called BitBucket Server) is getting there to being a good Github Enterprise alternative. I'm a bit of a JIRA whore so I like the integrations you have with that.

Set QLineEdit to accept only numbers

The best is QSpinBox.

And for a double value use QDoubleSpinBox.

QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Check if ADODB connection is open

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

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

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

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

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

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

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

    Dim i As Long
    Dim cmd As New ADODB.Command

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

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

    'Tidy up
    Set cmd = Nothing

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

End Function

How can I pipe stderr, and not stdout?

In Bash, you can also redirect to a subshell using process substitution:

command > >(stdlog pipe)  2> >(stderr pipe)

For the case at hand:

command 2> >(grep 'something') >/dev/null

How to change colors of a Drawable in Android?

If you have your drawable set to the ImageView you can do it with a 1 liner:

yourImageView.setColorFilter(context.getResources().getColor(R.color.YOUR_COLOR_HERE);

How to disable text selection using jQuery?

        $(document).ready(function(){
            $("body").css("-webkit-user-select","none");
            $("body").css("-moz-user-select","none");
            $("body").css("-ms-user-select","none");
            $("body").css("-o-user-select","none");
            $("body").css("user-select","none");
        });

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Increase max execution time for php

Well, since your on a shared server, you can't do anything about it. They usually set the max execution time so that you can't override it. I suggest you contact them.

How to get text box value in JavaScript



The problem is that you made a Tiny mistake!

This is the JS code I use:

var jobName = document.getElementById("txtJob").value;

You should not use name="". instead use id="".

Getting a File's MD5 Checksum in Java

There's an input stream decorator, java.security.DigestInputStream, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.

MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
     DigestInputStream dis = new DigestInputStream(is, md)) 
{
  /* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

Eclipse Intellisense?

You don't have to press CTRL * space but maybe the delay is too big or you don't like the trigger (default is '.'). Go to

Window -> Preferences -> Java/Editor/Content Assist

And change the settings under Auto Activation to your likings.

If this does not work for windows users then see this answer.

JavaScript and getElementById for multiple elements with the same ID

If you're using d3 for handling multiple objects with the same class / id

You can remove a subset of class elements by using d3.selectAll(".classname");

For example the donut graph here on http://medcorp.co.nz utilizes copies of an arc object with class name "arc" and there's a single line of d3, d3.selectAll(".arc").remove(); to remove all those objects;

using document.getElementById("arc").remove(); only removes a single element and would have to be called multiple times (as is with the suggestions above he creates a loop to remove the objects n times)

Difference between jQuery .hide() and .css("display", "none")

no difference

With no parameters, the .hide() method is the simplest way to hide an element:

$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

Same about show

Tick symbol in HTML/XHTML

I normally use the fontawesome font(http://fontawesome.io/icon/check/), you can use it in html files:

 <i class="fa fa-check"></i>

or in css:

content: "\f00c";
font-family: FontAwesome;

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How can I ping a server port with PHP?

socket_create needs to be run as root on a UNIX system with;

$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);

how to create dynamic two dimensional array in java?

One more example for 2 dimension String array:

public void arrayExam() {
    List<String[]> A = new ArrayList<String[]>();
    A.add(new String[] {"Jack","good"});
    A.add(new String[] {"Mary","better"});
    A.add(new String[] {"Kate","best"});
    for (String[] row : A) {
        Log.i(TAG,row[0] + "->" + row[1]);
    }
}

Output:

17467 08-02 19:24:40.518  8456  8456 I MyExam  : Jack->good
17468 08-02 19:24:40.518  8456  8456 I MyExam  : Mary->better
17469 08-02 19:24:40.518  8456  8456 I MyExam  : Kate->best

Select All checkboxes using jQuery

I have seen many answers to this question and found some answer is lengthy and some answer is a little bit wrong. I have created my own code by using the above IDs and class.

$('#ckbCheckAll').click(function(){
        if($(this).prop("checked")) {
            $(".checkBoxClass").prop("checked", true);
        } else {
            $(".checkBoxClass").prop("checked", false);
        }                
    });


    $('.checkBoxClass').click(function(){
        if($(".checkBoxClass").length == $(".checkBoxClass:checked").length) { 
            $("#ckbCheckAll").prop("checked", true);
        }else {
            $("#ckbCheckAll").prop("checked", false);            
        }
    });

In the above code, where user clicks on select all checkbox and all checkbox will be selected and vice versa and second code will work when the user selects checkbox one by one then select all checkbox will be checked or unchecked according to a number of checkboxes checked.

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

How can I change the value of the elements in a vector?

int main() {
  using namespace std;

  fstream input ("input.txt");
  if (!input) return 1;

  vector<double> v;
  for (double d; input >> d;) {
    v.push_back(d);
  }
  if (v.empty()) return 1;

  double total = std::accumulate(v.begin(), v.end(), 0.0);
  double mean = total / v.size();

  cout << "The values in the file input.txt are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x << '\n';
  }
  cout << "The sum of the values is: " << total << '\n';
  cout << "The mean value is: " << mean << '\n';
  cout << "After subtracting the mean, The values are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x - mean << '\n';  // outputs without changing
    *x -= mean;  // changes the values in the vector
  }

  return 0;
}

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

I have looked through multiple answers.\

  1. The answer with setting maximum-scale=1 in meta tag works fine on iOS devices but disables the pinch to zoom functionality on Android devices.
  2. The one with setting font-size: 16px; onfocus is too hacky for me.

So I wrote a JS function to dynamically change meta tag.

var iOS = navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
if (iOS)
    document.head.querySelector('meta[name="viewport"]').content = "width=device-width, initial-scale=1, maximum-scale=1";
else
    document.head.querySelector('meta[name="viewport"]').content = "width=device-width, initial-scale=1";

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

You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar

environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");

spring.factories of spring-cloud-commons-2.1.0.RC2.jar

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor

NSDate get year/month/day

In Swift 2.0:

    let date = NSDate()
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components([.Month, .Day], fromDate: date)

    let (month, day) = (components.month, components.day)

typedef struct vs struct definitions

The typedef, as it is with other constructs, is used to give a data type a new name. In this case it is mostly done in order to make the code cleaner:

struct myStruct blah;

vs.

myStruct blah;

Android customized button; changing text color

ok very simple first go to 1. res-valuse and open colors.xml 2.copy 1 of the defined text their for example #FF4081 and change name for instance i changed to white and change its value for instance i changed to #FFFFFF for white value like this

<color name="White">#FFFFFF</color>

then inside your button add this line

 b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White));

ok b3 is the name of my button so changed of the name of ur button all others will be same if u use white color if you change different color then change white to the name of your color but first you have define that color in colors.xml like i explained in pont 2

How to get Chrome to allow mixed content?

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" " --allow-running-insecure-content"

How to import a .cer certificate into a java keystore?

Here's a script I used to batch import a bunch of crt files in the current directory into the java keystore. Just save this to the same folder as your certificate, and run it like so:

./import_all_certs.sh

import_all_certs.sh

KEYSTORE="$(/usr/libexec/java_home)/jre/lib/security/cacerts";

function running_as_root()
{
  if [ "$EUID" -ne 0 ]
    then echo "NO"
    exit
  fi

  echo "YES"
}

function import_certs_to_java_keystore
{
  for crt in *.crt; do 
    echo prepping $crt 
    keytool -import -file $crt -storepass changeit -noprompt --alias alias__${crt} -keystore $KEYSTORE
    echo 
  done
}

if [ "$(running_as_root)" == "YES" ]
then
  import_certs_to_java_keystore
else
  echo "This script needs to be run as root!"
fi

How to get today's Date?

Is there are more correct way?

Yes, there is.

LocalDate.now( 
    ZoneId.of( "America/Montreal" ) 
).atStartOfDay(
    ZoneId.of( "America/Montreal" )
)

java.time

Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Examples

Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.

Here is an example of date-only, without time-of-day nor time zone.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );

today : 2015-10-19

Here is an example of getting current date-time.

ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );

When run:

zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]

First Moment Of The Day

The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0 but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0.

Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay. Let's see some code using the LocalDate named today and the ZoneId named zoneId from code above.

ZonedDateTime todayStart = today.atStartOfDay( zoneId );

zdt : 2015-10-19T00:00:00-04:00[America/Montreal]

Interoperability

If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant ) method.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

A hint for anyone experiencing this. This can happen when a switchMap doesn't receive an observable return value (like null). Simply add a default case, so it always returns an observable.

        switchMap((dateRange) => {
          if (dateRange === 'Last 24 hours') {
            return $observable1;
          }
          if (dateRange === 'Last 7 Days') {
            return $observable2;
          }
          if (dateRange === 'Last 30 Days') {
            return $observable3;
          }
          // This line will work for default cases
          return $observableElse;
        })

How can I make Flexbox children 100% height of their parent?

Use align-items: stretch

Similar to David Storey's answer, my workaround is:

.flex-2 {
    display: flex;
    align-items: stretch;
}

Note that height: 100% should be removed from the child component even (see comments).

Alternatively to align-items, you can use align-self just on the .flex-2-child item you want stretched.

What is managed or unmanaged code in programming?

Managed Code:
Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

Un-Managed Code:
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).

Reference: http://www.dotnetspider.com/forum/11612-difference-between-managed-and-unmanaged-code.aspx

Get keys from HashMap in Java

If you just need something simple and more of a verification.

public String getKey(String key)
{
    if(map.containsKey(key)
    {
        return key;
    }
    return null;
}

Then you can search for any key.

System.out.println( "Does this key exist? : " + getKey("United") );

Rails 4 Authenticity Token

This is a security feature in Rails. Add this line of code in the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:

driver.manage().timeouts().implicitlyWait( ... )

How to link to apps on the app store

This code generates the App Store link on iOS

NSString *appName = [NSString stringWithString:[[[NSBundle mainBundle] infoDictionary]   objectForKey:@"CFBundleName"]];
NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.com/app/%@",[appName stringByReplacingOccurrencesOfString:@" " withString:@""]]];

Replace itms-apps with http on Mac:

NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"http:/itunes.com/app/%@",[appName stringByReplacingOccurrencesOfString:@" " withString:@""]]]; 

Open URL on iOS:

[[UIApplication sharedApplication] openURL:appStoreURL];

Mac:

[[NSWorkspace sharedWorkspace] openURL:appStoreURL];

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Is your server configured for client authentication? If so you need to pass the client certificate while connecting with the server.

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Image vs Bitmap class

Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.

You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.

Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

npm throws error without sudo

In case sudo chown -R $(whoami) ~/.npm didn't work for you, or you need a non terminal command solution.

The issue is that your user account does not have write permission to node_modules folder, so you can do the following

  1. Open finder and press cmd + shift + g this will open go to folder with url

  2. Write the following path /usr/local/lib/node_modules and press go

  3. Right click on node_modules folder and choose Get Info

  4. Scroll down to sharing & permissions section

  5. Unlock to be able to make changes.

  6. Press + and add your user account

  7. Make sure that you choose Read & Write in privilege drop down

Now you should be able to install packages without sudo and permission issues should be solved

java: ArrayList - how can I check if an index exists?

Since java-9 there is a standard way of checking if an index belongs to the array - Objects#checkIndex() :

List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException

How to get previous page url using jquery

document.referrer is not working always.

You can use:

window.location.origin

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t = Time.now
d = DateTime.now

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)

How to exit git log or git diff

You're in the less program, which makes the output of git log scrollable.

Type q to exit this screen. Type h to get help.

If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER to cat or set core.pager to cat (execute git config --global core.pager cat).

How to delete empty folders using windows command prompt?

@echo off
set /p "ipa= ENTER FOLDER NAME TO DELETE> "
set ipad="%ipa%"
IF not EXIST %ipad% GOTO notfound
IF EXIST %ipad% GOTO found
:found
echo DONOT CLOSE THIS WINDOW
md ccooppyy
xcopy %ipad%\*.* ccooppyy /s > NUL
rd %ipad% /s /q
ren ccooppyy %ipad%
cls
echo SUCCESS, PRESS ANY KEY TO EXIT
pause > NUL
exit 
:notfound
echo I COULDN'T FIND THE FOLDER %ipad%
pause
exit

How do JavaScript closures work?

After a function is invoked, it goes out of scope. If that function contains something like a callback function, then that callback function is still in scope. If the callback function references some local variable in the immediate environment of the parent function, then naturally you'd expect that variable to be inaccessible to the callback function and return undefined.

Closures ensure that any property that is referenced by the callback function is available for use by that function, even when its parent function may have gone out of scope.

how to get session id of socket.io client in Client

Try from your code socket.socket.sessionid ie.

    var socket = io.connect('http://localhost');
alert(socket.socket.sessionid);
  var sendBtn= document.getElementById('btnSend');
  sendBtn.onclick= function(){
var userId=document.getElementById('txt1').value;
var userMsg = document.getElementById('txt2').value;
socket.emit('sendto',{username: userId, message: userMsg});
};

  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
  socket.on('message',function(data){ console.log(data);});

Start a fragment via Intent within a Fragment

Try this it may help you:

public void ButtonClick(View view) {
    Fragment mFragment = new YourNextFragment(); 
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}

How to navigate back to the last cursor position in Visual Studio Code?

The answer for your question:

  1. Mac:
    (Alt+?) For backward and (Alt+?) For forward navigation
  2. Windows:
    (Ctrl+-) For backward and (Ctrl+Shift+-) For forward navigation
  3. Linux:
    (Ctrl+Alt+-) For backward and (Ctrl+Shift+-) For forward navigation


You can find out the current key-bindings following this link

You can even edit the key-binding as per your preference.

Migration: Cannot add foreign key constraint

make sure your foreing column is over wide rage of foreing key column

I means your foreingkey (in second table) must be same type of your ponter pricipal key (in first table)

your pointer principal key must be add unsigned method, let me show:

on your FIRST migration table:

$table->increments('column_name'); //is INTEGER and UNSIGNED

on your SECOND migration table:

$table->integer('column_forein_name')->unsigned(); //this must be INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

ANOTHER EXAMPLE TO SEE DIFFERENCE

on your FIRST migration table:

$table->mediumIncrements('column_name'); //is MEDIUM-INTEGER and UNSIGNED

on your SECOND migration table:

$table->mediumInteger('column_forein_name')->unsigned(); //this must be MEDIUM-INTEGER and UNSIGNED
$table->foreign('column_forein_name')->references('column_name')->on('first_table_name');

SEE MYSQL NUMERIC TYPES TABLE RANGES

CSS center display inline block?

Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table

body {
    background: #bbb;
    text-align: center;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: inline-block;
    overflow: hidden;
}

How to get Device Information in Android

You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).

For instance :

System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK      // API Level
android.os.Build.DEVICE           // Device
android.os.Build.MODEL            // Model 
android.os.Build.PRODUCT          // Product

Etc...

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

You could use serialize

<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">

But best way in this case use the json_encode method in your blade and json_decode in controller.

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

Unity Scripts edited in Visual studio don't provide autocomplete

  1. Select project in Visual Studio
  2. Click "Refresh" button

enter image description here

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

If you are running the

mvn spring-boot:run

from the command line, make sure you are in the directory that contains the pom.xml file. Otherwise, you will run into the No plugin found for prefix 'spring-boot' in the current project and in the plugin groups error.

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Single Result from Database by using mySQLi

Use mysqli_fetch_row(). Try this,

$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row   = mysqli_fetch_row($result);

$ssfullname = $row['ssfullname'];
$ssemail    = $row['ssemail'];

ASP.NET MVC - Set custom IIdentity or IPrincipal

MVC provides you with the OnAuthorize method that hangs from your controller classes. Or, you could use a custom action filter to perform authorization. MVC makes it pretty easy to do. I posted a blog post about this here. http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

Delete an element from a dictionary

pop mutates the dictionary.

 >>> lol = {"hello": "gdbye"}
 >>> lol.pop("hello")
     'gdbye'
 >>> lol
     {}

If you want to keep the original you could just copy it.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

To state the obvious, the cup represents outerScopeVar.

Asynchronous functions be like...

asynchronous call for coffee

Add a dependency in Maven

I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.

If yes, then this is what you want to read.

And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)

How to prevent Browser cache on Angular 2 site?

I had similar issue with the index.html being cached by the browser or more tricky by middle cdn/proxies (F5 will not help you).

I looked for a solution which verifies 100% that the client has the latest index.html version, luckily I found this solution by Henrik Peinar:

https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c

The solution solve also the case where the client stays with the browser open for days, the client checks for updates on intervals and reload if newer version deployd.

The solution is a bit tricky but works like a charm:

  • use the fact that ng cli -- prod produces hashed files with one of them called main.[hash].js
  • create a version.json file that contains that hash
  • create an angular service VersionCheckService that checks version.json and reload if needed.
  • Note that a js script running after deployment creates for you both version.json and replace the hash in angular service, so no manual work needed, but running post-build.js

Since Henrik Peinar solution was for angular 4, there were minor changes, I place also the fixed scripts here:

VersionCheckService :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class VersionCheckService {
    // this will be replaced by actual hash post-build.js
    private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';

    constructor(private http: HttpClient) {}

    /**
     * Checks in every set frequency the version of frontend application
     * @param url
     * @param {number} frequency - in milliseconds, defaults to 30 minutes
     */
    public initVersionCheck(url, frequency = 1000 * 60 * 30) {
        //check for first time
        this.checkVersion(url); 

        setInterval(() => {
            this.checkVersion(url);
        }, frequency);
    }

    /**
     * Will do the call and check if the hash has changed or not
     * @param url
     */
    private checkVersion(url) {
        // timestamp these requests to invalidate caches
        this.http.get(url + '?t=' + new Date().getTime())
            .subscribe(
                (response: any) => {
                    const hash = response.hash;
                    const hashChanged = this.hasHashChanged(this.currentHash, hash);

                    // If new version, do something
                    if (hashChanged) {
                        // ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
                        // for an example: location.reload();
                        // or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
                    }
                    // store the new hash so we wouldn't trigger versionChange again
                    // only necessary in case you did not force refresh
                    this.currentHash = hash;
                },
                (err) => {
                    console.error(err, 'Could not get version');
                }
            );
    }

    /**
     * Checks if hash has changed.
     * This file has the JS hash, if it is a different one than in the version.json
     * we are dealing with version change
     * @param currentHash
     * @param newHash
     * @returns {boolean}
     */
    private hasHashChanged(currentHash, newHash) {
        if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
            return false;
        }

        return currentHash !== newHash;
    }
}

change to main AppComponent:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    constructor(private versionCheckService: VersionCheckService) {

    }

    ngOnInit() {
        console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
        if (environment.versionCheckUrl) {
            this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
        }
    }

}

The post-build script that makes the magic, post-build.js:

const path = require('path');
const fs = require('fs');
const util = require('util');

// get application version from package.json
const appVersion = require('../package.json').version;

// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);

console.log('\nRunning post-build tasks');

// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');

let mainHash = '';
let mainBundleFile = '';

// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;

// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
  .then(files => {
    mainBundleFile = files.find(f => mainBundleRegexp.test(f));

    if (mainBundleFile) {
      let matchHash = mainBundleFile.match(mainBundleRegexp);

      // if it has a hash in it's name, mark it down
      if (matchHash.length > 1 && !!matchHash[1]) {
        mainHash = matchHash[1];
      }
    }

    console.log(`Writing version and hash to ${versionFilePath}`);

    // write current version and hash into the version.json file
    const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
    return writeFile(versionFilePath, src);
  }).then(() => {
    // main bundle file not found, dev build?
    if (!mainBundleFile) {
      return;
    }

    console.log(`Replacing hash in the ${mainBundleFile}`);

    // replace hash placeholder in our main.js file so the code knows it's current hash
    const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
    return readFile(mainFilepath, 'utf8')
      .then(mainFileData => {
        const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
        return writeFile(mainFilepath, replacedFile);
      });
  }).catch(err => {
    console.log('Error with post build:', err);
  });

simply place the script in (new) build folder run the script using node ./build/post-build.js after building dist folder using ng build --prod

String.Format not work in TypeScript

I solved it like this;

1.Created a function

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}

2.Used it like the following;

FormatString("{0} is {1} {2}", "This", "formatting", "hack");

Laravel 5: Display HTML with Blade

For laravel 5

{!!html_entity_decode($text)!!}

Figured out through this link, see RachidLaasri answer

How to create a .gitignore file

There is a pretty simple way to create a .gitignore file.This one is created in github and I'm pretty sure that most source controls offer the feature for creating a file there itself.Attaching an image by image tutorial for reference.

1.enter image description here

2.enter image description here

3.enter image description here

4.enter image description here

Rendering a template variable as HTML

You can render a template in your code like so:

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

See the Django docs for further information.

How can I split a text into sentences?

This function can split the entire text of Huckleberry Finn into sentences in about 0.1 seconds and handles many of the more painful edge cases that make sentence parsing non-trivial e.g. "Mr. John Johnson Jr. was born in the U.S.A but earned his Ph.D. in Israel before joining Nike Inc. as an engineer. He also worked at craigslist.org as a business analyst."

# -*- coding: utf-8 -*-
import re
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov)"

def split_into_sentences(text):
    text = " " + text + "  "
    text = text.replace("\n"," ")
    text = re.sub(prefixes,"\\1<prd>",text)
    text = re.sub(websites,"<prd>\\1",text)
    if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
    text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
    text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
    text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
    text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
    text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text)
    if "”" in text: text = text.replace(".”","”.")
    if "\"" in text: text = text.replace(".\"","\".")
    if "!" in text: text = text.replace("!\"","\"!")
    if "?" in text: text = text.replace("?\"","\"?")
    text = text.replace(".",".<stop>")
    text = text.replace("?","?<stop>")
    text = text.replace("!","!<stop>")
    text = text.replace("<prd>",".")
    sentences = text.split("<stop>")
    sentences = sentences[:-1]
    sentences = [s.strip() for s in sentences]
    return sentences

Iterate over object keys in node.js

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);