Programs & Examples On #Action

An Action is a response of the program on occurrence detected by the program that may be handled by the program events.

Action Image MVC3 Razor

You can use Url.Content which works for all links as it translates the tilde ~ to the root uri.

<a href="@Url.Action("Edit", new { id=MyId })">
    <img src="@Url.Content("~/Content/Images/Image.bmp")", alt="Edit" />
</a>

Passing parameters on button action:@selector

I have another solution in some cases.

store your parameter in a hidden UILabel. then add this UILabel as subview of UIButton.

when button is clicked, we can have a check on UIButton's all subviews. normally only 2 UILabel in it.

one is UIButton's title, the other is the one you just added. read that UILabel's text property, you will get the parameter.

This only apply for text parameter.

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

How can I pass a parameter in Action?

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

this.Include(includes, () =>
{
    _context.Cars.Include(<parameters>);
});

JavaScript: how to change form action attribute value based on selection?

Simple and easy in javascipt

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

php form action php self

If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

android pick images from gallery

U can do it easier than this answers :

Uri Selected_Image_Uri = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
imageView.setImageURI(Selected_Image_Uri);

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

How to dismiss notification after action has been clicked

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

Get controller and action name from within controller?

You can get controller name or action name from action like any variable. They are just special (controller and action) and already defined so you do not need to do anything special to get them except telling you need them.

public string Index(string controller,string action)
   {
     var names=string.Format("Controller : {0}, Action: {1}",controller,action);
     return names;
   }

Or you can include controller , action in your models to get two of them and your custom data.

public class DtoModel
    {
        public string Action { get; set; }
        public string Controller { get; set; }
        public string Name { get; set; }
    }

public string Index(DtoModel baseModel)
    {
        var names=string.Format("Controller : {0}, Action: {1}",baseModel.Controller,baseModel.Action);
        return names;
    }

How do I use two submit buttons, and differentiate between which one was used to submit the form?

You can use it as follows,

<td>

<input type="submit" name="save" class="noborder" id="save" value="Save" alt="Save" 
tabindex="4" />

</td>

<td>

<input type="submit" name="publish" class="noborder" id="publish" value="Publish" 
alt="Publish" tabindex="5" />

</td>

And in PHP,

<?php
if($_POST['save'])
{
   //Save Code
}
else if($_POST['publish'])
{
   //Publish Code
}
?>

How to set the action for a UIBarButtonItem in Swift

Swift 5

if you have created UIBarButtonItem in Interface Builder and you connected outlet to item and want to bind selector programmatically.

Don't forget to set target and selector.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

Uses of Action delegate in C#

We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use BuildPerson() function. Later we add Jane Doe too, but we modify her birthdate and name and height.

public class Program
{
        public static void Main(string[] args)
        {
            var person1 = BuildPerson();

            Console.WriteLine(person1.Firstname);
            Console.WriteLine(person1.Lastname);
            Console.WriteLine(person1.BirthDate);
            Console.WriteLine(person1.Height);

            var person2 = BuildPerson(p =>
            {
                p.Firstname = "Jane";
                p.BirthDate = DateTime.Today;
                p.Height = 1.76;
            });

            Console.WriteLine(person2.Firstname);
            Console.WriteLine(person2.Lastname);
            Console.WriteLine(person2.BirthDate);
            Console.WriteLine(person2.Height);

            Console.Read();
        }

        public static Person BuildPerson(Action<Person> overrideAction = null)
        {
            var person = new Person()
            {
                Firstname = "John",
                Lastname = "Doe",
                BirthDate = new DateTime(2012, 2, 2)
            };

            if (overrideAction != null)
                overrideAction(person);

            return person;
        }
    }

    public class Person
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public DateTime BirthDate { get; set; }
        public double Height { get; set; }
    }

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

SOAP Action WSDL

When soapAction is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction from {xsd:import namespace}+{wsdl:operation name}. So, to make the inferred "actual" soapAction match the expected soapAction, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name} in your WS definition (@WebMethod(action=...) for Java EE)

Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):

@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")

If you cannot change the server, you will have to force client to fill soapAction.

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

Differences between action and actionListener

ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.

If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.

Here is a link that describes the relationship:

http://www.java-samples.com/showtutorial.php?tutorialid=605

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

Set a form's action attribute when submitting?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.

Something like this:

<form id="whatever" name="whatever" onSubmit="return xyz();">
    Here is your entire form
    <input type="submit">
</form>;

<script type=text/javascript>
function xyz() {
  document.getElementById('whatever').action = 'whatever you want'
}
</script>

Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:

If you're using PrimeFaces (or some similar API) p:commandButton or p:commandLink, chances are that you have forgotten to explicitly add process="@this" to your command components.

As the PrimeFaces User's Guide states in section 3.18, the defaults for process and update are both @form, which pretty much opposes the defaults you might expect from plain JSF f:ajax or RichFaces, which are execute="@this" and render="@none" respectively.

Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)

Adding form action in html in laravel

For Laravel 2020. Ok, an example:

<form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must 
....
 </form>

And then in web.php:

Route::post("/login_kun", "LoginController@login");

And one more in new created LoginController:

 public function login(Request $request){
    dd($request->all());
}

and you are done my friend.

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

How to execute logic on Optional if not present?

You need Optional.isPresent() and orElse(). Your snippet won;t work because it doesn't return anything if not present.

The point of Optional is to return it from the method.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

Using a separate thread to display a simple please wait message is overkill especially if you don't have much experience with threading.

A much simpler approach is to create a "Please wait" form and display it as a mode-less window just before the slow loading form. Once the main form has finished loading, hide the please wait form.

In this way you are using just the one main UI thread to firstly display the please wait form and then load your main form.

The only limitation to this approach is that your please wait form cannot be animated (such as a animated GIF) because the thread is busy loading your main form.

PleaseWaitForm pleaseWait=new PleaseWaitForm ();

// Display form modelessly
pleaseWait.Show();

//  ALlow main UI thread to properly display please wait form.
Application.DoEvents();

// Show or load the main form.
mainForm.ShowDialog();

Import functions from another js file. Javascript

From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

Truncate (not round off) decimal numbers in javascript

You can work with strings. It Checks if '.' exists, and then removes part of string.

truncate (7.88, 1) --> 7.8

truncate (7.889, 2) --> 7.89

truncate (-7.88, 1 ) --> -7.88

function  truncate(number, decimals) {
    const tmp = number + '';
    if (tmp.indexOf('.') > -1) {
        return +tmp.substr(0 , tmp.indexOf('.') + decimals+1 );
    } else {
        return +number
    }
 }

How to grep for contents after pattern?

You can use grep, as the other answers state. But you don't need grep, awk, sed, perl, cut, or any external tool. You can do it with pure bash.

Try this (semicolons are there to allow you to put it all on one line):

$ while read line;
  do
    if [[ "${line%%:\ *}" == "potato" ]];
    then
      echo ${line##*:\ };
    fi;
  done< file.txt

## tells bash to delete the longest match of ": " in $line from the front.

$ while read line; do echo ${line##*:\ }; done< file.txt
1234
5678
5432
4567
5432
56789

or if you wanted the key rather than the value, %% tells bash to delete the longest match of ": " in $line from the end.

$ while read line; do echo ${line%%:\ *}; done< file.txt
potato
apple
potato
grape
banana
sushi

The substring to split on is ":\ " because the space character must be escaped with the backslash.

You can find more like these at the linux documentation project.

Linq select object from list depending on objects attribute

First, Single throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct property is true. Right now, you are checking if a is equal to a.Correct (which will not even compile).

You should use First (which will throw if there are no such elements), or FirstOrDefault (which will return null for a reference type if there isn't such element):

// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct); 

// this will return the first correct answer, 
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct); 

// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

How to concatenate items in a list to a single string?

If you have mixed content list. And want to stringify it. Here is one way:

Consider this list:

>>> aa
[None, 10, 'hello']

Convert it to string:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

If required, convert back to list:

>>> ast.literal_eval(st)
[None, 10, 'hello']

Find everything between two XML tags with RegEx

It is not a good idea to use regex for HTML/XML parsing...

However, if you want to do it anyway, search for regex pattern

<primaryAddress>[\s\S]*?<\/primaryAddress>

and replace it with empty string...

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.

<div class="ng-cloak">{{name}}<div>

and

<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Can I target all <H> tags with a single selector?

Stylus's selector interpolation

for n in 1..6
  h{n}
    font: 32px/42px trajan-pro-1,trajan-pro-2;

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Stop a gif animation onload, on mouseover start the activation

You can solve this by having a long stripe that you show in steps, like a filmstrip. Then you can stop the film on any frame. Example below (fiddle available at http://jsfiddle.net/HPXq4/9/):

the markup:

 <div class="thumbnail-wrapper">
     <img src="blah.jpg">
 </div>

the css:

.thumbnail-wrapper{
   width:190px;
   height:100px;
   overflow:hidden;
   position:absolute;
}
.thumbnail-wrapper img{
   position:relative;
   top:0;
}

the js:

var gifTimer;
var currentGifId=null;
var step = 100; //height of a thumbnail
$('.thumbnail-wrapper img').hover(
   function(){
      currentGifId = $(this)
      gifTimer = setInterval(playGif,500);
   },
   function(){
       clearInterval(gifTimer);
       currentGifId=null;
   }
);

var playGif = function(){
   var top = parseInt(currentGifId.css('top'))-step;
   var max = currentGifId.height();
   console.log(top,max)
   if(max+top<=0){
     console.log('reset')
     top=0;
   }
   currentGifId.css('top',top);
}

obviously, this can be optimized much further, but I simplified this example for readability

How to call another controller Action From a controller in Mvc

if the problem is to call. you can call it using this method.

yourController obj= new yourController();

obj.yourAction();

How to rename JSON key

  1. Parse the JSON
const arr = JSON.parse(json);
  1. For each object in the JSON, rename the key:
obj.id = obj._id;
delete obj._id;
  1. Stringify the result

All together:

_x000D_
_x000D_
function renameKey ( obj, oldKey, newKey ) {
  obj[newKey] = obj[oldKey];
  delete obj[oldKey];
}

const json = `
  [
    {
      "_id":"5078c3a803ff4197dc81fbfb",
      "email":"[email protected]",
      "image":"some_image_url",
      "name":"Name 1"
    },
    {
      "_id":"5078c3a803ff4197dc81fbfc",
      "email":"[email protected]",
      "image":"some_image_url",
      "name":"Name 2"
    }
  ]
`;
   
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );

console.log( updatedJson );
_x000D_
_x000D_
_x000D_

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

How to handle checkboxes in ASP.NET MVC forms?

You should also use <label for="checkbox1">Checkbox 1</label> because then people can click on the label text as well as the checkbox itself. Its also easier to style and at least in IE it will be highlighted when you tab through the page's controls.

<%= Html.CheckBox("cbNewColors", true) %><label for="cbNewColors">New colors</label>

This is not just a 'oh I could do it' thing. Its a significant user experience enhancement. Even if not all users know they can click on the label many will.

What was the strangest coding standard rule that you were forced to follow?

Totally useless database naming conventions. Every table name has to start with a number. The numbers show which kind of data is in the table.

  • 0: data that is used everywhere
  • 1: data that is used by a certain module only
  • 2: lookup table
  • 3: calendar, chat and mail
  • 4: logging

This makes it hard to find a table if you only know the first letter of its name. Also - as this is a mssql database - we have to surround tablenames with square brackets everywhere.

-- doesn't work
select * from 0examples;

-- does work
select * from [0examples];

Font Awesome not working, icons showing as squares

This should be much simpler in the new version 3.0. Easiest is to point to the Bootstrap CDN: http://www.bootstrapcdn.com/?v=01042013155511#tab_fontawesome

Convert Time DataType into AM PM Format:

Here are the various ways you may pull this (depending on your needs).

Using the Time DataType:

DECLARE @Time Time = '15:04:46.217'
SELECT --'3:04PM'
       CONVERT(VarChar(7), @Time, 0),

       --' 3:04PM' --Leading Space.
       RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' '),

       --'03:04 PM' --Leading Zero.  This answers the question above.
       STUFF(RIGHT('0' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(CAST(@Time as DateTime), 'hh:mm tt')--Comment out for SS08 or less.

Using the DateTime DataType:

DECLARE @Date DateTime = '2016-03-17 15:04:46.217'
SELECT --' 3:04PM' --No space before AM/PM.
       RIGHT(CONVERT(VarChar(19), @Date, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' '),

       --'3:04 PM' --No Leading Space.
       LTRIM(STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' ')),

       --'03:04 PM' --Leading Zero.
       STUFF(REPLACE(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), ' ', '0'), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(@Date, 'hh:mm tt')--Comment line out for SS08 or less.

jQuery - find table row containing table cell containing specific text

$(function(){
    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;
    }).parent('tr').css('color','red');
});

Will turn the text red for rows which have a cell whose text is 'foo'.

Android Studio - Device is connected but 'offline'

Change your USB Preferences to File Transfer if you use your smartphone to debug.

There are several option :

File Transfer /* Choose this one */

USB Tethering

MIDI

PTP

No Data Transfer

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Simplified:

DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();

PHP Fatal error: Call to undefined function json_decode()

If you're using phpbrew try to install json extension to fix error with undefined function json_decode():

phpbrew ext install json

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

How can I use Python to get the system hostname?

Both of these are pretty portable:

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

If input field is empty, disable submit button

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

Python 3 print without parenthesis

Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.

However, print without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:

Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: var = 'Hello world'

In [2]: /print var
Hello world

And if you turn on autocall, you won't even need to type the slash:

In [3]: %autocall
Automatic calling is: Smart

In [4]: print var
------> print(var)
Hello world

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Java Reflection: How to get the name of a variable?

It is not possible at all. Variable names aren't communicated within Java (and might also be removed due to compiler optimizations).

EDIT (related to comments):

If you step back from the idea of having to use it as function parameters, here's an alternative (which I wouldn't use - see below):

public void printFieldNames(Object obj, Foo... foos) {
    List<Foo> fooList = Arrays.asList(foos);
    for(Field field : obj.getClass().getFields()) {
         if(fooList.contains(field.get()) {
              System.out.println(field.getName());
         }
    }
}

There will be issues if a == b, a == r, or b == r or there are other fields which have the same references.

EDIT now unnecessary since question got clarified

Why is setTimeout(fn, 0) sometimes useful?

Take a look at John Resig's article about How JavaScript Timers Work. When you set a timeout, it actually queues the asynchronous code until the engine executes the current call stack.

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

surface plots in matplotlib

Just to add some further thoughts which may help others with irregular domain type problems. For a situation where the user has three vectors/lists, x,y,z representing a 2D solution where z is to be plotted on a rectangular grid as a surface, the 'plot_trisurf()' comments by ArtifixR are applicable. A similar example but with non rectangular domain is:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D 

# problem parameters
nu = 50; nv = 50
u = np.linspace(0, 2*np.pi, nu,) 
v = np.linspace(0, np.pi, nv,)

xx = np.zeros((nu,nv),dtype='d')
yy = np.zeros((nu,nv),dtype='d')
zz = np.zeros((nu,nv),dtype='d')

# populate x,y,z arrays
for i in range(nu):
  for j in range(nv):
    xx[i,j] = np.sin(v[j])*np.cos(u[i])
    yy[i,j] = np.sin(v[j])*np.sin(u[i])
    zz[i,j] = np.exp(-4*(xx[i,j]**2 + yy[i,j]**2)) # bell curve

# convert arrays to vectors
x = xx.flatten()
y = yy.flatten()
z = zz.flatten()

# Plot solution surface
fig = plt.figure(figsize=(6,6))
ax = Axes3D(fig)
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0,
                antialiased=False)
ax.set_title(r'trisurf example',fontsize=16, color='k')
ax.view_init(60, 35)
fig.tight_layout()
plt.show()

The above code produces:

Surface plot for non-rectangular grid problem

However, this may not solve all problems, particular where the problem is defined on an irregular domain. Also, in the case where the domain has one or more concave areas, the delaunay triangulation may result in generating spurious triangles exterior to the domain. In such cases, these rogue triangles have to be removed from the triangulation in order to achieve the correct surface representation. For these situations, the user may have to explicitly include the delaunay triangulation calculation so that these triangles can be removed programmatically. Under these circumstances, the following code could replace the previous plot code:


import matplotlib.tri as mtri 
import scipy.spatial
# plot final solution
pts = np.vstack([x, y]).T
tess = scipy.spatial.Delaunay(pts) # tessilation

# Create the matplotlib Triangulation object
xx = tess.points[:, 0]
yy = tess.points[:, 1]
tri = tess.vertices # or tess.simplices depending on scipy version

#############################################################
# NOTE: If 2D domain has concave properties one has to
#       remove delaunay triangles that are exterior to the domain.
#       This operation is problem specific!
#       For simple situations create a polygon of the
#       domain from boundary nodes and identify triangles
#       in 'tri' outside the polygon. Then delete them from
#       'tri'.
#       <ADD THE CODE HERE>
#############################################################

triDat = mtri.Triangulation(x=pts[:, 0], y=pts[:, 1], triangles=tri)

# Plot solution surface
fig = plt.figure(figsize=(6,6))
ax = fig.gca(projection='3d')
ax.plot_trisurf(triDat, z, linewidth=0, edgecolor='none',
                antialiased=False, cmap=cm.jet)
ax.set_title(r'trisurf with delaunay triangulation', 
          fontsize=16, color='k')
plt.show()

Example plots are given below illustrating solution 1) with spurious triangles, and 2) where they have been removed:

enter image description here

triangles removed

I hope the above may be of help to people with concavity situations in the solution data.

How to change the color of progressbar in C# .NET 3.5?

In the designer, you just need to set the ForeColor property to whatever color you'd like. In the case of Red, there's a predefined color for it.

To do it in code (C#) do this:

pgs.ForeColor = Color.Red;

Edit: Oh yeah, also set the Style to continuous. In code, like this:

pgs.Style = System.Windows.Forms.ProgressBarStyle.Continuous;

Another Edit: You'll also need to remove the line that reads Application.EnableVisualStyles() from your Program.cs (or similar). If you can't do this because you want the rest of the application to have visual styles, then I'd suggest painting the control yourself or moving on to WPF since this kind of thing is easy with WPF. You can find a tutorial on owner drawing a progress bar on codeplex

Calculating Time Difference

You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

import time
time.time()

which gives you the seconds since the start of the epoch.

You can then get the intermediate time with something like

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)

Width equal to content

You can use CSS property like this:

div {
    display: inherit;
}

I hope this helps.

CURL and HTTPS, "Cannot resolve host"

There is a current bug in glibc on Ubuntu which can have this effect: https://bugs.launchpad.net/ubuntu/+source/glibc/+bug/1674733

To resolve it, update libc and all related (Packages that will be upgraded: libc-bin libc-dev-bin libc6 libc6-dev libfreetype6 libfreetype6-dev locales multiarch-support) and restart the server.

Do you recommend using semicolons after every statement in JavaScript?

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

How to check if Thread finished execution

For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Manually Triggering Form Validation using jQuery

In some extent, You CAN trigger HTML5 form validation and show hints to user without submitting the form!

Two button, one for validate, one for submit

Set a onclick listener on the validate button to set a global flag(say justValidate) to indicate this click is intended to check the validation of the form.

And set a onclick listener on the submit button to set the justValidate flag to false.

Then in the onsubmit handler of the form, you check the flag justValidate to decide the returning value and invoke the preventDefault() to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault().

And, in HTML5 you have a method to check the form's validation: the form.checkValidity(), then in you can know if the form is validate or not in your code.

OK, here is the demo: http://jsbin.com/buvuku/2/edit

How to set the UITableView Section title programmatically (iPhone/iPad)?

If you are writing code in Swift it would look as an example like this

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    switch section
    {
        case 0:
            return "Apple Devices"
        case 1:
            return "Samsung Devices"
        default:
            return "Other Devices"
    }
}

Remove useless zero digits from decimals in PHP

The following is much simpler

if(floor($num) == $num) {
    echo number_format($num);
} else {
    echo $num;
}

How best to determine if an argument is not sent to the JavaScript function

function example(arg) {
  var argumentID = '0'; //1,2,3,4...whatever
  if (argumentID in arguments === false) {
    console.log(`the argument with id ${argumentID} was not passed to the function`);
  }
}

Because arrays inherit from Object.prototype. Consider ? to make the world better.

How to debug Lock wait timeout exceeded on MySQL?

Take a look at the man page of the pt-deadlock-logger utility:

brew install percona-toolkit
pt-deadlock-logger --ask-pass server_name

It extracts information from the engine innodb status mentioned above and also it can be used to create a daemon which runs every 30 seconds.

How to control border height?

You could create an image of whatever height you wish, and then position that with the CSS background(-position) property like:

#somid { background: url(path/to/img.png) no-repeat center top;

Instead of center topyou can also use pixel or % like 50% 100px.

http://www.w3.org/TR/CSS2/colors.html#propdef-background-position

Deck of cards JAVA

public class shuffleCards{

    public static void main(String[] args) {

        String[] cardsType ={"club","spade","heart","diamond"};
        String [] cardValue = {"Ace","2","3","4","5","6","7","8","9","10","King", "Queen", "Jack" };

        List<String> cards = new ArrayList<String>();
        for(int i=0;i<=(cardsType.length)-1;i++){
            for(int j=0;j<=(cardValue.length)-1;j++){
                cards.add(cardsType[i] + " " + "of" + " " + cardValue[j]) ;
            }
        }

        Collections.shuffle(cards);
        System.out.print("Enter the number of cards within:" + cards.size() + " = ");

        Scanner data = new Scanner(System.in);
        Integer inputString = data.nextInt();
        for(int l=0;l<= inputString -1;l++){
            System.out.print( cards.get(l)) ;
        }    
    }
}

java.lang.RuntimeException: Unable to start activity ComponentInfo

After trying few answers they are either not related to my project or , I have tried cleaning and rebuilding (https://stackoverflow.com/a/48760966/8463813). But it didn't work for me directly. I have compared it with older version of code, in which i observed some library files(jars and aars in External Libraries directory) are missing. Tried Invalidate Cache and Restart worked, which created all the libraries and working fine.

Difference between database and schema

A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.

Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.

EDIT for additional question

drop schema test1

Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.

You cannot drop a schema when it is in use. You have to first remove all objects from the schema.

Related reading:

  1. What good are SQL Server schemas?
  2. MSDN: User-Schema Separation

What is middleware exactly?

From my own experience with webwork, a middleware was stuff between users (the web browser) and the backend database. It was the software that took stuff that users put in (example: orders for iPads, did some magical business logic, i.e. check if there are enough iPads available to fill the order) and updated the backend database to reflect those changes.

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

Missing Authentication Token while accessing API Gateway?

I just had the same issue and it seems it also shows this message if the resource cannot be found.

In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.

When to use 'npm start' and when to use 'ng serve'?

From the document

npm-start :

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

which means it will call the start scripts inside the package.json

"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite --baseDir ./app --port 8001\" ",
"lite": "lite-server",
 ...
}

ng serve:

Provided by angular/angular-cli to start angular2 apps which created by angular-cli. when you install angular-cli, it will create ng.cmd under C:\Users\name\AppData\Roaming\npm (for windows) and execute "%~dp0\node.exe" "%~dp0\node_modules\angular-cli\bin\ng" %*

So using npm start you can make your own execution where is ng serve is only for angular-cli

See Also : What happens when you run ng serve?

Android ImageView's onClickListener does not work

Well my solution was another one, or let's say, the bug was:

I simply had another imageview with the same id in another <included /> twice-encapsuled xml layout, which was found before the one that i wanted to react on the click. Solution: Give one of them another id...

How can I search for a commit message on GitHub?

Using Advanced Search on Github seemed the easiest with a combination of other answers. It's basically a search string builder. https://github.com/search/advanced

For example I wanted to find all commits in Autodesk/maya-usd containing "USD" enter image description here

Then in the search results can choose Commits from the list on the left: enter image description here

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Changing three.js background to transparent or other color

I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:

renderer.setClearColorHex( 0x000000, 1 );

in your threejs init function. Change it to:

renderer.setClearColorHex( 0xffffff, 1 );

Update: Thanks to HdN8 for the updated solution:

renderer.setClearColor( 0xffffff, 0);

Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor() function:

var renderer = new THREE.WebGLRenderer({ alpha: true });

Update #3: Mr.doob points out that since r78 you can alternatively use the code below to set your scene's background colour:

var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

How to run a Maven project from Eclipse?

Well, you need to incorporate exec-maven-plugin, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain. You can pass argument and define which phase (test, package, integration, verify, or deploy), you want this plug-in to call your main class.

You need to add this plug-in under <build> tag and specify parameters. For example

   <project>
    ...
    ...
    <build>
     <plugins>
      <plugin>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>exec-maven-plugin</artifactId>
       <version>1.1.1</version>
       <executions>
        <execution>
         <phase>test</phase>
         <goals>
          <goal>java</goal>
         </goals>
         <configuration>
          <mainClass>my.company.name.packageName.TestMain</mainClass>
          <arguments>
           <argument>myArg1</argument>
           <argument>myArg2</argument>
          </arguments>
         </configuration>
        </execution>
       </executions>
      </plugin>
     </plugins>
    </build>
    ...
    ...
   </project>

Now, if you right-click on on the project folder and do Run As > Maven Test, or Run As > Maven Package or Run As > Maven Install, the test phase will execute and so your Main class.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Connect Bluestacks to Android Studio

In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.

After that when I press "Run" in android studio, bluestacks is detected as a new emulator.

enter image description here

enter image description here

Regards.

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

One command to create a directory and file inside it linux command

devnull's answer provides a function:

mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }

This function did not work for me as is (I'm running bash 4.3.48 on WSL Ubuntu), but did work once I removed the double dashes. So, this worked for me:

echo 'mkfile() { mkdir -p "$1" && touch "$1"/"$2" }' >> ~/.bash_profile
source ~/.bash_profile
mkfile sample/dir test.file

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

matplotlib colorbar in each subplot

In plt.colorbar(z1_plot,cax=ax1), use ax= instead of cax=, i.e. plt.colorbar(z1_plot,ax=ax1)

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

How to make the window full screen with Javascript (stretching all over the screen)

Try screenfull.js. It's a nice cross-browser solution that should work for Opera browser as well.

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

Demo.

How do I order my SQLITE database in descending order, for an android app?

According to docs:

public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

and your ORDER BY param means:

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

So, your query will be:

 Cursor cursor = db.query(TABLE_NAME, null, null,
            null, null, null, KEY_ITEM + " DESC", null);

How can I inject a property value into a Spring Bean which was configured using annotations?

Spring way:
private @Value("${propertyName}") String propertyField;

is a new way to inject the value using Spring's "PropertyPlaceholderConfigurer" class. Another way is to call

java.util.Properties props = System.getProperties().getProperty("propertyName");

Note: For @Value, you can not use static propertyField, it should be non-static only, otherwise it returns null. To fix it a non static setter is created for the static field and @Value is applied above that setter.

Iterate a list with indexes in Python

Yep, that would be the enumerate function! Or more to the point, you need to do:

list(enumerate([3,7,19]))

[(0, 3), (1, 7), (2, 19)]

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Connecting to SQL Server Express - What is my server name?

You should be able to see it in the Services panel. Look for a servicename like Sql Server (MSSQLSERVER). The name in the parentheses is your instance name.

multi line comment vb.net in Visual studio 2010

I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.

#if false

#endif

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

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

For some it's going to be:

sudo chown -R JonJames:admin /usr/local/lib

where "lib" is used as opposed to "bin" or "include" or "whatever else"

The Homebrew Warning "should" explain what specifically is not writable and then give you a command syntax for follow, however you will need to use the ":" as opposed to what the Warning mentions which is actually not correct syntax??

Read and Write CSV files including unicode with Python 2.7

I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:

class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
    # Redirect output to a queue
    self.queue = StringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f

    # Force BOM
    if encoding=="utf-16":
        import codecs
        f.write(codecs.BOM_UTF16)

    self.encoding = encoding

def writerow(self, row):
    # Modified from original: now using unicode(s) to deal with e.g. ints
    self.writer.writerow([unicode(s).encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = data.encode(self.encoding)

    # strip BOM
    if self.encoding == "utf-16":
        data = data[2:]

    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

How to convert base64 string to image?

Return converted image without saving:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

What is the 'dynamic' type in C# 4.0 used for?

I am surprised that nobody mentioned multiple dispatch. The usual way to work around this is via Visitor pattern and that is not always possible so you end up with stacked is checks.

So here is a real life example of an application of my own. Instead of doing:

public static MapDtoBase CreateDto(ChartItem item)
{
    if (item is ElevationPoint) return CreateDtoImpl((ElevationPoint)item);
    if (item is MapPoint) return CreateDtoImpl((MapPoint)item);
    if (item is MapPolyline) return CreateDtoImpl((MapPolyline)item);
    //other subtypes follow
    throw new ObjectNotFoundException("Counld not find suitable DTO for " + item.GetType());
}

You do:

public static MapDtoBase CreateDto(ChartItem item)
{
    return CreateDtoImpl(item as dynamic);
}

private static MapDtoBase CreateDtoImpl(ChartItem item)
{
    throw new ObjectNotFoundException("Counld not find suitable DTO for " + item.GetType());
}

private static MapDtoBase CreateDtoImpl(MapPoint item)
{
    return new MapPointDto(item);
}

private static MapDtoBase CreateDtoImpl(ElevationPoint item)
{
    return new ElevationDto(item);
}

Note that in first case ElevationPoint is subclass of MapPoint and if it's not placed before MapPointit will never be reached. This is not the case with dynamic, as the closest matching method will be called.

As you might guess from the code, that feature came handy while I was performing translation from ChartItem objects to their serializable versions. I didn't want to pollute my code with visitors and I didn't want also to pollute my ChartItem objects with useless serialization specific attributes.

Difference between id and name attributes in HTML

See this http://mindprod.com/jgloss/htmlforms.html#IDVSNAME

What’s the difference? The short answer is, use both and don’t worry about it. But if you want to understand this goofiness, here’s the skinny:

id= is for use as a target like this: <some-element id="XXX"></some-element> for links like this: <a href="#XXX".

name= is also used to label the fields in the message send to a server with an HTTP (HyperText Transfer Protocol) GET or POST when you hit submit in a form.

id= labels the fields for use by JavaScript and Java DOM (Document Object Model). The names in name= must be unique within a form. The names in id= must be unique within the entire document.

Sometimes the name= and id= names will differ, because the server is expecting the same name from various forms in the same document or various radio buttons in the same form as in the example above. The id= must be unique; the name= must not be.

JavaScript needed unique names, but there were too many documents already out here without unique name= names, so the W3 people invented the id tag that was required to be unique. Unfortunately older browsers did not understand it. So you need both naming schemes in your forms.

NOTE: attribute "name" for some tags like <a> is not supported in HTML5.

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

What do the return values of Comparable.compareTo mean in Java?

System.out.println(A.compareTo(B)>0?"Yes":"No")

if the value of A>B it will return "Yes" or "No".

android layout with visibility GONE

<TextView
                android:id="@+id/layone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Previous Page"
                android:textColor="#000000"
                android:textSize="16dp"
                android:paddingLeft="10dp"
                android:layout_marginTop="10dp"
                android:visibility="gone" />

layone is a TextView.
You got your id wrong.

LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here

layone.setVisibility(View.VISIBLE);

should do the job.

or change like this to show the TextView:

TextView layone= (TextView) view.findViewById(R.id.layone);

    layone.setVisibility(View.VISIBLE);

HTML5 canvas ctx.fillText won't do line breaks?

I created a tiny library for this scenario here: Canvas-Txt

It renders text in multi-line and it offers decent alignment modes.

In order to use this, you will need to either install it or use a CDN.

Installation

npm install canvas-txt --save

JavaScript

import canvasTxt from 'canvas-txt'

var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d')

var txt = 'Lorem ipsum dolor sit amet'

canvasTxt.fontSize = 24

canvasTxt.drawText(ctx, txt, 100, 200, 200, 200)

This will render text in an invisible box with position/dimensions of:

{ x: 100, y: 200, height: 200, width: 200 }

Example Fiddle

_x000D_
_x000D_
/* https://github.com/geongeorge/Canvas-Txt  */_x000D_
_x000D_
const canvasTxt = window.canvasTxt.default;_x000D_
const ctx = document.getElementById('myCanvas').getContext('2d');_x000D_
_x000D_
const txt = "Lorem ipsum dolor sit amet";_x000D_
const bounds = { width: 240, height: 80 };_x000D_
_x000D_
let origin = { x: ctx.canvas.width / 2, y: ctx.canvas.height / 2, };_x000D_
let offset = { x: origin.x - (bounds.width / 2), y: origin.y - (bounds.height / 2) };_x000D_
_x000D_
canvasTxt.fontSize = 20;_x000D_
_x000D_
ctx.fillStyle = '#C1A700';_x000D_
ctx.fillRect(offset.x, offset.y, bounds.width, bounds.height);_x000D_
_x000D_
ctx.fillStyle = '#FFFFFF';_x000D_
canvasTxt.drawText(ctx, txt, offset.x, offset.y, bounds.width, bounds.height);
_x000D_
body {_x000D_
  background: #111;_x000D_
}_x000D_
_x000D_
canvas {_x000D_
  border: 1px solid #333;_x000D_
  background: #222; /* Could alternatively be painted on the canvas */_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/build/index.js"></script>_x000D_
_x000D_
<canvas id="myCanvas" width="300" height="160"></canvas>
_x000D_
_x000D_
_x000D_

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

make html text input field grow as I type?

Which approach you use, of course, depends on what your end goal is. If you want to submit the results with a form then using native form elements means you don't have to use scripting to submit. Also, if scripting is turned off then the fallback still works without the fancy grow-shrink effects. If you want to get the plain text out of a contenteditable element you can always also use scripting like node.textContent to strip out the html that the browsers insert in the user input.

This version uses native form elements with slight refinements on some of the previous posts.

It allows the content to shrink as well.

Use this in combination with CSS for better control.

<html>

<textarea></textarea>
<br>
<input type="text">


<style>

textarea {
  width: 300px;
  min-height: 100px;
}

input {
  min-width: 300px;
}


<script>

document.querySelectorAll('input[type="text"]').forEach(function(node) {
  var minWidth = parseInt(getComputedStyle(node).minWidth) || node.clientWidth;
  node.style.overflowX = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.width = minWidth + 'px';
    node.style.width = node.scrollWidth + 'px';
  };
});

You can use something similar with <textarea> elements

document.querySelectorAll('textarea').forEach(function(node) {
  var minHeight = parseInt(getComputedStyle(node).minHeight) || node.clientHeight;
  node.style.overflowY = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.height = minHeight + 'px';
    node.style.height = node.scrollHeight + 'px';
  };
});

This doesn't flicker on Chrome, results may vary on other browsers, so test.

How do I compute derivative using Numpy?

You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]

git clone from another directory

It is worth mentioning that the command works similarly on Linux:

git clone path/to/source/folder path/to/destination/folder

Executing multiple commands from a Windows cmd script

You can use the && symbol between commands to execute the second command only if the first succeeds. More info here http://commandwindows.com/command1.htm

HTML img onclick Javascript

here you go.

<img src="https://i.imgur.com/7KpCS0Y.jpg" onclick="window.open(this.src)">

Android studio Gradle build speed up

For faster builds, increase the maximum heap size for the Gradle daemon to more than 2048 MB.

To do this set
org.gradle.jvmargs=-Xmx2048M
in the project gradle.properties.

How can I enable Assembly binding logging?

Per pierce.jason's answer above, I had luck with:

Just create a new DWORD(32) under the Fusion key. Name the DWORD to LogFailures, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.

What to gitignore from the .idea folder?

  • Remove .idea folder

    $rm -R .idea/
    
  • Add rule

    $echo ".idea/*" >> .gitignore
    
  • Commit .gitignore file

    $git commit -am "remove .idea"
    
  • Next commit will be ok

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

The issue is in the deserialization of the bean Customer. Your programs knows how to do it in XML, with JAXB as Daniel is writing, but most likely doesn't know how to do it in JSON.

Here you have an example with Resteasy/Jackson http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/

The same with Jersey: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

How to remove leading zeros using C#

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

How do I increment a DOS variable in a FOR /F loop?

set TEXT_T="myfile.txt"
set /a c=1

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c+=1
    set OUTPUT_FILE_NAME=output_%c%.txt
    echo Output file is %OUTPUT_FILE_NAME%
    echo %%i, %c%
)

Undefined symbols for architecture arm64

This linker error message suggests that the source file defining it is not marked as being part of your app target. Find that source file, and use the File property inspector on the right to check the target membership entry for your app target.

Solution: Select the file -> openFile Inspector -> see Target Membership -> check if unchecked target your running target

Check if a number has a decimal place/is a whole number

Function for check number is Decimal or whole number

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

How to convert a Hibernate proxy to a real entity object

The way I recommend with JPA 2 :

Object unproxied  = entityManager.unwrap(SessionImplementor.class).getPersistenceContext().unproxy(proxy);

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');

Open fancybox from function

Make argument object extends from <a> , and use open function of fancybox in click event via delegate.

    var paramsFancy={
         'autoScale': true,
         'transitionIn': 'elastic',
         'transitionOut': 'elastic',
         'speedIn': 500,
         'speedOut': 300,
         'autoDimensions': true,
         'centerOnScroll': true,
         'href' : '#contentdiv'
      };

    $(document).delegate('a[href=#modalMine]','click',function(){
               /*Now you can call your function ,
   you can change fields of paramsFancy via this function */
                 myfunction(this);

                paramsFancy.href=$(this).attr('href');
                $.fancybox.open(paramsFancy);

    });

How to truncate float values?

You can do:

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

testing:

>>> f=1.923328437452
>>> [truncate(f, n) for n in range(5)]
[1.0, 1.9, 1.92, 1.923, 1.9233]

How to modify PATH for Homebrew?

To avoid unnecessary duplication, I added the following to my ~/.bash_profile

case ":$PATH:" in
  *:/usr/local/bin:*) ;;     # do nothing if $PATH already contains /usr/local/bin
  *) PATH=/usr/local/bin:$PATH ;;  # in every other case, add it to the front
esac

Credit: https://superuser.com/a/580611

C# Debug - cannot start debugging because the debug target is missing

I had the same problem and unfortunately non of above answers worked for me . the solution that worked for me is :

right click on your startup project and select Properties - Debug and change "start external program: " to the correct path

Done!

How to execute python file in linux

You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.

It should look like that :

#!/usr/bin/env python

or the real path

#!/usr/bin/python

You should also check the file have the right to be execute. chmod +x file.py

As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I had also same issue. I solved this problem by updating my system jdk. Previously i used jdk7.0 and now it is updated to jdk8.0. find below link to download the updated jdk with new version. it help me to solve my problem.

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Java check if boolean is null

boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

Boolean testvar = null;
if (testvar == null) { ...}

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

"Any CPU" means that when the program is started, the .NET Framework will figure out, based on the OS bitness, whether to run your program in 32 bits or 64 bits.

There is a difference between x86 and Any CPU: on a x64 system, your executable compiled for X86 will run as a 32-bit executable.

As far as your suspicions go, just go to the Visual Studio 2008 command line and run the following.

dumpbin YourProgram.exe /headers

It will tell you the bitness of your program, plus a whole lot more.

How do I debug Node.js applications?

Node.js version 0.3.4+ has built-in debugging support.

node debug script.js

Manual: http://nodejs.org/api/debugger.html

HTML/CSS: Making two floating divs the same height

You can get equal height columns in CSS by applying bottom padding of a large amount, bottom negative margin of the same amount and surrounding the columns with a div that has overflow hidden. Vertically centering the text is a little trickier but this should help you on the way.

_x000D_
_x000D_
#container {_x000D_
  overflow: hidden;_x000D_
      width: 100%;_x000D_
}_x000D_
#left-col {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
  background-color: orange;_x000D_
  padding-bottom: 500em;_x000D_
  margin-bottom: -500em;_x000D_
}_x000D_
#right-col {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
  margin-right: -1px; /* Thank you IE */_x000D_
  border-left: 1px solid black;_x000D_
  background-color: red;_x000D_
  padding-bottom: 500em;_x000D_
  margin-bottom: -500em;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"_x000D_
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">_x000D_
_x000D_
<head></head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left-col">_x000D_
      <p>Test content</p>_x000D_
      <p>longer</p>_x000D_
    </div>_x000D_
    <div id="right-col">_x000D_
      <p>Test content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

I think it worth mentioning that the previous answer by streetpc has invalid html, the doctype is XHTML and there are single quotes around the attributes. Also worth noting is that you dont need an extra element with clear on in order to clear the internal floats of the container. If you use overflow hidden this clears the floats in all non-IE browsers and then just adding something to give hasLayout such as width or zoom:1 will cause IE to clear its internal floats.

I have tested this in all modern browsers FF3+ Opera9+ Chrome Safari 3+ and IE6/7/8. It may seem like an ugly trick but it works well and I use it in production a lot.

I hope this helps.

How do you do a ‘Pause’ with PowerShell 2.0?

cmd /c pause | out-null

(It is not the PowerShell way, but it's so much more elegant.)

Save trees. Use one-liners.

Is it safe to store a JWT in localStorage with ReactJS?

It is not safe if you use CDN's:

Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

via stormpath

Any script you require from the outside could potentially be compromised and could grab any JWTS from your client's storage and send personal data back to the attacker's server.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

If you are using the Facebook SDK then the issue might be in the "authorities" value you provide for the Facebook provider.

REPLACE -

<provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.FacebookContentProvider"
        android:exported="true" />

WITH ->

<provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.FacebookContentProvider[YOUR_APP_ID]"
        android:exported="true" />

You might need to change the defaultConfig.ApplicationId also as suggested in other answers.

Setting dropdownlist selecteditem programmatically

Safety check to only select if an item is matched.

//try to find item in list.  
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

Allow anything through CORS Policy

I've your same requirements on a public API for which I used rails-api.

I've also set header in a before filter. It looks like this:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

It seems you missed the Access-Control-Request-Method header.

How to get text of an input text box during onKeyPress?

By using event.key we can get values prior entry into HTML Input Text Box. Here is the code.

_x000D_
_x000D_
function checkText()_x000D_
{_x000D_
  console.log("Value Entered which was prevented was - " + event.key);_x000D_
  _x000D_
  //Following will prevent displaying value on textbox_x000D_
  //You need to use your validation functions here and return value true or false._x000D_
  return false;_x000D_
}
_x000D_
<input type="text" placeholder="Enter Value" onkeypress="return checkText()" />
_x000D_
_x000D_
_x000D_

Serialize form data to JSON

Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.

This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.

How to run jenkins as a different user

On Mac OS X, the way I enabled Jenkins to pull from my (private) Github repo is:

First, ensure that your user owns the Jenkins directory

sudo chown -R me:me /Users/Shared/Jenkins

Then edit the LaunchDaemon plist for Jenkins (at /Library/LaunchDaemons/org.jenkins-ci.plist) so that your user is the GroupName and the UserName:

    <key>GroupName</key>
    <string>me</string>
...
    <key>UserName</key>
    <string>me</string>

Then reload Jenkins:

sudo launchctl unload -w /Library/LaunchDaemons/org.jenkins-ci.plist
sudo launchctl load -w /Library/LaunchDaemons/org.jenkins-ci.plist

Then Jenkins, since it's running as you, has access to your ~/.ssh directory which has your keys.

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

What is the difference between VFAT and FAT32 file systems?

Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx

What's FAT?

FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.

The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.

What About VFAT?

Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.

When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.

An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.

You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.

FAT32

FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.

The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.

This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.

Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.

Note: This section of the quote/ article (1999) is out of date. Updated info quote below.

As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.

The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.

Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.

Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):

I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.

The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.

The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.

My httpd.conf is empty

The /etc/apache2/httpd.conf is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf!

“httpd.conf is for user options.” No it isn't, it's there for historic reasons.

Using Apache server, all user options should go into a new *.conf-file inside /etc/apache2/conf.d/. This method should be "update-safe", as httpd.conf or apache2.conf may get overwritten on the next server update.

Inside /etc/apache2/apache2.conf, you will find the following line, which includes those files:

# Include generic snippets of statements
Include conf.d/

As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/. Use a2enconf FILENAME_WITHOUT_SUFFIX to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf (e.g. conf-available/my-settings.conf);

android: stretch image in imageview to fit screen

The accepted answer is perfect, however if you want to do it from xml, you can use android:scaleType="fitXY"

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

You've got a workable idea, but the #flatten! is in the wrong place -- it flattens its receiver, so you could use it to turn [1, 2, ['foo', 'bar']] into [1,2,'foo','bar'].

I'm doubtless forgetting some approaches, but you can concatenate:

a1.concat a2
a1 + a2              # creates a new array, as does a1 += a2

or prepend/append:

a1.push(*a2)         # note the asterisk
a2.unshift(*a1)      # note the asterisk, and that a2 is the receiver

or splice:

a1[a1.length, 0] = a2
a1[a1.length..0] = a2
a1.insert(a1.length, *a2)

or append and flatten:

(a1 << a2).flatten!  # a call to #flatten instead would return a new array

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Getting attribute using XPath

How could I get the value of lang (where lang=eng in book title), for the first element?

Use:

/*/book[1]/title/@lang

This means:

Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

To get just the string value of this attribute use the standard XPath function string():

string(/*/book[1]/title/@lang)

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

Error handling with PHPMailer

PHPMailer uses Exceptions. Try to adopt the following code:

require_once '../class.phpmailer.php';

$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

try {
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;
}

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

Download old version of package with NuGet

Browse to its page in the package index, eg. http://www.nuget.org/packages/Newtonsoft.Json/4.0.5

Then follow the install instructions given:

Install-Package Newtonsoft.Json -Version 4.0.5

Alternatively to download the .nupkg file, follow the 'Download' link eg. https://www.nuget.org/api/v2/package/Newtonsoft.Json/4.0.5

Obsolete: install my Chrome extension Nutake which inserts a download link.

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

White space at top of page

If nothing of the above helps, check if there is margin-top set on some of the (some levels below) nested DOM element(s).

It will be not recognizable when you inspect body element itself in the debugger. It will only be visible when you unfold several elements nested down in body element in Chrome Dev Tools elements debugger and check if there is one of them with margin-top set.

The below is the upper part of a site screen shot and the corresponding Chrome Dev Tools view when you inspect body tag.

No sign of top margin here and you have resetted all the browser-scpecific CSS properties as per answers above but that unwanted white space is still here.

The unwanted white space above the body element The corresponding debugger view

The following is a view when you inspect the right nested element. It is clearly seen the orange'ish top-margin is set on it. This is the one that causes the white space on top of body element.

Clearly visible top-margin enter image description here

On that found element replace margin-top with padding-top if you need space above it and yet not to leak it above the body tag.

Hope that helps :)

How to pretty print XML from the command line?

Edit:

Disclaimer: you should usually prefer installing a mature tool like xmllint to do a job like this. XML/HTML can be a horribly mutilated mess. However, there are valid situations where using existing tooling is preferable over manually installing new ones, and where it is also a safe bet the XML's source is valid (enough). I've written this script for one of those cases, but they are rare, so precede with caution.


I'd like to add a pure Bash solution, as it is not 'that' difficult to just do it by hand, and sometimes you won't want to install an extra tool to do the job.

#!/bin/bash

declare -i currentIndent=0
declare -i nextIncrement=0
while read -r line ; do
  currentIndent+=$nextIncrement
  nextIncrement=0
  if [[ "$line" == "</"* ]]; then # line contains a closer, just decrease the indent
    currentIndent+=-1
  else
    dirtyStartTag="${line%%>*}"
    dirtyTagName="${dirtyStartTag%% *}"
    tagName="${dirtyTagName//</}"
    # increase indent unless line contains closing tag or closes itself
    if [[ ! "$line" =~ "</$tagName>" && ! "$line" == *"/>"  ]]; then
      nextIncrement+=1
    fi
  fi

  # print with indent
  printf "%*s%s" $(( $currentIndent * 2 )) # print spaces for the indent count
  echo $line
done <<< "$(cat - | sed 's/></>\n</g')" # separate >< with a newline

Paste it in a script file, and pipe in the xml. This assumes the xml is all on one line, and there are no extra spaces anywhere. One could easily add some extra \s* to the regexes to fix that.

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like

Dim copyRange2 As Range
Dim copyRange3 As Range

Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)

copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")

put these near the other codings that are the same you can easily change the Ranges as you need.

I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.

I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.

Angular2 QuickStart npm start is not working correctly

I solved my issue with the Quick Start program by following below link.

Angular 2 QuickStart Live-server error

Change the Package.json Scripts Settings

"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\",

to:

"start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",

Laravel Mail::send() sending to multiple to or bcc addresses

In a scenario where you intend to push a single email to different recipients at one instance (i.e CC multiple email addresses), the solution below works fine with Laravel 5.4 and above.

Mail::to('[email protected]')
    ->cc(['[email protected]','[email protected]','[email protected]','[email protected]'])
    ->send(new document());

where document is any class that further customizes your email.

How to validate Google reCAPTCHA v3 on server side?

Check below example

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

</script>
<form autocomplete="off" method="post" action=submit.php">

    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

If you've applied the CORS middleware and it's still not working, try this.

If the route for your API is:

Route::post("foo", "MyController"})->middleware("cors");

Then you need to change it to allow for the OPTIONS method:

Route::match(['post', 'options'], "foo", "MyController")->middleware("cors");

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

Overriding interface property type defined in Typescript d.ts file

Extending @zSkycat's answer a little, you can create a generic that accepts two object types and returns a merged type with the members of the second overriding the members of the first.

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type Merge<M, N> = Omit<M, Extract<keyof M, keyof N>> & N;

interface A {
    name: string;
    color?: string;
}

// redefine name to be string | number
type B = Merge<A, {
    name: string | number;
    favorite?: boolean;
}>;

let one: A = {
    name: 'asdf',
    color: 'blue'
};

// A can become B because the types are all compatible
let two: B = one;

let three: B = {
    name: 1
};

three.name = 'Bee';
three.favorite = true;
three.color = 'green';

// B cannot become A because the type of name (string | number) isn't compatible
// with A even though the value is a string
// Error: Type {...} is not assignable to type A
let four: A = three;

using CASE in the WHERE clause

You don't have to use CASE...WHEN, you could use an OR condition, like this:

WHERE
  pw='correct'
  AND (id>=800 OR success=1) 
  AND YEAR(timestamp)=2011

this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.

It is less common, however you could still use CASE WHEN, like this:

WHERE
  pw='correct'
  AND CASE WHEN id<800 THEN success=1 ELSE TRUE END 
  AND YEAR(timestamp)=2011

this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

If you wanna get the uploaded file name, use $_FILES["file"]["name"]

But If you wanna read the uploaded file you should use $_FILES["file"]["tmp_name"], because tmp_name is a temporary copy of your uploaded file and it's easier than using

$_FILES["file"]["name"] // This name includes a file path, which makes file read process more complex

How to format a Java string with leading zero?

You can use the String.format method as used in another answer to generate a string of 0's,

String.format("%0"+length+"d",0)

This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.

How to Select a substring in Oracle SQL up to a specific character?

You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.

  1  select 'ABC_blahblahblah' test_string,
  2         instr('ABC_blahblahblah','_',1,1) position_underscore,
  3         substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
  4*   from dual
SQL> /

TEST_STRING      POSITION_UNDERSCORE RES
---------------- ------------------  ---
ABC_blahblahblah                  4  ABC

Instr documentation

Susbtr Documentation

How to count digits, letters, spaces for a string in Python?

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

For any of those who are experiencing this on Windows and none of the above worked, try running this from cmd.exe. Executing these commands via PowerShell caused the install to fail each time.

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Invert "if" statement to reduce nesting

As others have mentioned, there shouldn't be a performance hit, but there are other considerations. Aside from those valid concerns, this also can open you up to gotchas in some circumstances. Suppose you were dealing with a double instead:

public void myfunction(double exampleParam){
    if(exampleParam > 0){
        //Body will *not* be executed if Double.IsNan(exampleParam)
    }
}

Contrast that with the seemingly equivalent inversion:

public void myfunction(double exampleParam){
    if(exampleParam <= 0)
        return;
    //Body *will* be executed if Double.IsNan(exampleParam)
}

So in certain circumstances what appears to be a a correctly inverted if might not be.

How to set a value to a file input in HTML?

You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?

How to delete the contents of a folder?

Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.

import os
import shutil

for root, dirs, files in os.walk('/path/to/folder'):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

How to programmatically click a button in WPF?

The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider as project/package dependency.

An alternative is to emulate the behaviour. In the following there is my extended solution which also condiders the MVVM-pattern with its bound commands - implemented as extension method:

public static class ButtonExtensions
{
    /// <summary>
    /// Performs a click on the button.<br/>
    /// This is the WPF-equivalent of the Windows Forms method "<see cref="M:System.Windows.Forms.Button.PerformClick" />".
    /// <para>This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:<br />
    /// 1. The raising the ClickEvent.<br />
    /// 2.1. Checking that the bound command can be executed, calling <see cref="ICommand.CanExecute" />, if a command is bound.<br />
    /// 2.2. If command can be executed, then the <see cref="ICommand.Execute(object)" /> will be called and the optional bound parameter is p
    /// </para>
    /// </summary>
    /// <param name="sourceButton">The source button.</param>
    /// <exception cref="ArgumentNullException">sourceButton</exception>
    public static void PerformClick(this Button sourceButton)
    {
        // Check parameters
        if (sourceButton == null)
            throw new ArgumentNullException(nameof(sourceButton));

        // 1.) Raise the Click-event
        sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

        // 2.) Execute the command, if bound and can be executed
        ICommand boundCommand = sourceButton.Command;
        if (boundCommand != null)
        {
            object parameter = sourceButton.CommandParameter;
            if (boundCommand.CanExecute(parameter) == true)
                boundCommand.Execute(parameter);
        }
    }
}

Get google map link with latitude/longitude

I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:

<iframe 
  width="300" 
  height="170" 
  frameborder="0" 
  scrolling="no" 
  marginheight="0" 
  marginwidth="0" 
  src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&amp;output=embed"
 >
 </iframe>
 <br />
 <small>
   <a 
    href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&amp;output=embed" 
    style="color:#0000FF;text-align:left" 
    target="_blank"
   >
     See map bigger
   </a>
 </small>

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

How to export dataGridView data Instantly to Excel on button click?

In my opinion this is the easiest and instantly working method of exporting datagridview.

 try
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
            sfd.FileName = "ProfitLoss.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                DataTable dts = new DataTable();
                for (int i = 0; i < grdProfitAndLoss.Columns.Count; i++)
                {
                    dts.Columns.Add(grdProfitAndLoss.Columns[i].Name);
                }
                for (int j = 0; j < grdProfitAndLoss.Rows.Count; j++)
                {
                    DataRow toInsert = dts.NewRow();
                    int k = 0;
                    int inc = 0;
                    for (k = 0; k < grdProfitAndLoss.Columns.Count; k++)
                    {
                        if (grdProfitAndLoss.Columns[k].Visible == false) { continue; }
                        toInsert[inc] = grdProfitAndLoss.Rows[j].Cells[k].Value;
                        inc++;
                    }
                    dts.Rows.Add(toInsert);
                }
                dts.AcceptChanges();
                ExcelUtlity obj = new ExcelUtlity();
                obj.WriteDataTableToExcel(dts, "Profit And Loss", sfd.FileName, "Profit And Loss");
                MessageBox.Show("Exported Successfully");
            }
        }
        catch (Exception ex)
        {

        }

write multiple lines in a file in python

Assuming you don't want a space at each new line use:

print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))

This works for version 3.6

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

How to properly exit a C# application?

By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?

In short, yes. The entire application will end when the main form (the form started via Application.Run in the Main method) is closed (not hidden).

If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.

If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.

How to solve java.lang.NoClassDefFoundError?

Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:

1.firstly, create the instance of class in a simple thread and catch the crash.

2.then call the field method of Class in main thread, you will get the NoClassDefFoundError.

here is the test code:

public class MyClass{
       private static  Handler mHandler = new Handler();
       public static int num = 0;
}

in your onCrete method of Main activity, add test code part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //test code start
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MyClass myClass = new MyClass();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }).start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    MyClass.num = 3;
    // end of test code
}

there is a simple way to fix it using a handlerThread to init handler:

private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
    handlerThread.start();
    mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}

__FILE__ macro shows full path

Since you are using GCC, you can take advantage of

__BASE_FILE__ This macro expands to the name of the main input file, in the form of a C string constant. This is the source file that was specified on the command line of the preprocessor or C compiler

and then control how you want to display the filename by changing the source file representation (full path/relative path/basename) at compilation time.

How to resize array in C++?

Raw arrays aren't resizable in C++.

You should be using something like a Vector class which does allow resizing..

std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).

SQL Server: Difference between PARTITION BY and GROUP BY

When you use GROUP BY, the resulting rows will be usually less then incoming rows.

But, when you use PARTITION BY, the resulting row count should be the same as incoming.

Python Git Module experiences?

For the record, none of the aforementioned Git Python libraries seem to contain a "git status" equivalent, which is really the only thing I would want since dealing with the rest of the git commands via subprocess is so easy.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

How can I get a precise time, for example in milliseconds in Objective-C?

You can get current time in milliseconds since January 1st, 1970 using an NSDate:

- (double)currentTimeInMilliseconds {
    NSDate *date = [NSDate date];
    return [date timeIntervalSince1970]*1000;
}

Rails 4 - passing variable to partial

Either

render partial: 'user', locals: {size: 30}

Or

render 'user', size: 30

To use locals, you need partial. Without the partial argument, you can just list variables directly (not within locals)

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

How is this usually done? Should I copy the cmake/ directory of SomeLib into my project and set the CMAKE_MODULE_PATH relatively?

If you don't trust CMake to have that module, then - yes, do that - sort of: Copy the find_SomeLib.cmake and its dependencies into your cmake/ directory. That's what I do as a fallback. It's an ugly solution though.

Note that the FindFoo.cmake modules are each a sort of a bridge between platform-dependence and platform-independence - they look in various platform-specific places to obtain paths in variables whose names is platform-independent.

Spring @Transactional - isolation, propagation

You can use like this:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public EventMessage<ModificaOperativitaRapporto> activate(EventMessage<ModificaOperativitaRapporto> eventMessage) {
//here some transaction related code
}

You can use this thing also:

public interface TransactionStatus extends SavepointManager {
    boolean isNewTransaction();
    boolean hasSavepoint();
    void setRollbackOnly();
    boolean isRollbackOnly();
    void flush();
    boolean isCompleted();
}

Facebook development in localhost

Edit: 2-15-2012 This is how to use FB authentication for a localhost website.

I find it more scalable and convenient to set up a second Facebook app. If I'm building MyApp, then I'll make a second one called MyApp-dev.

  • Create a new app at https://developers.facebook.com/apps
  • (New 2/15/2012) Click the Website checkbox under 'Select how your application integrates with Facebook' (In the recent Facebook version you can find this under Settings > Basic > Add Platform - Then select website)
  • Set the Site URL field (NOT the App Domains field) to http://www.localhost:3000 (this address is for Ruby on Rails, change as needed)

enter image description here

  • In your application initializer, put in code to detect the environment
    • Sample Rails 3 code
      if Rails.env == 'development' || Rails.env == 'test'
        Rails.application.config.middleware.use OmniAuth::Builder do
          provider :facebook, 'DEV_APP_ID', 'DEV_APP_SECRET'
        end
      else
        # Production
        Rails.application.config.middleware.use OmniAuth::Builder do
          provider :facebook, 'PRODUCTION_APP_ID', 'PRODUCTION_APP_SECRET'
        end
      end
      

I prefer this method because once it's set up, coworkers and other machines don't have additional setup.

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

To use the class ActionBarOverlayLayout you need to include this in the dependencies section of build.gradle file:

compile 'com.android.support:design:24.1.1'

Sync the project once again and then you will find no problem

Check if String / Record exists in DataTable

You can loop over each row of the DataTable and check the value.

I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
    if (dr["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
}

Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

DataTable workTable = new DataTable("Customers");

// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };

Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
    // do your deed
}

Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);

foreach (DataRow dr in drFound)
{
    // do you deed. Each record here was already found to match your criteria
}

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Command line for looking at specific port

As noted elsewhere: use netstat, with appropriate switches, and then filter the results with find[str]

Most basic:

netstat -an | find ":N"

or

netstat -a -n | find ":N"

To find a foreign port you could use:

netstat -an | findstr ":N[^:]*$"

To find a local port you might use:

netstat -an | findstr ":N.*:[^:]*$"

Where N is the port number you are interested in.

-n ensures all ports will be numerical, i.e. not returned as translated to service names.

-a will ensure you search all connections (TCP, UDP, listening...)

In the find string you must include the colon, as the port qualifier, otherwise the number may match either local or foreign addresses.

You can further narrow narrow the search using other netstat switches as necessary...

Further reading (^0^)

netstat /?

find /?

findstr /?

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

Pass Javascript Variable to PHP POST

You can do this using Ajax. I have a function that I use for something like this:

function ajax(elementID,filename,str,post)
{
    var ajax;
    if (window.XMLHttpRequest)
    {
        ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
    }
    else if (ActiveXObject("Microsoft.XMLHTTP"))
    {
        ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
    }
    else if (ActiveXObject("Msxml2.XMLHTTP"))
    {
        ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
    }
    else
    {
        alert("Error: Your browser does not support AJAX.");
        return false;
    }
    ajax.onreadystatechange=function()
    {
        if (ajax.readyState==4&&ajax.status==200)
        {
            document.getElementById(elementID).innerHTML=ajax.responseText;
        }
    }
    if (post==false)
    {
        ajax.open("GET",filename+str,true);
        ajax.send(null);
    }
    else
    {
        ajax.open("POST",filename,true);
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        ajax.send(str);
    }
    return ajax;
}

The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.