Programs & Examples On #Business rules

Business logic in MVC

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

Thats' the trick...I hope this helps...

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

How to send a GET request from PHP?

Remember that if you are using a proxy you need to do a little trick in your php code:

(PROXY WITHOUT AUTENTICATION EXAMPLE)

<?php
$aContext = array(
    'http' => array(
        'proxy' => 'proxy:8080',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;
?>

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

Unable to cast object of type 'System.DBNull' to type 'System.String`

I suppose you can do it like this:

string accountNumber = DBSqlHelperFactory.ExecuteScalar(...) as string;

If accountNumber is null it means it was DBNull not string :)

Regex Last occurrence?

What about this regex: \\[^\\]+$

Submit button not working in Bootstrap form

Replace this

 <button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">

with

<button  value=" Send" class="btn btn-success" type="submit" id="submit">

Questions every good .NET developer should be able to answer?

Good questions I have been asked are

  • What do you think is good about .NET?
  • What do you think is bad about .NET?

It would be interesting to see what a candidate would come up with and you'll certainly learn quite a bit about how he/she uses the framework.

How to calculate the median of an array?

public static int median(int[] arr) {
int median = 0;
java.util.Arrays.sort(arr);
        
for (int i=0;i<arr.length;i++) {
            
    if (arr.length % 2 == 1) {
        median = Math.round(arr[arr.length/2]);
    } else {
        median = (arr[(arr.length/2)] + arr[(arr.length/2)-1])/2;
    }
}
return median;

}

Working copy XXX locked and cleanup failed in SVN

SVN normally updates its internal structure (.svn/prop-base) of the files in a folder before the actual files is fetched from repository. Once the files are fetched this will be cleared up. Frequently the error is thrown because the "update" failed or prematurely cancelled during the update progress.

  1. Check any files are listed under .svn/prop-base directory
  2. Remove any files which are not under the folder
  3. Cleanup
  4. Update

Now the update should work.

How to compare strings in C conditional preprocessor-directives

As already stated above, the ISO-C11 preprocessor does not support string comparison. However, the problem of assigning a macro with the “opposite value” can be solved with “token pasting” and “table access”. Jesse’s simple concatenate/stringify macro-solution fails with gcc 5.4.0 because the stringization is done before the evaluation of the concatenation (conforming to ISO C11). However, it can be fixed:

#define P_(user) user ## _VS
#define VS(user) P_ (user)
#define S(U) S_(U)
#define S_(U) #U

#define jack_VS  queen
#define queen_VS jack

S (VS (jack))
S (jack)
S (VS (queen))
S (queen)

#define USER jack          // jack    or queen, your choice
#define USER_VS USER##_VS  // jack_VS or queen_VS
S (USER)
S (USER_VS)

The first line (macro P_()) adds one indirection to let the next line (macro VS()) finish the concatenation before the stringization (see Why do I need double layer of indirection for macros?). The stringization macros (S() and S_()) are from Jesse.

The table (macros jack_VS and queen_VS) which is much easier to maintain than the if-then-else construction of the OP is from Jesse.

Finally, the next four-line block invokes the function-style macros. The last four-line block is from Jesse’s answer.

Storing the code in foo.c and invoking the preprocessor gcc -nostdinc -E foo.c yields:

# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "foo.c"
# 9 "foo.c"
"queen"
"jack"
"jack"
"queen"



"jack"
"USER_VS"

The output is as expected. The last line shows that the USER_VS macro is not expanded before stringization.

Get a particular cell value from HTML table using JavaScript

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

Linq select to new object

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   

How do I release memory used by a pandas dataframe?

This solves the problem of releasing the memory for me!!!

import gc
import pandas as pd

del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()

the data-frame will be explicitly set to null

in the above statements

Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.

more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/

Why is it string.join(list) instead of list.join(string)?

Think of it as the natural orthogonal operation to split.

I understand why it is applicable to anything iterable and so can't easily be implemented just on list.

For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.

phpmyadmin logs out after 1440 secs

Add this line to /config.inc.php:

$cfg['LoginCookieValidity'] = 36000;

In /setup/lib/index.lib.php

$cf->getValue('LoginCookieValidity') > 36000;

If you don't already have a .htaccess file for your phpMyAdmin site, create one, and add the following line to override the default PHP session timeout:

php_value session.gc_maxlifetime 36000

I would not recommend altering this value in your main php.ini file, as it will allow a ridiculously long session timeout for all your PHP sites.

source: http://www.sitekickr.com/blog/increase-phpmyadmin-timeout/

How to decide when to use Node.js?

It can be used where

  • Applications that are highly event driven & are heavily I/O bound
  • Applications handling a large number of connections to other systems
  • Real-time applications (Node.js was designed from the ground up for real time and to be easy to use.)
  • Applications that juggle scads of information streaming to and from other sources
  • High traffic, Scalable applications
  • Mobile apps that have to talk to platform API & database, without having to do a lot of data analytics
  • Build out networked applications
  • Applications that need to talk to the back end very often

On Mobile front, prime-time companies have relied on Node.js for their mobile solutions. Check out why?

LinkedIn is a prominent user. Their entire mobile stack is built on Node.js. They went from running 15 servers with 15 instances on each physical machine, to just 4 instances – that can handle double the traffic!

eBay launched ql.io, a web query language for HTTP APIs, which uses Node.js as the runtime stack. They were able to tune a regular developer-quality Ubuntu workstation to handle more than 120,000 active connections per node.js process, with each connection consuming about 2kB memory!

Walmart re-engineered its mobile app to use Node.js and pushed its JavaScript processing to the server.

Read more at: http://www.pixelatingbits.com/a-closer-look-at-mobile-app-development-with-node-js/

Ansible - Save registered variable to file

Thanks to tmoschou for adding this comment to an outdated accepted answer:

As of Ansible 2.10, The documentation for ansible.builtin.copy says: 

If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.

For more details see this and an explanation


Original answer:

You can use the copy module, with the parameter content=.

I gave the exact same answer here: Write variable to a file in Ansible

In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action notation:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file

Spring Boot - Loading Initial Data

Here is the way I got that:

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

    /**
     * This event is executed as late as conceivably possible to indicate that
     * the application is ready to service requests.
     */

    @Autowired
    private MovieRepositoryImpl movieRepository;

    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {
        seedData();
    }

    private void seedData() {
        movieRepository.save(new Movie("Example"));

        // ... add more code
    }

}

Thanks to the author of this article:

http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

How to obtain the total numbers of rows from a CSV file in Python?

I think we can improve the best answer a little bit, I'm using:

len = sum(1 for _ in reader)

Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.

how to get data from selected row from datagridview

I was having the same issue and this works excellently.

Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting  
  'Display complete contents in tooltip even though column display cuts off part of it.   
  DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
End Sub

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

If you are using different aspx.cs files that define classes of the same name you can use

<compilation targetFramework="4.5" />

under <system.web> in your web.config file.

Although I would still strongly advise that you would change the class name.

How to handle the modal closing event in Twitter Bootstrap?

If your modal div is dynamically added then use( For bootstrap 3 and 4)

$(document).on('hide.bs.modal','#modal-id', function () {
                alert('');
 //Do stuff here
});

This will work for non-dynamic content also.

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

C# - Insert a variable number of spaces into a string? (Formatting an output file)

I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:

string.Empty.PadRight(totalLength, (char)32);

An alternative approach: Create all spaces manually within a custom method and call it:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

And call it in your code to create white spaces: GetSpaces(14);

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

Textarea onchange detection

I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.

    $('div.lawyerList').on('change','textarea',function(){
      // Change occurred so count chars...
    });

or

    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });

Setting SMTP details for php mail () function

Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider

WPF What is the correct way of using SVG files as icons in WPF

Use the SvgImage or the SvgImageConverter extensions, the SvgImageConverter supports binding. See the following link for samples demonstrating both extensions.

https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples/ControlSamplesWpf

How to get a unique device ID in Swift?

I've tried with

let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString

instead

let UUID = NSUUID().UUIDString

and it works.

How can I bind to the change event of a textarea in jQuery?

bind is deprecated. Use on:

$("#textarea").on('change keyup paste', function() {
    // your code here
});

Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:

var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});

jsFiddle Demo

nvm keeps "forgetting" node in new terminal session

Here is a simple instruction:

1) Install:

nvm install 8.10.0

2) Use once per terminal

nvm use 8.10.0

3) Set up as default for all terminals

nvm alias default 8.10.0

You may need to use root permissions to perform those actions.

And don't forget to check nvm documentation for more info.

Also note that you may need to specify node version for your IDE: enter image description here

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".

Multiline text in JLabel

It is possible to use (basic) CSS in the HTML.


This question was linked from Multiline JLabels - Java.

ActionBar text color

If you need to set the color programmatically this is the way to do it:

static void setActionBarTextColor(Activity activity, int color)
{
      ActionBar actionBar = activity instanceof AppCompatActivity
                    ? ((AppCompatActivity) activity).getSupportActionBar()
                    : activity.getActionBar();
      String title = activity.getTitle(); // or any title you want
      SpannableString ss = new SpannableString(title);
      ss.setSpan(new ForegroundColorSpan(color), 0, title.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      actionBar.setTitle(ss);
}

How to decode jwt token in javascript without using a library?

@Peheje will work, but you will have problem with unicode. To fix it I use the code on https://stackoverflow.com/a/30106551/5277071;

_x000D_
_x000D_
let b64DecodeUnicode = str =>_x000D_
  decodeURIComponent(_x000D_
    Array.prototype.map.call(atob(str), c =>_x000D_
      '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)_x000D_
    ).join(''))_x000D_
_x000D_
let parseJwt = token =>_x000D_
  JSON.parse(_x000D_
    b64DecodeUnicode(_x000D_
      token.split('.')[1].replace('-', '+').replace('_', '/')_x000D_
    )_x000D_
  )_x000D_
_x000D_
_x000D_
let form = document.getElementById("form")_x000D_
form.addEventListener("submit", (e) => {_x000D_
   form.out.value = JSON.stringify(_x000D_
      parseJwt(form.jwt.value)_x000D_
   )_x000D_
   e.preventDefault();_x000D_
})
_x000D_
textarea{width:300px; height:60px; display:block}
_x000D_
<form id="form" action="parse">_x000D_
  <textarea name="jwt">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA</textarea>_x000D_
  <textarea name="out"></textarea>_x000D_
  <input type="submit" value="parse" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

Javascript get object key name

An ES6 update... though both filter and map might need customization.

Object.entries(theObj) returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values() separately.

_x000D_
_x000D_
const buttons = {_x000D_
    button1: {_x000D_
        text: 'Close',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button2: {_x000D_
        text: 'OK',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button3: {_x000D_
        text: 'Cancel',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
    _x000D_
console.log(list)
_x000D_
_x000D_
_x000D_

EXCEL VBA Check if entry is empty or not 'space'

Most terse version I can think of

Len(Trim(TextBox1.Value)) = 0

If you need to do this multiple times, wrap it in a function

Public Function HasContent(text_box as Object) as Boolean
    HasContent = (Len(Trim(text_box.Value)) > 0)
End Function

Usage

If HasContent(TextBox1) Then
    ' ...

Undo scaffolding in Rails

If you just want to see the files a generator will create you can pass the generator --pretend or -p option.

Calling a PHP function from an HTML form in the same file

That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.

To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.

How do I test a private function or a class that has private methods, fields or inner classes?

Generally a unit test is intended to exercise the public interface of a class or unit. Therefore, private methods are implementation detail that you would not expect to test explicitly.

Synchronous XMLHttpRequest warning and <script>

I was plagued by this error message despite using async: true. It turns out the actual problem was using the success method. I changed this to done and warning is gone.

success: function(response) { ... }

replaced with:

done: function(response) { ... }

What does jQuery.fn mean?

fn literally refers to the jquery prototype.

This line of code is in the source code:

jQuery.fn = jQuery.prototype = {
 //list of functions available to the jQuery api
}

But the real tool behind fn is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this will refer to the jquery object.

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};

So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.

jsFiddle Demo

$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

Now you can use those against a class like this:

$('.blue').blueBorder().blueText();

(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)

This answer has a good example of a full fledged extension.

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}

How to get the separate digits of an int number?

see bellow my proposal with comments

          int size=i.toString().length(); // the length of the integer (i) we need to split;
           ArrayList<Integer> li = new ArrayList<Integer>(); // an ArrayList in whcih to store the resulting digits

        Boolean b=true; // control variable for the loop in which we will reatrive step by step the digits
        String number="1"; // here we will add the leading zero depending on the size of i
        int temp;  // the resulting digit will be kept by this temp variable

    for (int j=0; j<size; j++){
                        number=number.concat("0");
                    }

Integer multi = Integer.valueOf(number); // the variable used for dividing step by step the number we received 
                while(b){

                    multi=multi/10;
                    temp=i/(multi);
                    li.add(temp);
                    i=i%(multi);
                                        if(i==0){
                                        b=false;
                                        }


                }

                for(Integer in: li){
                    System.out.print(in.intValue()+ " ");
                }

Get value of c# dynamic property via string

Once you have your PropertyInfo (from GetProperty), you need to call GetValue and pass in the instance that you want to get the value from. In your case:

d.GetType().GetProperty("value2").GetValue(d, null);

How to redirect to Login page when Session is expired in Java web application?

When the use logs in, put its username in the session:

`session.setAttribute("USER", username);`

At the beginning of each page you can do this:

<%
String username = (String)session.getAttribute("USER");
if(username==null) 
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<% { } %>

Calculate relative time in C#

I would recommend computing this on the client side too. Less work for the server.

The following is the version that I use (from Zach Leatherman)

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str){
        var time_formats = [
                [60, 'just now'],
                [90, '1 minute'], // 60*1.5
                [3600, 'minutes', 60], // 60*60, 60
                [5400, '1 hour'], // 60*60*1.5
                [86400, 'hours', 3600], // 60*60*24, 60*60
                [129600, '1 day'], // 60*60*24*1.5
                [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                [907200, '1 week'], // 60*60*24*7*1.5
                [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                [47304000, '1 year'], // 60*60*24*365*1.5
                [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                [4730400000, '1 century'] // 60*60*24*365*100*1.5
        ];

        var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                dt = new Date,
                seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                token = ' ago',
                i = 0,
                format;

        if (seconds < 0) {
                seconds = Math.abs(seconds);
                token = '';
        }

        while (format = time_formats[i++]) {
                if (seconds < format[0]) {
                        if (format.length == 2) {
                                return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                        } else {
                                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                        }
                }
        }

        // overflow for centuries
        if(seconds > 4730400000)
                return Math.round(seconds / 4730400000) + ' centuries' + token;

        return date_str;
};

if(typeof jQuery != 'undefined') {
        jQuery.fn.humane_dates = function(){
                return this.each(function(){
                        var date = humane_date(this.title);
                        if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                jQuery(this).text(date);
                });
        };
}

How can the size of an input text box be defined in HTML?

You can set the width in pixels via inline styling:

<input type="text" name="text" style="width: 195px;">

You can also set the width with a visible character length:

<input type="text" name="text" size="35">

Ignoring upper case and lower case in Java

The .equalsIgnoreCase() method should help with that.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

In VBA get rid of the case sensitivity when comparing words?

If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.

If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.

Convert hex color value ( #ffffff ) to integer value

I was facing the same problem. This way I was able to solved it. As CQM said, using Color.parseColor() is a good solution to this issue.

Here is the code I used:

this.Button_C.setTextColor(Color.parseColor(prefs.getString("color_prefs", String.valueOf(R.color.green))));

In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs).

Send response to all clients except sender

Other cases

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

How to make JQuery-AJAX request synchronous

It's as simple as the one below, and works like a charm.

My solution perfectly answers your question: How to make JQuery-AJAX request synchronous

Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

$.ajaxSetup({async: false});

$ajax({ajax call....});

$.ajaxSetup({async: true});

In your case it would look like this:

$.ajaxSetup({async: false});

$.ajax({
        type: "POST",
        async: "false",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            if(arr == "Successful") {
                return true;
            } else {
                return false;
            }
        }
    });


$.ajaxSetup({async: true});

I hope it helps :)

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

The link above is rather outdated. For WebLogic 12c you may define the transaction timout in a transaction-descriptor for each EJB in the WebLogic deployment descriptor weblogic-ejb-jar.xml, see weblogic-ejb-jar.xml Deployment Descriptor Reference.

For a message driven been it looks like this:

<weblogic-enterprise-bean>
    <ejb-name>TestMessageBeanLow</ejb-name>
    <message-driven-descriptor>
        <pool>
            <max-beans-in-free-pool>1</max-beans-in-free-pool>
        </pool>
        <destination-jndi-name>jms/ActiveMQ/TestRequestQueue_LOW</destination-jndi-name>
        <connection-factory-jndi-name>jms/ActiveMQ/TestConnectionFactory</connection-factory-jndi-name>
    </message-driven-descriptor>
    <transaction-descriptor>
        <trans-timeout-seconds>60</trans-timeout-seconds>
    </transaction-descriptor>
    <resource-description>
        <res-ref-name>jms/ConnectionFactory</res-ref-name>
        <jndi-name>jms/ActiveMQ/TestConnectionFactory</jndi-name>
    </resource-description>
</weblogic-enterprise-bean>

Pass array to MySQL stored routine

I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.

-- *****************************************************************************
-- test_PVreplace

DROP FUNCTION IF EXISTS test_PVreplace;

delimiter //
CREATE FUNCTION test_PVreplace (
   str TEXT,   -- String to do search'n'replace on
   pv TEXT     -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
   )
   RETURNS TEXT

-- Replace specific tags with specific values.

sproc:BEGIN
   DECLARE idx INT;
   DECLARE idx0 INT DEFAULT 1;   -- 1-origined, not 0-origined
   DECLARE len INT;
   DECLARE sPV TEXT;
   DECLARE iPV INT;
   DECLARE sP TEXT;
   DECLARE sV TEXT;

   -- P/V string *must* end with a delimiter.

   IF (RIGHT (pv, 1) <> '|') THEN
      SET pv = CONCAT (pv, '|');
      END IF;

   -- Find all the P/V pairs.

   SELECT LOCATE ('|', pv, idx0) INTO idx;
   WHILE (idx > 0) DO
      SET len = idx - idx0;
      SELECT SUBSTRING(pv, idx0, len) INTO sPV;

      -- Found a P/V pair.  Break it up.

      SELECT LOCATE ('=', sPV) INTO iPV;
      IF (iPV = 0) THEN
         SET sP = sPV;
         SET sV = '';
      ELSE
         SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
         SELECT SUBSTRING(sPV, iPV+1) INTO sV;
         END IF;

      -- Do the substitution(s).

      SELECT REPLACE (str, sP, sV) INTO str;

      -- Do next P/V pair.

      SET idx0 = idx + 1;
      SELECT LOCATE ('|', pv, idx0) INTO idx;
      END WHILE;
   RETURN (str);
END//
delimiter ;

SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');

.ssh/config file for windows (git)

There is an option IdentityFile which you can use in your ~/.ssh/config file and specify key file for each host.

Host host_with_key1.net
  IdentityFile ~/.ssh/id_rsa

Host host_with_key2.net
  IdentityFile ~/.ssh/id_rsa_test

More info: http://linux.die.net/man/5/ssh_config

Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/

Moving up one directory in Python

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'

Java Long primitive type maximum limit

It will overflow and wrap around to Long.MIN_VALUE.

Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

https://nodejs.org/download/ . The page has Windows Installer (.msi) as well as other installers and binaries.Download and install for windows.

Node.js comes with NPM.

NPM is located in the directory where Node.js is installed.

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

String strip() for JavaScript?

If you're already using jQuery, then you may want to have a look at jQuery.trim() which is already provided with jQuery.

What is the difference between UTF-8 and ISO-8859-1?

UTF

UTF is a family of multi-byte encoding schemes that can represent Unicode code points which can be representative of up to 2^31 [roughly 2 billion] characters. UTF-8 is a flexible encoding system that uses between 1 and 4 bytes to represent the first 2^21 [roughly 2 million] code points.

Long story short: any character with a code point/ordinal representation below 127, aka 7-bit-safe ASCII is represented by the same 1-byte sequence as most other single-byte encodings. Any character with a code point above 127 is represented by a sequence of two or more bytes, with the particulars of the encoding best explained here.

ISO-8859

ISO-8859 is a family of single-byte encoding schemes used to represent alphabets that can be represented within the range of 127 to 255. These various alphabets are defined as "parts" in the format ISO-8859-n, the most familiar of these likely being ISO-8859-1 aka 'Latin-1'. As with UTF-8, 7-bit-safe ASCII remains unaffected regardless of the encoding family used.

The drawback to this encoding scheme is its inability to accommodate languages comprised of more than 128 symbols, or to safely display more than one family of symbols at one time. As well, ISO-8859 encodings have fallen out of favor with the rise of UTF. The ISO "Working Group" in charge of it having disbanded in 2004, leaving maintenance up to its parent subcommittee.

Switch case on type c#

The simplest thing to do could be to use dynamics, i.e. you define the simple methods like in Yuval Peled answer:

void Test(WebControl c)
{
...
}

void Test(ComboBox c)
{
...
}

Then you cannot call directly Test(obj), because overload resolution is done at compile time. You have to assign your object to a dynamic and then call the Test method:

dynamic dynObj = obj;
Test(dynObj);

How do I parse JSON with Ruby on Rails?

The Oj gem (https://github.com/ohler55/oj) should work. It's simple and fast.

http://www.ohler.com/oj/#Simple_JSON_Writing_and_Parsing_Example

require 'oj'

h = { 'one' => 1, 'array' => [ true, false ] }
json = Oj.dump(h)

# json =
# {
#   "one":1,
#   "array":[
#     true,
#     false
#   ]
# }

h2 = Oj.load(json)
puts "Same? #{h == h2}"
# true

The Oj gem won't work for JRuby. For JRuby this (https://github.com/ralfstx/minimal-json) or this (https://github.com/clojure/data.json) may be good options.

Brew doctor says: "Warning: /usr/local/include isn't writable."

What worked for me was

$ sudo chown -R yourname:admin /usr/local/bin

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

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

To list all the process running on port 8080 do the following.

netstat -ano | find "8080"

TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       10612

TCP    [::]:8080              [::]:0                 LISTENING       10612

Then to kill the process run the following command

taskkill /F /PID 10612

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

How to exclude property from Json Serialization

If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.

Using the Javascript Serializer

    public static class JsonSerializerExtensions
    {
        public static string ToJsonString(this object target,bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            if(ignoreNulls)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
            }
            return javaScriptSerializer.Serialize(target);
        }

        public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
        {
            var javaScriptSerializer = new JavaScriptSerializer();
            foreach (var key in ignore.Keys)
            {
                javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
            }
            return javaScriptSerializer.Serialize(target);
        }
    }


public class PropertyExclusionConverter : JavaScriptConverter
    {
        private readonly List<string> propertiesToIgnore;
        private readonly Type type;
        private readonly bool ignoreNulls;

        public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
        {
            this.ignoreNulls = ignoreNulls;
            this.type = type;
            this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
        }

        public PropertyExclusionConverter(Type type, bool ignoreNulls)
            : this(type, null, ignoreNulls){}

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            var result = new Dictionary<string, object>();
            if (obj == null)
            {
                return result;
            }
            var properties = obj.GetType().GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
                {
                    if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
                    {
                         continue;
                    }
                    result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
                }
            }
            return result;
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
        }
    }

Spring Data JPA map the native query result to Non-Entity POJO

I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping is inconvienient and makes your code ugly :).

An example right from spring data JPA source code:

public interface UserRepository extends JpaRepository<User, Integer> {

   @Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
   NameOnly findByNativeQuery(Integer id);

   public static interface NameOnly {

     String getFirstname();

     String getLastname();

  }
}

You can also use this method to get a list of projections.

Check out this spring data JPA docs entry for more info about projections.

Note 1:

Remember to have your User entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname() might return value of last name et cetera).

Note 2:

If you use SELECT table.column ... notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):

@Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

But this works fine:

@Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);

In case of more complex queries I'd rather use JdbcTemplate with custom repository instead.

What's the difference between StaticResource and DynamicResource in WPF?

Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. You can abstract away entire control using static resources.

Static resources are used under following circumstances:

  1. When reaction resource changes at runtime is not required.
  2. If you need a good performance with lots of resources.
  3. While referencing resources within the same dictionary.

Dynamic resources:

  1. Value of property or style setter theme is not known until runtime
    • This include system, aplication, theme based settings
    • This also includes forward references.
  2. Referencing large resources that may not load when page, windows, usercontrol loads.
  3. Referencing theme styles in a custom control.

javascript /jQuery - For Loop

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}

?: ?? Operators Instead Of IF|ELSE

If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.

if (Source == value) return;
Source = value;
RaisePropertyChanged("Source");

How do you return the column names of a table?

I use

SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

I also had this issue. Tried different things. But finally

conda install opencv

worked for me.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi and clicking on Enable. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.

How do I get only directories using Get-ChildItem?

From PowerShell v2 and newer (k represents the folder you are beginning your search at):

Get-ChildItem $Path -attributes D -Recurse

If you just want folder names only, and nothing else, use this:

Get-ChildItem $Path -Name -attributes D -Recurse

If you are looking for a specific folder, you could use the following. In this case, I am looking for a folder called myFolder:

Get-ChildItem $Path -attributes D -Recurse -include "myFolder"

How do I find duplicates across multiple columns?

Using count(*) over(partition by...) provides a simple and efficient means to locate unwanted repetition, whilst also list all affected rows and all wanted columns:

SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city

While most recent RDBMS versions support count(*) over(partition by...) MySQL V 8.0 introduced "window functions", as seen below (in MySQL 8.0)

CREATE TABLE stuff(
   id   INTEGER  NOT NULL
  ,name VARCHAR(60) NOT NULL
  ,city VARCHAR(60) NOT NULL
);
INSERT INTO stuff(id,name,city) VALUES 
  (904834,'jim','London')
, (904835,'jim','London')
, (90145,'Fred','Paris')
, (90132,'Fred','Paris')
, (90133,'Fred','Paris')

, (923457,'Barney','New York') # not expected in result
;
SELECT
    t.*
FROM (
    SELECT
        s.*
      , COUNT(*) OVER (PARTITION BY s.name, s.city) AS qty
    FROM stuff s
    ) t
WHERE t.qty > 1
ORDER BY t.name, t.city
    id | name | city   | qty
-----: | :--- | :----- | --:
 90145 | Fred | Paris  |   3
 90132 | Fred | Paris  |   3
 90133 | Fred | Paris  |   3
904834 | jim  | London |   2
904835 | jim  | London |   2

db<>fiddle here

Window functions. MySQL now supports window functions that, for each row from a query, perform a calculation using rows related to that row. These include functions such as RANK(), LAG(), and NTILE(). In addition, several existing aggregate functions now can be used as window functions; for example, SUM() and AVG(). For more information, see Section 12.21, “Window Functions”.

Python decorators in classes

Would something like this do what you need?

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

test = Test()

test.bar()

This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method.

>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>> 

edited to answer question in comments:

How to use the hidden decorator in another class

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

    _decorator = staticmethod( _decorator )

class TestB( Test ):
    @Test._decorator
    def bar( self ):
        print "override bar in"
        super( TestB, self ).bar()
        print "override bar out"

print "Normal:"
test = Test()
test.bar()
print

print "Inherited:"
b = TestB()
b.bar()
print

Output:

Normal:
start magic
normal call
end magic

Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic

Command to escape a string in bash

In Bash:

printf "%q" "hello\world" | someprog

for example:

printf "%q" "hello\world"
hello\\world

This could be used through variables too:

printf -v var "%q\n" "hello\world"
echo "$var"
hello\\world

Use Ant for running program with command line arguments

What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:

In my build.xml:

<target name="printclasspath">
    <pathconvert property="classpathProp" refid="project.class.path"/>
    <echo>${classpathProp}</echo>
</target>

In another script called 'run.sh':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \  -f 7):build
java "$@"

It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.

I think it's a shame there's not some option in ant whereby you could do something like:

ant -- arg1 arg2 arg3

mpirun uses this type of syntax; ssh also can use this syntax I think.

Example: Communication between Activity and Service using Messaging

Note: You don't need to check if your service is running, CheckIfServiceIsRunning(), because bindService() will start it if it isn't running.

Also: if you rotate the phone you don't want it to bindService() again, because onCreate() will be called again. Be sure to define onConfigurationChanged() to prevent this.

CR LF notepad++ removal

Please find the below screenshot

enter image description here

enter image description here

JavaScript get window X/Y position for scroll

function FastScrollUp()
{
     window.scroll(0,0)
};

function FastScrollDown()
{
     $i = document.documentElement.scrollHeight ; 
     window.scroll(0,$i)
};
 var step = 20;
 var h,t;
 var y = 0;
function SmoothScrollUp()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, -step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollUp()},20);

};


function SmoothScrollDown()
{
     h = document.documentElement.scrollHeight;
     y += step;
     window.scrollBy(0, step)
     if(y >= h )
       {clearTimeout(t); y = 0; return;}
     t = setTimeout(function(){SmoothScrollDown()},20);

}

Tried to Load Angular More Than Once

I was also facing such an issue where I was continously getting an infinite loop and the page was reloading itself infinitely. After a bit of debugging I found out that the error was being caused because, angular was not able to load template given with a particular id because the template was not present in that file.

Be careful with the url's which you give in angular apps. If its not correct, angular can just keep on looking for it eventually, leading to infinite loop!

Hope this helps!

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.

How to join multiple lines of file names into one with custom delimiter?

The combination of setting IFS and use of "$*" can do what you want. I'm using a subshell so I don't interfere with this shell's $IFS

(set -- *; IFS=,; echo "$*")

To capture the output,

output=$(set -- *; IFS=,; echo "$*")

How to save final model using keras?

you can save the model in json and weights in a hdf5 file format.

# keras library import  for Saving and loading model and weights

from keras.models import model_from_json
from keras.models import load_model

# serialize model to JSON
#  the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()


with open("model_num.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model_num.h5")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

# load json and create model
json_file = open('model_num.json', 'r')

loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")

loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')

To predict for different data you can use this

loaded_model.predict_classes("your_test_data here")

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

How to Convert datetime value to yyyymmddhhmmss in SQL server?

This seems to work:

declare @d datetime
set @d = '2014-04-17 13:55:12'

select replace(convert(varchar(8), @d, 112)+convert(varchar(8), @d, 114), ':','') 

Result:

20140417135512

Android : Check whether the phone is dual SIM

I am able to read both the IMEI's from OnePlus 2 Phone

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
                Log.i(TAG, "Default device ID " + manager.getDeviceId());
                Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
                Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
            }

How to capture Enter key press?

_x000D_
_x000D_
 // jquery press check by Abdelhamed Mohamed_x000D_
_x000D_
_x000D_
    $(document).ready(function(){_x000D_
    $("textarea").keydown(function(event){_x000D_
        if (event.keyCode == 13) {_x000D_
         // do something here_x000D_
         alert("You Pres Enter");_x000D_
        }_x000D_
       });_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <textarea></textarea>
_x000D_
_x000D_
_x000D_

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

How to set multiple commands in one yaml file with Kubernetes?

Just to bring another possible option, secrets can be used as they are presented to the pod as volumes:

Secret example:

apiVersion: v1
kind: Secret 
metadata:
  name: secret-script
type: Opaque
data:
  script_text: <<your script in b64>>

Yaml extract:

....
containers:
    - name: container-name
      image: image-name
      command: ["/bin/bash", "/your_script.sh"]
      volumeMounts:
        - name: vsecret-script
          mountPath: /your_script.sh
          subPath: script_text
....
  volumes:
    - name: vsecret-script
      secret:
        secretName: secret-script

I know many will argue this is not what secrets must be used for, but it is an option.

Exit Shell Script Based on Process Exit Code

If you just call exit in Bash without any parameters, it will return the exit code of the last command. Combined with OR, Bash should only invoke exit, if the previous command fails. But I haven't tested this.

command1 || exit;
command2 || exit;

Bash will also store the exit code of the last command in the variable $?.

Types in MySQL: BigInt(20) vs Int(20)

Let's give an example for int(10) one with zerofill keyword, one not, the table likes that:

create table tb_test_int_type(
    int_10 int(10),
    int_10_with_zf int(10) zerofill,
    unit int unsigned
);

Let's insert some data:

insert into tb_test_int_type(int_10, int_10_with_zf, unit)
values (123456, 123456,3147483647), (123456, 4294967291,3147483647) 
;

Then

select * from tb_test_int_type; 

# int_10, int_10_with_zf, unit
'123456', '0000123456', '3147483647'
'123456', '4294967291', '3147483647'

We can see that

  • with keyword zerofill, num less than 10 will fill 0, but without zerofill it won't

  • Secondly with keyword zerofill, int_10_with_zf becomes unsigned int type, if you insert a minus you will get error Out of range value for column...... But you can insert minus to int_10. Also if you insert 4294967291 to int_10 you will get error Out of range value for column.....

Conclusion:

  1. int(X) without keyword zerofill, is equal to int range -2147483648~2147483647

  2. int(X) with keyword zerofill, the field is equal to unsigned int range 0~4294967295, if num's length is less than X it will fill 0 to the left

How to initialize weights in PyTorch?

Sorry for being so late, I hope my answer will help.

To initialise weights with a normal distribution use:

torch.nn.init.normal_(tensor, mean=0, std=1)

Or to use a constant distribution write:

torch.nn.init.constant_(tensor, value)

Or to use an uniform distribution:

torch.nn.init.uniform_(tensor, a=0, b=1) # a: lower_bound, b: upper_bound

You can check other methods to initialise tensors here

Switch android x86 screen resolution

To change the Android-x86 screen resolution on VirtualBox you need to:

  1. Add custom screen resolution:
    Android <6.0:

    VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x16"
    

    Android >=6.0:

    VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"
    
  2. Figure out what is the ‘hex’-value for your VideoMode:
    2.1. Start the VM
    2.2. In GRUB menu enter a (Android >=6.0: e)
    2.3. In the next screen append vga=ask and press Enter
    2.4. Find your resolution and write down/remember the 'hex'-value for Mode column

  3. Translate the value to decimal notation (for example 360 hex is 864 in decimal).

  4. Go to menu.lst and modify it:
    4.1. From the GRUB menu select Debug Mode
    4.2. Input the following:

    mount -o remount,rw /mnt  
    cd /mnt/grub  
    vi menu.lst
    

    4.3. Add vga=864 (if your ‘hex’-value is 360). Now it should look like this:

    kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode DPI=160 UVESA_MODE=320x480 SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img vga=864

    4.4. Save it:

    :wq
    
  5. Unmount and reboot:

    cd /
    umount /mnt
    reboot -f
    

Hope this helps.

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

PostgreSQL: Why psql can't connect to server?

Just want to make a small addition: if your instance is complaining on a socket, you can also check unix_socket_directories at /data/postgresql.conf file which could have been set to /tmp, for example, if you have used a 3rd party distribution. You can change it to /var/run/postgresql and restart the service. That may also require creating a postgresql dir at /var/run and subsys/postgresql-9.6 at /var/lock if those doesn't already exist (worked for me with postgresql 9.6).

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

CSS3 gradient background set on body doesn't stretch but instead repeats?

Apply the following CSS:

html {
    height: 100%;
}
body {
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

Edit: Added margin: 0; to body declaration per comments (Martin).

Edit: Added background-attachment: fixed; to body declaration per comments (Johe Green).

Git - Undo pushed commits

You can do something like

git push origin +<short_commit_sha>^:<branch_name>

Seaborn plots not showing up

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

What port is used by Java RMI connection?

All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.

If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.

  • In the case where your remote object extends UnicastRemoteObject, have its constructor call super(port) with some non-zero port number.

  • In the case where it doesn't extend UnicastRemoteObject, provide a non-zero port number to UnicastRemoteObject.exportObject().

There are several wrinkles to this.

  • If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry(). So if you create a Registry on port 1099, all other objects exported from that JVM can share port 1099.

  • If you are using socket factories, your RMIServerSocketFactory must have a sensible implementation of equals() for port sharing to work, i.e. one that doesn't just rely on object identity via == or Object.equals().

  • If either you don't provide a server socket factory, or you do provide one with a sensible equals() method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099) followed by any number of super(1099) or exportObject(..., 1099) calls.

JavaFX 2.1 TableView refresh items

?????????TableColumn?visable???????databinding???,???JavaFX?bug????????,?????Java8??????

??trace JavaFX ?source code?,?????bug???Listener????????????????JFace??PropertyChangeSupport????POJO?????????????DoubleProperty ??WritableObjectValue,???????

                                                           ???????

I had firmed use change Column Visable Property is not conform data binding automation purpose.

After I traced JavaFX TableView source code. I never discovered any problem code for Tableview binding issue. After 4 weeks ago, I changed POJO field's type from DoubleProperty to WritableObjectValue, problem was solved.

                                               resolve in Taiwan Taipei.

Sample code:

public class CostAnalytics{
protected WritableObjectValue<Double> subtotal=new SimpleObjectProperty<Double>();//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
//...
public void setQuantity(double quantity) {
    this.pcs.firePropertyChange("quantity", this.quantity, quantity);
    this.quantity.set(quantity);
    this.calsSubtotal();
}
public WritableObjectValue<Double> getSubtotal() {//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
    return subtotal;
}
///...
}


TableColumn<CostAnalytics, Double> subtotal = new TableColumn<CostAnalytics, Double>(
            "??");
subtotal.setCellValueFactory(new Callback<CellDataFeatures<CostAnalytics, Double>, ObservableValue<Double>>() {

        public ObservableValue<Double> call(
                CellDataFeatures<CostAnalytics, Double> p) {
            WritableObjectValue<Double> result = p.getValue().getSubtotal();// //??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
            // return (ObservableValue<Double>)
            // result;//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
            // return new
            // ReadOnlyObjectWrapper<Double>(p.getValue().getSubtotal());//????????
            return (ObservableValue<Double>) p.getValue().getSubtotal();// ??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
        }

    });

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

How do I import the javax.servlet API in my Eclipse project?

Ensure you've the right Eclipse and Server

Ensure that you're using at least Eclipse IDE for Enterprise Java developers (with the Enterprise). It contains development tools to create dynamic web projects and easily integrate servletcontainers (those tools are part of Web Tools Platform, WTP). In case you already had Eclipse IDE for Java (without Enterprise), and manually installed some related plugins, then chances are that it wasn't done properly. You'd best trash it and grab the real Eclipse IDE for Enterprise Java one.

You also need to ensure that you already have a servletcontainer installed on your machine which implements at least the same Servlet API version as the servletcontainer in the production environment, for example Apache Tomcat, Oracle GlassFish, JBoss AS/WildFly, etc. Usually, just downloading the ZIP file and extracting it is sufficient. In case of Tomcat, do not download the EXE format, that's only for Windows based production environments. See also a.o. Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use.

A servletcontainer is a concrete implementation of the Servlet API. Note that the Java EE SDK download at Oracle.com basically contains GlassFish. So if you happen to already have downloaded Java EE SDK, then you basically already have GlassFish. Also note that for example GlassFish and JBoss AS/WildFly are more than just a servletcontainer, they also supports JSF, EJB, JPA and all other Java EE fanciness. See also a.o. What exactly is Java EE?


Integrate Server in Eclipse and associate it with Project

Once having installed both Eclipse for Enterprise Java and a servletcontainer on your machine, do the following steps in Eclipse:

  1. Integrate servletcontainer in Eclipse

    a. Via Servers view

    • Open the Servers view in the bottom box.

    • Rightclick there and choose New > Server.

    • Pick the appropriate servletcontainer make and version and walk through the wizard.

      enter image description here

    b. Or, via Eclipse preferences

    • Open Window > Preferences > Server > Runtime Environments.

    • You can Add, Edit and Remove servers here.

      enter image description here

  2. Associate server with project

    a. In new project

    • Open the Project Navigator/Explorer on the left hand side.

    • Rightclick there and choose New > Project and then in menu Web > Dynamic Web Project.

    • In the wizard, set the Target Runtime to the integrated server.

      enter image description here

    b. Or, in existing project

    • Rightclick project and choose Properties.

    • In Targeted Runtimes section, select the integrated server.

      enter image description here

    Either way, Eclipse will then automatically take the servletcontainer's libraries in the build path. This way you'll be able to import and use the Servlet API.


Never carry around loose server-specific JAR files

You should in any case not have the need to fiddle around in the Build Path property of the project. You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar, jsp-api.jar, el-api.jar, j2ee.jar, javaee.jar, etc. It would only lead to future portability, compatibility, classpath and maintainability troubles, because your webapp would not work when it's deployed to a servletcontainer of a different make/version than where those libraries are originally obtained from.

In case you're using Maven, you need to make absolutely sure that servletcontainer-specific libraries which are already provided by the target runtime are marked as <scope>provided</scope>.

Here are some typical exceptions which you can get when you litter the /WEB-INF/lib or even /JRE/lib, /JRE/lib/ext, etc with servletcontainer-specific libraries in a careless attempt to fix the compilation errors:

Content is not allowed in Prolog SAXParserException

This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.

You will find a possible solution here.

Java 8, Streams to find the duplicate elements

You can get the duplicated like this :

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicated = numbers
  .stream()
  .filter(n -> numbers
        .stream()
        .filter(x -> x == n)
        .count() > 1)
   .collect(Collectors.toSet());

How can I read inputs as numbers?

I encountered a problem of taking integer input while solving a problem on CodeChef, where two integers - separated by space - should be read from one line.

While int(input()) is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

Now I use num1 and num2 as integers. Hope this helps.

SQL Server remove milliseconds from datetime

Use 'Smalldatetime' data type

select convert(smalldatetime, getdate())

will fetch

2015-01-08 15:27:00

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

File Upload ASP.NET MVC 3.0

You don't use a file input control. Server side controls are not used in ASP.NET MVC. Checkout the following blog post which illustrates how to achieve this in ASP.NET MVC.

So you would start by creating an HTML form which would contain a file input:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

and then you would have a controller to handle the upload:

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}

symfony 2 No route found for "GET /"

Prefix is the prefix for url routing. If it's equals to '/' it means it will have no prefix. Then you defined a route with pattern "it should start with /hello".

To create a route for '/' you need to add these lines in your src/Shop/MyShopBundle/Resources/config/routing.yml :

ShopMyShopBundle_homepage:
    pattern:  /
    defaults: { _controller: ShopMyShopBundle:Main:index }

jQuery: How to get the HTTP status code from within the $.ajax.error method?

use

   statusCode: {
    404: function() {
      alert('page not found');
    }
  }

-

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    statusCode: {
    404: function() {
      alert('page not found');
    },

    400: function() {
       alert('bad request');
   }
  }

});

How can I close a browser window without receiving the "Do you want to close this window" prompt?

The browser is complaining because you're using JavaScript to close a window that wasn't opened with JavaScript, i.e. window.open('foo.html');.

Using floats with sprintf() in embedded C

Don't do this; integers in C/C++ are always rounded down so there is no need to use the floor function.

char str[100]; 
int d1 = value;

Better to use

int d1 = (int)(floor(value));

Then you won't get rounding up of the integer part (68.9999999999999999 becomes 69.00..). 68.09999847 instead of 68.1 is difficult to avoid - any floating point format has limited precision.

How do you get the string length in a batch file?

You can try this code. Fast, you can also include special characters

@echo off
set "str=[string]"
echo %str% > "%tmp%\STR"
for %%P in ("%TMP%\STR") do (set /a strlen=%%~zP-3)
echo String lenght: %strlen%

Escaping quotation marks in PHP

Use a backslash as such

"From time to \"time\"";

Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this

'From time to "time"';

The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such

$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"

As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:

$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;

Adding div element to body or document in JavaScript

The best and better way is to create an element and append it to the body tag. Second way is to first get the innerHTML property of body and add code with it. For example:

var b = document.getElementsByTagName('body');
b.innerHTML = b.innerHTML + "Your code";

scp (secure copy) to ec2 instance without password

I was hung up on this because I was specifying my public key file in

scp -i [private key file path]

When I caught that mistake and changed it to the private key path instead, I was all set.

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Change URL parameters

I think you want the query plugin.

E.g.:

window.location.search = jQuery.query.set("rows", 10);

This will work regardless of the current state of rows.

Java Could not reserve enough space for object heap error

I had this problem. I solved it with downloading 64x of the Java. Here is the link: http://javadl.sun.com/webapps/download/AutoDL?BundleId=87443

How to efficiently calculate a running standard deviation?

n=int(raw_input("Enter no. of terms:"))

L=[]

for i in range (1,n+1):

    x=float(raw_input("Enter term:"))

    L.append(x)

sum=0

for i in range(n):

    sum=sum+L[i]

avg=sum/n

sumdev=0

for j in range(n):

    sumdev=sumdev+(L[j]-avg)**2

dev=(sumdev/n)**0.5

print "Standard deviation is", dev

Link to the issue number on GitHub within a commit message

Just include #xxx in your commit message to reference an issue without closing it.

With new GitHub issues 2.0 you can use these synonyms to reference an issue and close it (in your commit message):

  • fix #xxx
  • fixes #xxx
  • fixed #xxx
  • close #xxx
  • closes #xxx
  • closed #xxx
  • resolve #xxx
  • resolves #xxx
  • resolved #xxx

You can also substitute #xxx with gh-xxx.

Referencing and closing issues across repos also works:

fixes user/repo#xxx

Check out the documentation available in their Help section.

Get Line Number of certain phrase in file Python

def get_line_number(phrase, file_name):
    with open(file_name) as f:
        for i, line in enumerate(f, 1):
            if phrase in line:
                return i

finding first day of the month in python

This could be an alternative to Gustavo Eduardo Belduma's answer:

import datetime 
first_day_of_the_month = datetime.date.today().replace(day=1)

Converting a JToken (or string) to a given Type

I was able to convert using below method for my WebAPI:

[HttpPost]
public HttpResponseMessage Post(dynamic item) // Passing parameter as dynamic
{
JArray itemArray = item["Region"]; // You need to add JSON.NET library
JObject obj = itemArray[0] as JObject;  // Converting from JArray to JObject
Region objRegion = obj.ToObject<Region>(); // Converting to Region object
}

Cleanest way to toggle a boolean variable in Java?

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

Using Alert in Response.Write Function in ASP.NET

Replace:

Response.Write("<script language=javascript>alert('ERROR');</script>);

With

Response.Write("<script language=javascript>alert('ERROR');</script>");

In other words, you're missing a closing " at the end of the Response.Write statement.

It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:

var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);

This will take care of wrapping the script with <script> tags and writing the script into the page for you.

Golang append an item to a slice

In order to make your code work without having to return the slice from Test, you can pass a pointer like this:

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice *[]int) {
    *slice = append(*slice, 100)

    fmt.Println(*slice)
}

func main() {

    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(&a)

    fmt.Println(a)
}

Why use a ReentrantLock if one can use synchronized(this)?

You can use reentrant locks with a fairness policy or timeout to avoid thread starvation. You can apply a thread fairness policy. it will help avoid a thread waiting forever to get to your resources.

private final ReentrantLock lock = new ReentrantLock(true);
//the param true turns on the fairness policy. 

The "fairness policy" picks the next runnable thread to execute. It is based on priority, time since last run, blah blah

also, Synchronize can block indefinitely if it cant escape the block. Reentrantlock can have timeout set.

Why would a JavaScript variable start with a dollar sign?

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).

In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?

I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.

For example:

var $get = function(id) { return document.getElementById(id); }

That seems like a reasonable convention.

Limit Get-ChildItem recursion depth

I tried to limit Get-ChildItem recursion depth using Resolve-Path

$PATH = "."
$folder = get-item $PATH 
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}

But this works fine :

gci "$PATH\*\*\*\*"

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

This solution provides CONVERT_IMPLICIT operation for your condition in predicate

SELECT * 
FROM xxx 
WHERE CAST(dates AS date) BETWEEN '1/1/2013' and '1/2/2013'

enter image description here

OR

SELECT * 
FROM xxx 
WHERE CONVERT(date, dates, 101) BETWEEN '1/1/2013' and '1/2/2013'

enter image description here

Demo on SQLFiddle

Timing a command's execution in PowerShell

Use Measure-Command

Example

Measure-Command { <your command here> | Out-Host }

The pipe to Out-Host allows you to see the output of the command, which is otherwise consumed by Measure-Command.

Get the contents of a table row with a button click

var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
   $(this).find("td").each(function () {
       values[count] = $(this).text();
       count++;
    });
});

Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row

Update records using LINQ

You have two options as far as I know:

  1. Perform your query, iterate over it to modify the entities, then call SaveChanges().
  2. Execute a SQL command like you mentioned at the top of your question. To see how to do this, take a look at this page.

If you use option 2, you're losing some of the abstraction that the Entity Framework gives you, but if you need to perform a very large update, this might be the best choice for performance reasons.

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

What is the difference between IEnumerator and IEnumerable?

An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in .NET code you probably won't call explicitly, though you could).

An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator.

Which do you use? The only reason to use IEnumerator is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator. But you'd still need to return that IEnumerator in an IEnumerable class.

For a look at what an enumerator (implementing IEnumerator<T>) looks like, see any Enumerator<T> class, such as the ones contained in List<T>, Queue<T>, or Stack<T>. For a look at a class implementing IEnumerable, see any standard collection class.

Multi-statement Table Valued Function vs Inline Table Valued Function

if you are going to do a query you can join in your Inline Table Valued function like:

SELECT
    a.*,b.*
    FROM AAAA a
        INNER JOIN MyNS.GetUnshippedOrders() b ON a.z=b.z

it will incur little overhead and run fine.

if you try to use your the Multi Statement Table Valued in a similar query, you will have performance issues:

SELECT
    x.a,x.b,x.c,(SELECT OrderQty FROM MyNS.GetLastShipped(x.CustomerID)) AS Qty
    FROM xxxx   x

because you will execute the function 1 time for each row returned, as the result set gets large, it will run slower and slower.

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

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

Something like this:

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

(remove the onclick and method)

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

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

and on a submit listener

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

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

Improving upon @barry-stae and @Sandeep answers for regular users of elinks you would add the following to .bashrc:

function mdviewer() {
  pandoc $* | elinks --force-html
}

Don't forget to install pandoc (and elinks).

Aesthetics must either be length one, or the same length as the dataProblems

I hit this error because I was specifying a label attribute in my geom (geom_text) but was specifying a color in the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
  geom_text(angle=45, label=df$V1, size=2)

To fix this, I just moved the label attribute out of the geom and into the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
  geom_text(angle=45, size=2)

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

Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.

So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....

You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.

How can I run a windows batch file but hide the command window?

If you write an unmanaged program and use CreateProcess API then you should initialize lpStartupInfo parameter of the type STARTUPINFO so that wShowWindow field of the struct is SW_HIDE and not forget to use STARTF_USESHOWWINDOW flag in the dwFlags field of STARTUPINFO. Another method is to use CREATE_NO_WINDOW flag of dwCreationFlags parameter. The same trick work also with ShellExecute and ShellExecuteEx functions.

If you write a managed application you should follows advices from http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx: initialize ProcessStartInfo with CreateNoWindow = true and UseShellExecute = false and then use as a parameter of . Exactly like in case of you can set property WindowStyle of ProcessStartInfo to ProcessWindowStyle.Hidden instead or together with CreateNoWindow = true.

You can use a VBS script which you start with wcsript.exe. Inside the script you can use CreateObject("WScript.Shell") and then Run with 0 as the second (intWindowStyle) parameter. See http://www.robvanderwoude.com/files/runnhide_vbs.txt as an example. I can continue with Kix, PowerShell and so on.

If you don't want to write any program you can use any existing utility like CMDOW /RUN /HID "c:\SomeDir\MyBatch.cmd", hstart /NOWINDOW /D=c:\scripts "c:\scripts\mybatch.bat", hstart /NOCONSOLE "batch_file_1.bat" which do exactly the same. I am sure that you will find much more such kind of free utilities.

In some scenario (for example starting from UNC path) it is important to set also a working directory to some local path (%SystemRoot%\system32 work always). This can be important for usage any from above listed variants of starting hidden batch.

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

Count number of times value appears in particular column in MySQL

select name, count(*) from table group by name;

i think should do it

How do I rename a local Git branch?

  1. Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

If you are on a different branch:

git branch -m old-name new-name
  1. Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

  1. Reset the upstream branch for the new-name local branch. Switch to the branch and then:

git push origin -u new-name

Or for a fast way to do that, you can use these 3 steps:

# Rename branch locally

git branch -m old_branch new_branch  

# Delete the old remote branch

git push origin :old_branch  

# Push the new branch, set local branch to track the new remote

git push --set-upstream origin new_branch   

Referance: https://www.w3docs.com/snippets/git/how-to-rename-git-local-and-remote-branches.html

Adding click event listener to elements with the same class

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

Vue template or render function not defined yet I am using neither?

If you used to calle a component like this:

Vue.component('dashboard', require('./components/Dashboard.vue'));

I suppose that problem occurred when you update to laravel mix 5.0 or another libraries, so you have to put .default. As like below:

Vue.component('dashboard', require('./components/Dashboard.vue').default);

I solved the same problem.

how to sort pandas dataframe from one column

Just as another solution:

Instead of creating the second column, you can categorize your string data(month name) and sort by that like this:

df.rename(columns={1:'month'},inplace=True)
df['month'] = pd.Categorical(df['month'],categories=['December','November','October','September','August','July','June','May','April','March','February','January'],ordered=True)
df = df.sort_values('month',ascending=False)

It will give you the ordered data by month name as you specified while creating the Categorical object.

Is there a C++ decompiler?

information is discarded in the compiling process. Even if a decompiler could produce the logical equivalent code with classes and everything (it probably can't), the self-documenting part is gone in optimized release code. No variable names, no routine names, no class names - just addresses.

How to comment a block in Eclipse?

Eclipse Oxygen with CDT, PyDev:

Block comments under Source menu

Add Comment Block Ctrl + 4

Add Single Comment Block Ctrl+Shift+4

Remove Comment Block Ctrl + 5

Using Case/Switch and GetType to determine the object

Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.

Remove a symlink to a directory

Assuming your setup is something like: ln -s /mnt/bar ~/foo, then you should be able to do a rm foo with no problem. If you can't, make sure you are the owner of the foo and have permission to write/execute the file. Removing foo will not touch bar, unless you do it recursively.

jQuery $.cookie is not a function

The old version of jQuery Cookie has been deprecated, so if you're getting the error:

$.cookie is not a function

you should upgrade to the new version.

The API for the new version is also different - rather than using

$.cookie("yourCookieName");

you should use

Cookies.get("yourCookieName");

DropDownList's SelectedIndexChanged event not firing

Set DropDownList AutoPostBack property to true.

Eg:

<asp:DropDownList ID="logList" runat="server" AutoPostBack="True" 
        onselectedindexchanged="itemSelected">
    </asp:DropDownList>

Split function equivalent in T-SQL?

You've tagged this SQL Server 2008 but future visitors to this question (using SQL Server 2016+) will likely want to know about STRING_SPLIT.

With this new builtin function you can now just use

SELECT TRY_CAST(value AS INT)
FROM   STRING_SPLIT ('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15', ',') 

Some restrictions of this function and some promising results of performance testing are in this blog post by Aaron Bertrand.

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

How to Detect Browser Window /Tab Close Event?

my solution is similar to the solution given by Server Themes. Do check it once:

localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
    if (e.keyCode == 116) {
        localStorage.setItem("validNavigation", true);
    }
});

// Attach the event click for all links in the page
$(document).on("click", "a", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});

$(document).bind("click", "button[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {

    if (localStorage.getItem("validNavigation") === "false") {
        event.returnValue = "Write something clever here..";
        console.log("Test success!");
        localStorage.setItem("validNavigation", false);
    }
};

If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.

Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

Media Queries: How to target desktop, tablet, and mobile?

@media (max-width: 767px)   {

      .container{width:100%} *{color:green;}-Mobile

    }


    @media (min-width: 768px)  {

     .container{width:100%} *{color:pink  } -Desktop

    }
    @media (min-width: 768px) and (orientation:portrait)  {

       .container{width:100%} *{color:yellow  } -Mobile

    }
    @media (min-width: 1024px)  {

       .container{width:100%} *{color:pink  } -Desktop

    }
    @media (min-width: 1200px)  {

    .container{width:1180px} *{color:pink   } -Desktop

    }

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Reasons for using the set.seed function

The need is the possible desire for reproducible results, which may for example come from trying to debug your program, or of course from trying to redo what it does:

These two results we will "never" reproduce as I just asked for something "random":

R> sample(LETTERS, 5)
[1] "K" "N" "R" "Z" "G"
R> sample(LETTERS, 5)
[1] "L" "P" "J" "E" "D"

These two, however, are identical because I set the seed:

R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R> 

There is vast literature on all that; Wikipedia is a good start. In essence, these RNGs are called Pseudo Random Number Generators because they are in fact fully algorithmic: given the same seed, you get the same sequence. And that is a feature and not a bug.

How to align checkboxes and their labels consistently cross-browsers

Sometimes vertical-align needs two inline (span, label, input, etc...) elements next to each other to work properly. The following checkboxes are properly vertically centered in IE, Safari, FF, and Chrome, even if the text size is very small or large.

They all float next to each other on the same line, but the nowrap means that the whole label text always stays next to the checkbox.

The downside is the extra meaningless SPAN tags.

_x000D_
_x000D_
.checkboxes label {_x000D_
  display: inline-block;_x000D_
  padding-right: 10px;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
.checkboxes input {_x000D_
  vertical-align: middle;_x000D_
}_x000D_
.checkboxes label span {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<form>_x000D_
  <div class="checkboxes">_x000D_
    <label for="x"><input type="checkbox" id="x" /> <span>Label text x</span></label>_x000D_
    <label for="y"><input type="checkbox" id="y" /> <span>Label text y</span></label>_x000D_
    <label for="z"><input type="checkbox" id="z" /> <span>Label text z</span></label>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Now, if you had a very long label text that needed to wrap without wrapping under the checkbox, you'd use padding and negative text indent on the label elements:

_x000D_
_x000D_
.checkboxes label {_x000D_
  display: block;_x000D_
  padding-right: 10px;_x000D_
  padding-left: 22px;_x000D_
  text-indent: -22px;_x000D_
}_x000D_
.checkboxes input {_x000D_
  vertical-align: middle;_x000D_
}_x000D_
.checkboxes label span {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<form>_x000D_
  <div class="checkboxes">_x000D_
    <label for="x"><input type="checkbox" id="x" /> <span>Label text x so long that it will probably wrap so let's see how it goes with the proposed CSS (expected: two lines are aligned nicely)</span></label>_x000D_
    <label for="y"><input type="checkbox" id="y" /> <span>Label text y</span></label>_x000D_
    <label for="z"><input type="checkbox" id="z" /> <span>Label text z</span></label>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Setting environment variable in react-native?

i have created a pre build script for the same problem because i need some differents api endpoints for the differents environments

const fs = require('fs')

let endPoint

if (process.env.MY_ENV === 'dev') {
  endPoint = 'http://my-api-dev/api/v1'
} else if (process.env.MY_ENV === 'test') {
  endPoint = 'http://127.0.0.1:7001'
} else {
  endPoint = 'http://my-api-pro/api/v1'
}

let template = `
export default {
  API_URL: '${endPoint}',
  DEVICE_FINGERPRINT: Math.random().toString(36).slice(2)
}
`

fs.writeFile('./src/constants/config.js', template, function (err) {
  if (err) {
    return console.log(err)
  }

  console.log('Configuration file has generated')
})

And i have created a custom npm run scripts to execute react-native run..

My package-json

"scripts": {
    "start-ios": "node config-generator.js && react-native run-ios",
    "build-ios": "node config-generator.js && react-native run-ios --configuration Release",
    "start-android": "node config-generator.js && react-native run-android",
    "build-android": "node config-generator.js && cd android/ && ./gradlew assembleRelease",
    ...
}

Then in my services components simply import the auto generated file:

import config from '../constants/config'

fetch(`${config.API_URL}/login`, params)

Where can I find php.ini?

PHP comes with two native functions to show which config file is loaded :

Depending on your setup, Apache and CLI might use different ini files. Here are the two solutions :

Apache :

Just add the following in a php file and open it in your browser

print php_ini_loaded_file();
print_r(php_ini_scanned_files());

CLI :

Copy-paste in your terminal :

php -r 'print php_ini_loaded_file(); print_r(php_ini_scanned_files());'

Can't find file executable in your configured search path for gnc gcc compiler

I had also found this error but I have solved this problem by easy steps. If you want to solve this problem follow these steps:

Step 1: First start code block

Step 2: Go to menu bar and click on the Setting menu

Step 3: After that click on the Compiler option

Step 4: Now, a pop up window will be opened. In this window, select "GNU GCC COMPILER"

Step 5: Now go to the toolchain executables tab and select the compiler installation directory like (C:\Program Files (x86)\CodeBlocks\MinGW\bin)

Step 6: Click on the Ok.

enter image description here

Now you can remove this error by follow these steps. Sometimes you don't need to select bin folder. You need to select only (C:\Program Files (x86)\CodeBlocks\MinGW) this path but some system doesn't work this path. That's why you have to select path from C:/ to bin folder.

Thank you.

How to clear basic authentication details in chrome

Chrome uses the same Internet Options as IE.

Try opening your Internet Options and removing the URL from "Trusted Sites." This should regenerate a 401 call for credentials when you restart the browser and visit the URL again.

You may need to remove it from "Intranet Sites" as well.

jQuery get the name of a select option

Firstly name isn't a valid attribute of an option element. Instead you could use a data parameter, like this:

<option value="foo" data-name="bar">Foo Bar</option>

The main issue you have is that the JS is looking at the name attribute of the select element, not the chosen option. Try this:

$('#band_type_choices').on('change', function() {         
    $('.checkboxlist').hide();
    $('#checkboxlist_' + $('option:selected', this).data("name")).css("display", "block");
});

Note the option:selected selector within the context of the select which raised the change event.

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setText("Passed!");
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setText("Failed!");
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}

How to clear PermGen space Error in tomcat

If your using eclipse with tomcat follow the below steps

  1. On server window Double click on tomcat, It will open the tomcat's Overview window .

  2. In the Overview window you will find Open launch configuration under General information and click on Open launch configuration.

  3. In the edit Configuration window look for Arguments and click on It.
  4. In the arguments tag look for VM arguments.
  5. simply paste this -Xms256m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=512m to the end of the arguments.

edit launch configuration properties

Create an array or List of all dates between two dates

public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
    if (endDate < startDate)
        throw new ArgumentException("endDate must be greater than or equal to startDate");

    while (startDate <= endDate)
    {
        yield return startDate;
        startDate = startDate.AddDays(1);
    }
}

How do I put two increment statements in a C++ 'for' loop?

Try this

for(int i = 0; i != 5; ++i, ++j)
    do_something(i,j);

Is there any publicly accessible JSON data source to test with real world data?

Twitter has a public API which returns JSON, for example -

A GET request to:

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=mralexgray&count=1,

EDIT: Removed due to twitter restricting their API with OAUTH requirements...

{"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}

Replacing it with a simple example of the Github API - that returns a tree, of in this case, my repositories...

https://api.github.com/users/mralexgray/repos

I won't include the output, as it's long.. (returns 30 repos at a time) ... But here is proof of it's tree-ed-ness.

enter image description here

Centering text in a table in Twitter Bootstrap

add:

<p class="text-center"> Your text here... </p>

long long in C/C++

your code compiles here fine (even with that line uncommented. had to change it to

num3 = 100000000000000000000;

to start getting the warning.

Why is my method undefined for the type object?

It should be like that

public static void main(String[] args) {
        EchoServer0 e = new EchoServer0();
        // TODO Auto-generated method stub
        e.listen();
}

Your variable of type Object truly doesn't have such a method, but the type EchoServer0 you define above certainly has.

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Specifying and saving a figure with exact size in pixels

plt.imsave worked for me. You can find the documentation here: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.imsave.html

#file_path = directory address where the image will be stored along with file name and extension
#array = variable where the image is stored. I think for the original post this variable is im_np
plt.imsave(file_path, array)