Programs & Examples On #Rpm spec

The rpm spec file contains the information required by RPM to build a package.

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Typical mainframe flow...

Input Disk/Tape/User (runtime) --> Job Control Language (JCL) --> Output Disk/Tape/Screen/Printer
                                   |                          ^
                                   v                          |
                                   `--> COBOL Program --------' 

Typical Linux flow...

Input Disk/SSD/User (runtime) --> sh/bash/ksh/zsh/... ----------> Output Disk/SSD/Screen/Printer
                                   |                          ^
                                   v                          |
                                   `--> Python script --------'
                                   |                          ^
                                   v                          |
                                   `--> awk script -----------'
                                   |                          ^
                                   v                          |
                                   `--> sed script -----------'
                                   |                          ^
                                   v                          |
                                   `--> C/C++ program --------'
                                   |                          ^
                                   v                          |
                                   `--- Java program ---------'
                                   |                          ^
                                   v                          |
                                   :                          :

Shells are the glue of Linux

Linux shells like sh/ksh/bash/... provide input/output/flow-control designation facilities much like the old mainframe Job Control Language... but on steroids! They are Turing complete languages in their own right while being optimized to efficiently pass data and control to and from other executing processes written in any language the O/S supports.

Most Linux applications, regardless what language the bulk of the program is written in, depend on shell scripts and Bash has become the most common. Clicking an icon on the desktop usually runs a short Bash script. That script, either directly or indirectly, knows where all the files needed are and sets variables and command line parameters, finally calling the program. That's a shell's simplest use.

Linux as we know it however would hardly be Linux without the thousands of shell scripts that startup the system, respond to events, control execution priorities and compile, configure and run programs. Many of these are quite large and complex.

Shells provide an infrastructure that lets us use pre-built components that are linked together at run time rather than compile time. Those components are free-standing programs in their own right that can be used alone or in other combinations without recompiling. The syntax for calling them is indistinguishable from that of a Bash builtin command, and there are in fact numerous builtin commands for which there is also a stand-alone executable on the system, often having additional options.

There is no language-wide difference between Python and Bash in performance. It entirely depends on how each is coded and which external tools are called.

Any of the well known tools like awk, sed, grep, bc, dc, tr, etc. will leave doing those operations in either language in the dust. Bash then is preferred for anything without a graphical user interface since it is easier and more efficient to call and pass data back from a tool like those with Bash than Python.

Performance

It depends on which programs the Bash shell script calls and their suitability for the subtask they are given whether the overall throughput and/or responsiveness will be better or worse than the equivalent Python. To complicate matters Python, like most languages, can also call other executables, though it is more cumbersome and thus not as often used.

User Interface

One area where Python is the clear winner is user interface. That makes it an excellent language for building local or client-server applications as it natively supports GTK graphics and is far more intuitive than Bash.

Bash only understands text. Other tools must be called for a GUI and data passed back from them. A Python script is one option. Faster but less flexible options are the binaries like YAD, Zenity, and GTKDialog.

While shells like Bash work well with GUIs like Yad, GtkDialog (embedded XML-like interface to GTK+ functions), dialog, and xmessage, Python is much more capable and so better for complex GUI windows.

Summary

Building with shell scripts is like assembling a computer with off-the-shelf components the way desktop PCs are.

Building with Python, C++ or most any other language is more like building a computer by soldering the chips (libraries) and other electronic parts together the way smartphones are.

The best results are usually obtained by using a combination of languages where each can do what they do best. One developer calls this "polyglot programming".

CRON job to run on the last day of the month

#########################################################
# Memory Aid 
# environment    HOME=$HOME SHELL=$SHELL LOGNAME=$LOGNAME PATH=$PATH
#########################################################
#
# string         meaning
# ------         -------
# @reboot        Run once, at startup.
# @yearly        Run once a year, "0 0 1 1 *".
# @annually      (same as @yearly)
# @monthly       Run once a month, "0 0 1 * *".
# @weekly        Run once a week, "0 0 * * 0".
# @daily         Run once a day, "0 0 * * *".
# @midnight      (same as @daily)
# @hourly        Run once an hour, "0 * * * *".
#mm     hh      Mday    Mon     Dow     CMD # minute, hour, month-day month DayofW CMD
#........................................Minute of the hour
#|      .................................Hour in the day (0..23)
#|      |       .........................Day of month, 1..31 (mon,tue,wed)
#|      |       |       .................Month (1.12) Jan, Feb.. Dec
#|      |       |       |        ........day of the week 0-6  7==0
#|      |       |       |        |      |command to be executed
#V      V       V       V        V      V
*       *       28-31   *       *       [ `date -d +'1 day' +\%d` -eq 1 ] && echo "Tomorrow is the first today now is  `date`" >> ~/message
1       0       1       *       *       rm -f ~/message
*       *       28-31   *       *       [ `date -d +'1 day' +\%d` -eq 1 ] && echo "HOME=$HOME LOGNAME=$LOGNAME SHELL = $SHELL PATH=$PATH" 

How can I write text on a HTML5 canvas element?

_x000D_
_x000D_
var canvas = document.getElementById("my-canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
_x000D_
context.fillStyle = "blue";_x000D_
context.font = "bold 16px Arial";_x000D_
context.fillText("Zibri", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
_x000D_
#my-canvas {_x000D_
  background: #FF0;_x000D_
}
_x000D_
<canvas id="my-canvas" width="200" height="120"></canvas>
_x000D_
_x000D_
_x000D_

Tomcat 7 is not running on browser(http://localhost:8080/ )

1)Goto Server tab 2)Right on server -> general -> click on switch location. 3)Double click on the server -> under server location -> select tomcat installation. 4) restart the server.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How to select clear table contents without destroying the table?

How about:

ACell.ListObject.DataBodyRange.Rows.Delete

That will keep your table structure and headings, but clear all the data and rows.

EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
   .DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With

If you want to leave all the rows intact with their formulas and whatnot, just do:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With

Which is close to what @Readify suggested, except it won't clear formulas.

Remove an item from a dictionary when its key is unknown

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping

Count how many rows have the same value

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

Row numbers in query result using Microsoft Access

Thanks for your solutions above! DCount did the trick for me too!

I had to use a combination of date columns and a unique identifier for the sorting portion of it (as well as some additional conditions), so here is what I ended up doing: 1) I had to check if DateColumnA was null, then check if DateColumnB was null, then use DateColumnC; then, if multiple records have the same date value, they all end up with the same id! 2) So, I figured I would use the integer unique ID of the table, and add it up to the time as "minutes". This will always provide different results 3) Finally, the logic above results in the count starting in 0... so just add 1!

SELECT 
 1+DCount("[RequestID]","[Request]","Archived=0 and ProjectPhase <> 2 and iif(isnull(DateColumnA)=true,iif(isnull(DateColumnB)=true,DateColumnC,DateColumnB),DateColumnA)+(RequestID/3600) < #" & if(isnull(DateColumnA)=true,iif(isnull(DateColumnB)=true,DateColumnC,DateColumnB),DateColumnA) + (RequestID/3600) & "#") AS RowID, 
FROM 
 Request
ORDER BY 1

I hope this helps you out!

Validate that text field is numeric usiung jQuery

This should work. I would trim the whitespace from the input field first of all:

if($('#Field').val() != "") {
    var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(!intRegex.test(value)) {
        errors += "Field must be numeric.<br/>";
        success = false;
    }
} else {
    errors += "Field is blank.</br />";
    success = false;
}

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Well, it's fairly self-explanatory: you've run out of memory.

You may want to try starting it with more memory, using the -Xmx flag, e.g.

java -Xmx2048m [whatever you'd have written before]

This will use up to 2 gigs of memory.

See the non-standard options list for more details.

Regular expression to match balanced parentheses

This might help to match balanced parenthesis.

\s*\w+[(][^+]*[)]\s*

Select statement to find duplicates on certain fields

To see duplicate values:

with MYCTE  as (
    select row_number() over ( partition by name  order by name) rown, *
    from tmptest  
    ) 
select * from MYCTE where rown <=1

How to convert an Array to a Set in Java

Like this:

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

In Java 9+, if unmodifiable set is ok:

Set<T> mySet = Set.of(someArray);

In Java 10+, the generic type parameter can be inferred from the arrays component type:

var mySet = Set.of(someArray);

remove item from array using its name / value

Array.prototype.removeValue = function(name, value){
   var array = $.map(this, function(v,i){
      return v[name] === value ? null : v;
   });
   this.length = 0; //clear original array
   this.push.apply(this, array); //push all elements except the one we want to delete
}

countries.results.removeValue('name', 'Albania');

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

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

Note that -(NSString *)tableView: titleForHeaderInSection: is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section is implemented in delegate of UITableView;

Protect image download

As some people already said that it is not possible to prevent people to download your pictures, a trick could be something like this:

$(document).ready(function()
{
    $('img').bind('contextmenu', function(e){
        return false;
    }); 
});

This trick prevents from the right click on all img. Obviously people can open the source code and download the images using links in your source code.

Checking for an empty field with MySQL

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

Running code in main thread from another thread

One method I can think of is this:

1) Let the UI bind to the service.
2) Expose a method like the one below by the Binder that registers your Handler:

public void registerHandler(Handler handler) {
    mHandler = handler;
}

3) In the UI thread, call the above method after binding to the service:

mBinder.registerHandler(new Handler());

4) Use the handler in the Service's thread to post your task:

mHandler.post(runnable);

Connection refused on docker container

If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:

It is assumed that you are running with publish command like below.

docker run -it -p 8080:8080 demo

With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.

Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

I think that replacing:

List<String> list = Arrays.asList(split);

with

List<String> list = new ArrayList<String>(Arrays.asList(split));

resolves the problem.

Get key and value of object in JavaScript?

$.each(top_brands, function(index, el) {
  for (var key in el) {
    if (el.hasOwnProperty(key)) {
         brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
    }
  }
});

But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};, then thing will be much more simple.

for (var key in top_brands) {
  if (top_brands.hasOwnProperty(key)) {
       brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
  }
}

Or use the jquery each:

$.each(top_brands, function(key, value) {
    brand_options.append($("<option />").val(key).text(key + " "  + value));
});

Managing large binary files with Git

Have a look at git bup which is a Git extension to smartly store large binaries in a Git repository.

You'd want to have it as a submodule, but you won't have to worry about the repository getting hard to handle. One of their sample use cases is storing VM images in Git.

I haven't actually seen better compression rates, but my repositories don't have really large binaries in them.

Your mileage may vary.

How do I make a new line in swift

You can use the following code;

var example: String = "Hello World \r\n This is a new line"

How can I wrap or break long text/word in a fixed width span?

Try following css with addition of white-space:

span {
    display: block;
    word-wrap:break-word;
    width: 50px;
    white-space: normal
}

Instantly detect client disconnection from server socket

Using the method SetSocketOption, you will be able to set KeepAlive that will let you know whenever a Socket gets disconnected

Socket _connectedSocket = this._sSocketEscucha.EndAccept(asyn);
                _connectedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

http://msdn.microsoft.com/en-us/library/1011kecd(v=VS.90).aspx

Hope it helps! Ramiro Rinaldi

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

This answer might also be helpful, it leverages js reduce operator/method to remove duplicates from array.

_x000D_
_x000D_
const result = [1, 2, 2, 3, 3, 3, 3].reduce((x, y) => x.includes(y) ? x : [...x, y], []);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to pass data from Javascript to PHP and vice versa?

There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.

<script language="javascript" type="text/javascript">
 function _vals(target, value){
   form1.all("target").value=target;
   form1.all("value").value=value;
   form1.submit();
 }
</script>

Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.

I'm sure there's probably more methods which are better, but these are just a few that spring to mind.

EDIT: Building on this from what others have said using the above method you would have an anchor tag like

<a onclick="_vals('name', 'val')" href="#">My Link</a>

And then in your PHP you can get form data using

$val = $_POST['value'];

So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.

jQuery Set Cursor Position in Text Area

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

Random shuffling of an array

The most simple solution for this Random Shuffling in an Array.

String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[i]);
}

onclick go full screen

It's possible with JavaScript.

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
  elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

How to change button text or link text in JavaScript?

Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

How to remove an element slowly with jQuery?

I'm little late to the party, but for anyone like me that came from a Google search and didn't find the right answer. Don't get me wrong there are good answers here, but not exactly what I was looking for, without further ado, here is what I did:

_x000D_
_x000D_
$(document).ready(function() {
    
    var $deleteButton = $('.deleteItem');

    $deleteButton.on('click', function(event) {
      event.preventDefault();

      var $button = $(this);

      if(confirm('Are you sure about this ?')) {

        var $item = $button.closest('tr.item');

        $item.addClass('removed-item')
        
            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
          
                $(this).remove();
        });
      }
      
    });
    
});
_x000D_
/**
 * Credit to Sara Soueidan
 * @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-4.css
 */

.removed-item {
    -webkit-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
    -o-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
    animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards
}

@keyframes removed-item-animation {
    from {
        opacity: 1;
        -webkit-transform: scale(1);
        -ms-transform: scale(1);
        -o-transform: scale(1);
        transform: scale(1)
    }

    to {
        -webkit-transform: scale(0);
        -ms-transform: scale(0);
        -o-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}

@-webkit-keyframes removed-item-animation {
    from {
        opacity: 1;
        -webkit-transform: scale(1);
        transform: scale(1)
    }

    to {
        -webkit-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}

@-o-keyframes removed-item-animation {
    from {
        opacity: 1;
        -o-transform: scale(1);
        transform: scale(1)
    }

    to {
        -o-transform: scale(0);
        transform: scale(0);
        opacity: 0
    }
}
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
  
  <table class="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th>id</th>
        <th>firstname</th>
        <th>lastname</th>
        <th>@twitter</th>
        <th>action</th>
      </tr>
    </thead>
    <tbody>
      
      <tr class="item">
        <td>1</td>
        <td>Nour-Eddine</td>
        <td>ECH-CHEBABY</td>
        <th>@__chebaby</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
      
      <tr class="item">
        <td>2</td>
        <td>John</td>
        <td>Doe</td>
        <th>@johndoe</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
      
      <tr class="item">
        <td>3</td>
        <td>Jane</td>
        <td>Doe</td>
        <th>@janedoe</th>
        <td><button class="btn btn-danger deleteItem">Delete</button></td>
      </tr>
    </tbody>
  </table>
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


</body>
</html>
_x000D_
_x000D_
_x000D_

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

Calculating percentile of dataset column

Using {dplyr}:

library(dplyr)

# percentiles
infert %>% 
  mutate(PCT = ntile(age, 100))

# quartiles
infert %>% 
  mutate(PCT = ntile(age, 4))

# deciles
infert %>% 
  mutate(PCT = ntile(age, 10))

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

UILabel Align Text to center

From iOS 6 and later UITextAlignment is deprecated. use NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Swift Version from iOS 6 and later

myLabel.textAlignment = .center

Can we pass parameters to a view in SQL?

I have an idea that I haven't tried yet. You can do:

CREATE VIEW updated_customers AS
SELECT * FROM customer as aa
LEFT JOIN customer_rec as bb
ON aa.id = bb.customer_id
WHERE aa.updated_at between (SELECT start_date FROM config WHERE active = 1) 
and (SELECT end_date FROM config WHERE active = 1)

Your parameters will be saved and changed in the Config table.

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

AJAX jQuery refresh div every 5 seconds

Try using setInterval and include jquery library and just try removing unwrap()

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

var timeout = setInterval(reloadChat, 5000);    
function reloadChat () {

     $('#links').load('test.php');
}
</script>

UPDATE

you are using a jquery old version so include the latest jquery version

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

Initializing IEnumerable<string> In C#

public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

Equivalent function for DATEADD() in Oracle

Equivalent will be

ADD_MONTHS( SYSDATE, -6 )

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

How do I change the default application icon in Java?

java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");

May or may not require a '/' at the front of the path.

How to manually install an artifact in Maven 2?

If you ever get similar errors when using Windows PowerShell, you should try Windows' simple command-line. I didn't find out what caused this, but PowerShell seems to interpret some of Maven's parameters.

How to generate the whole database script in MySQL Workbench?

In MySQL Workbench 6, commands have been repositioned as the "Server Administration" tab is gone.

You now find the option "Data Export" under the "Management" section when you open a standard server connection.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!

as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];

you have to pass this two variable from the retrofit.

as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'

I hope it helps you.

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

SQL Plus change current directory

I don't think you can!

/home/export/user1 $ sqlplus / 
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql

script2.sql has to be in /home/export/user1.

You either use the full path, or exit the script and start sqlplus again from the right directory.

#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql

(something like that - doing this from memory!)

Getting current device language in iOS?

For Swift 3:

NSLocale.preferredLanguages[0] as String

Changing button color programmatically

I have finally found a working code - try this:

document.getElementById("button").style.background='#000000';

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

What are some resources for getting started in operating system development?

I would like to include this repo How-to-Make-a-Computer-Operating-System by Samy Pesse. Is a work-in-progress. Very interesting.

How to obtain the chat_id of a private Telegram channel?

You Can Too Do This:

Step 1)Convert Your Private Channel To Public Channel

Step 2)Set The ChannelName For This Channel

Step 3)then you Can change this Channel to Private

Step 4)Now Sending Your Message Using @ChannelName That you Set In Step 3

note:For Step 1 You Can Change One of Your Public Channel To Private For a short time.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

The answer posted here by simon-sarris helped me.

This helped me solve my issue.

The Visual Studio installer must have added an errant line to the registry.

open up regedit and take a look at this registry key:

enter image description here

See that key? The Content Type key? change its value from text/plain to text/javascript.

Finally chrome can breathe easy again.

I should note that neither Content Type nor PercievedType are there by default on Windows 7, so you could probably safely delete them both, but the minimum you need to do is that edit.

Anyway I hope this fixes it for you too!

Don't forget to restart your system after the changes.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

Read connection string from web.config

C#

// Add a using directive at the top of your code file    
using System.Configuration;

// Within the code body set your variable    
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;

VB

' Add an Imports statement at the top of your code file    
Imports System.Configuration

' Within the code body set your variable    
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString

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

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

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

   Adobe Reader Preferences dialog

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

   Adobe Reader Read Mode toolbar button

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

#toolbar=0&navpanes=0

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

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

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

What is so bad about singletons?

It's not that singletons themselves are bad but the GoF design pattern is. The only really argument that is valid is that the GoF design pattern doesn't lend itself in regards to testing, especially if tests are run in parallel.

Using a single instance of an class is a valid construct as long as you apply the following means in code:

  1. Make sure the class that will be used as a singleton implements an interface. This allows stubs or mocks to be implemented using the same interface

  2. Make sure that the Singleton is thread-safe. That's a given.

  3. The singleton should be simple in nature and not overly complicated.

  4. During the runtime of you application, where singletons need to be passed to a given object, use a class factory that builds that object and have the class factory pass the singleton instance to the class that needs it.

  5. During testing and to ensure deterministic behavior, create the singleton class as separate instance as either the actual class itself or a stub/mock that implements its behavior and pass it as is to the class that requires it. Don't use the class factor that creates that object under test that needs the singleton during test as it will pass the single global instance of it, which defeats the purpose.

We've used Singletons in our solutions with a great deal of success that are testable ensuring deterministic behavior in parallel test run streams.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

The standard Ubuntu install seems to put the various Java versions in /usr/lib/jvm. The javac, java you find in your path will softlink to this.

There's no issue with installing your own Java version anywhere you like, as long as you set the JAVA_HOME environment variable and make sure to have the new Java bin on your path.

A simple way to do this is to have the Java home exist as a softlink, so that if you want to upgrade or switch versions you only have to change the directory that this points to - e.g.:

/usr/bin/java --> /opt/jdk/bin/java,

/opt/jdk --> /opt/jdk1.6.011

How to list the properties of a JavaScript object?

With ES6 and later (ECMAScript 2015), you can get all properties like this:

let keys = Object.keys(myObject);

And if you wanna list out all values:

let values = Object.keys(myObject).map(key => myObject[key]);

How can I take an UIImage and give it a black border?

This function will return you image with black border try this.. hope this will help you

- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
    CGSize size = CGSizeMake(image.size.width,image.size.height);
    UIGraphicsBeginImageContext(size);

    CGPoint thumbPoint = CGPointMake(0,0);

    [image drawAtPoint:thumbPoint];


    UIGraphicsBeginImageContext(size);
    CGImageRef imgRef = blackBorderImage.CGImage;
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGPoint starredPoint = CGPointMake(0, 0);
    [imageCopy drawAtPoint:starredPoint];
    UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageC;
}

How to represent a DateTime in Excel

You can set date time values to a cell in XlsIO using one of these options

sheet.Range["A1"].Value2 = DateTime.Now;
sheet.Range["A1"].NumberFormat = "dd/mm/yyyy";

sheet.Range["A2"].DateTime = DateTime.Now;
sheet.Range["A2"].NumberFormat = "[$-409]d-mmm-yy;@";

You can find more information here.

How to create a fix size list in python?

It's not really the python way to initialize lists like this. Anyway, you can initialize a list like this:

>>> l = [None] * 4
>>> l
[None, None, None, None]

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Check an integer value is Null in c#

Because int is a ValueType then you can use the following code:

if(Age == default(int) || Age == null)

or

if(Age.HasValue && Age != 0) or if (!Age.HasValue || Age == 0)

Regex matching in a Bash if statement

Or you might be looking at this question because you happened to make a silly typo like I did and have the =~ reversed to ~=

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

Nginx 403 error: directory index of [folder] is forbidden

  1. Check that index.html or index.php is not missing in the directory
  2. See the error log file which is location in /var/log/nginx and then open vim error.log

How to detect escape key press with pure JS or jQuery?

On Firefox 78 use this ("keypress" doesn't work for Escape key):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);

Format timedelta to string

def td_format(td_object):
    seconds = int(td_object.total_seconds())
    periods = [
        ('year',        60*60*24*365),
        ('month',       60*60*24*30),
        ('day',         60*60*24),
        ('hour',        60*60),
        ('minute',      60),
        ('second',      1)
    ]

    strings=[]
    for period_name, period_seconds in periods:
        if seconds > period_seconds:
            period_value , seconds = divmod(seconds, period_seconds)
            has_s = 's' if period_value > 1 else ''
            strings.append("%s %s%s" % (period_value, period_name, has_s))

    return ", ".join(strings)

Check if TextBox is empty and return MessageBox?

Try doing the following

if (String.IsNullOrEmpty(MaterialTextBox.Text) || String.IsNullOrWhiteSpace(MaterialTextBox.Text))
    {
        //do job
    }
    else
    {
        MessageBox.Show("Please enter correct path");
    }

Hope it helps

NGinx Default public www location?

Dump the configuration:

$ nginx -T
...
server {
    ...
    location / {
        root   /usr/share/nginx/html;
        ...
    }
    ...
}

What you get might be different since it depends on how your nginx was configured/installed.

References:

Update: There's some confusion on the issue of if/when the -T option was added to nginx. It was documented in the man page by vl-homutov on 2015 June 16, which became part of the v1.9.2 release. It's even mentioned in the release notes. The -T option has been present in every nginx release since, including the one available on Ubuntu 16.04.1 LTS:

root@23cc8e58640e:/# nginx -h    
nginx version: nginx/1.10.0 (Ubuntu)
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

Table-level backup

You cannot use the BACKUP DATABASE command to backup a single table, unless of course the table in question is allocated to it's own FILEGROUP.

What you can do, as you have suggested is Export the table data to a CSV file. Now in order to get the definition of your table you can 'Script out' the CREATE TABLE script.

You can do this within SQL Server Management Studio, by:

right clicking Database > Tasks > Generate Script

You can then select the table you wish to script out and also choose to include any associated objects, such as constraints and indexes.

in order to get the DATA along with just the schema, you've got to choose Advanced on the set scripting options tab, and in the GENERAL section set the Types of data to script select Schema and Data

Hope this helps but feel free to contact me directly if you require further assitance.

\r\n, \r and \n what is the difference between them?

All 3 of them represent the end of a line. But...

  • \r (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
  • \n (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n moves to the beginning of the line.
  • \r\n (End Of Line) → a combination of \r and \n

Java :Add scroll into text area

After adding JTextArea into JScrollPane here:

scroll = new JScrollPane(display);

You don't need to add it again into other container like you do:

middlePanel.add(display);

Just remove that last line of code and it will work fine. Like this:

    middlePanel=new JPanel();
    middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

    // create the middle panel components

    display = new JTextArea(16, 58);
    display.setEditable(false); // set textArea non-editable
    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    //Add Textarea in to middle panel
    middlePanel.add(scroll);

JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:

new JScrollPane( myComponent ) 

or set view like this:

JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );

Additional:

Here is fully working example since you still did not get it working:

public static void main ( String[] args )
{
    JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );

    // My code
    JFrame frame = new JFrame ();
    frame.add ( middlePanel );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

And here is what you get: enter image description here

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

Unable to use Intellij with a generated sources folder

With gradle, the project settings will be cleared whenever you refresh the gradle settings. Instead you need to add the following lines (or similar) in your build.gradle, I'm using kotlin so:

sourceSets {
    main {
        java {
            srcDir "${buildDir.absolutePath}/generated/source/kapt/main"
        }
    }
}

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Make sure you have downloaded Support Repository to use support library dependency in build.gradle.

enter image description here

If these all are there already installed sync your project with gradle once using the button available.

sync button

How can I download HTML source in C#

@cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!

problem: if you use an url like this: www.somesite.it/?p=1500 in some case you get an internal server error (500), although in web browser this www.somesite.it/?p=1500 perfectly work.

solution: you have to move out parameters, working code is:

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}

here official documentation

Who is listening on a given TCP port on Mac OS X?

On macOS, here's an easy way to get the process ID that's listening on a specific port with netstat. This example looks for a process serving content on port 80:

find server running on port 80

netstat -anv | egrep -w [.]80.*LISTEN

sample output

tcp4  0 0  *.80       *.*    LISTEN      131072 131072    715      0

The 2nd from the last column is the PID. In above, it's 715.

options

-a - show all ports, including those used by servers

-n - show numbers, don't look up names. This makes the command a lot faster

-v - verbose output, to get the process IDs

-w - search words. Otherwise the command will return info for ports 8000 and 8001, not just "80"

LISTEN - give info only for ports in LISTEN mode, i.e. servers

How can I conditionally require form inputs with AngularJS?

For Angular 2

<input [(ngModel)]='email' [required]='!phone' />
<input [(ngModel)]='phone' [required]='!email' /> 

How to get rid of punctuation using NLTK tokenizer?

Sincerely asking, what is a word? If your assumption is that a word consists of alphabetic characters only, you are wrong since words such as can't will be destroyed into pieces (such as can and t) if you remove punctuation before tokenisation, which is very likely to affect your program negatively.

Hence the solution is to tokenise and then remove punctuation tokens.

import string

from nltk.tokenize import word_tokenize

tokens = word_tokenize("I'm a southern salesman.")
# ['I', "'m", 'a', 'southern', 'salesman', '.']

tokens = list(filter(lambda token: token not in string.punctuation, tokens))
# ['I', "'m", 'a', 'southern', 'salesman']

...and then if you wish, you can replace certain tokens such as 'm with am.

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

How to change package name in flutter?

Even if my answer wont be accepted as the correct answer, I just feel all these answers above caused me to have more problems here is how I fixed it

  1. Get Sublime Text (crazy, right? No, just follow my steps)
  2. Click on file and select open folder, then choose the folder of the project you are working on
  3. Now click on Find from the Tabs, and select find in files or just do Ctrl + Shift + F (for Windows users, for mac users you already know the drill)
  4. Now copy and paste exactly the name of the package you want to change in the Find section and paste in the replace section what you would like to replace the package name with.
  5. Click on FIND (do not click on REPLACE just yet).
  6. Now clicking on Find lists all available package name in your project which matches your search criteria, if you are satisfied with this then repeat from no. 3 but this time click on REPLACE.
  7. Rebuild your project and have fun

Conclusion: a simple find and replace program is all you need to sort this problem out, and I strongly recommend Sublime Text 3 for that.

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to downgrade Node version

This may be due to version incompatibility between your code and the version you have installed.

In my case I was using v8.12.0 for development (locally) and installed latest version v13.7.0 on the server.

So using nvm I switched the node version to v8.12.0 with the below command:

> nvm install 8.12.0 // to install the version I wanted

> nvm use 8.12.0  // use the installed version

NOTE: You need to install nvm on your system to use nvm.

You should try this solution before trying solutions like installing build-essentials or uninstalling the current node version because you could switch between versions easily than reverting all the installations/uninstallations that you've done.

SVN remains in conflict?

If you are using the Eclipse IDE and stumble upon this error when committing, here's an in-tool solution for you. I'm using Subclipse, but the solution for Subversive could be similar.

What you maybe didn't notice is that there is an additional symbol on the conflicting file, which marks the file indeed as "conflicted".

Right-click on the file, choose "Team" and "Edit conflicts...". Choose the appropriate action. I merged the file manually on text-level before, so I took the first option, which will take the current state of your local copy as "resolved solution". Now hit "OK" and that's it.

The conflicting symbol should have disappeared and you should be able to commit again.

cordova Android requirements failed: "Could not find an installed version of Gradle"

I m using Cordova version 7.0.1 and Cordova android version is 6.2.3. I was facing the issue while performing android build. I m using only Cordova CLI and not using android studio at all.

The quick workaround for this issue before its official fixed in Cordova is as follows:

  1. Look for check_reqs.js file under platforms\android\cordova\lib folder
  2. Edit the else part of androidStudioPath variable null check in get_gradle_wrapper function as below:

Existing code:

else { //OK, let's try to check for Gradle! return forgivingWhichSync('gradle'); }

Modified code:

else { //OK, let's try to check for Gradle! var sdkDir = process.env['ANDROID_HOME']; return path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper', 'gradlew'); }

NOTE: This change needs to be done everytime when the android platform is removed and re-added

UPDATE: In my case, I already had gradle wrapper inside my android SDK and I dint find necessity to install gradle explicitly. Hence, I made this workaround to minimize my impact and effort

Rails Object to hash

You could definitely use the attributes to return all attributes but you could add an instance method to Post, call it "to_hash" and have it return the data you would like in a hash. Something like

def to_hash
 { name: self.name, active: true }
end

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

How to include *.so library in Android Studio?

This is my build.gradle file, Please note the line

jniLibs.srcDirs = ['libs']

This will include libs's *.so file to apk.

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
        jniLibs.srcDirs = ['libs']
    }

    // Move the tests to tests/java, tests/res, etc...
    instrumentTest.setRoot('tests')

    // Move the build types to build-types/<type>
    // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
    // This moves them out of them default location under src/<type>/... which would
    // conflict with src/ being used by the main source set.
    // Adding new build types or product flavors should be accompanied
    // by a similar customization.
    debug.setRoot('build-types/debug')
    release.setRoot('build-types/release')
}

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Callback when DOM is loaded in react.js

The below is what I came up with to wait for when the DOM is ready before trying to get a class using document.getElementsByClassName. I called this function from the componentDidMount() lifecycle method.

     changeIcon() {
            if (
                document.getElementsByClassName('YOURCLASSNAME')
                    .length > 0 &&
                document.getElementsByClassName('YOURCLASSNAME').length > 0
            ) {
                document.getElementsByClassName(
                    'YOURCLASSNAME'
                )[0].className = 'YOUR-NEW-CLASSNAME';
                document.getElementsByClassName(
                    'YOUR-OTHER-EXISTING-CLASSNAME'
                )[0].style.display = 'block';
            } else {
                setTimeout(this.changeIcon, 500);
            }
     }

Removing multiple keys from a dictionary safely

It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.

from itertools import product
from time import perf_counter

# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}
print(len(cells))

print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000

keys = product(range(50000, 100000), range(1, 100))

# for x,y in keys:
#     del cells[x, y]

for n in map(cells.pop, keys):
    pass

print(len(cells))
stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")

10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map and pop, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:

keys = cells.keys() & keys

In summary: del is already heavily optimised, so don't worry about using it.

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

How do you stash an untracked file?

I encountered a similar problem while using Sourcetree with newly created files (they wouldnt be included in the stash either).

When I first chose 'stage all' and then stash the newly added components where tracked and therefore included in the stash.

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

Detailed 500 error message, ASP + IIS 7.5

I have come to the same problem and fixed the same way as Alex K.

So if "Send Errors To Browser" is not working set also this:

Error Pages -> 500 -> Edit Feature Settings -> "Detailed Errors"

enter image description here

Also note that if the content of the error page sent back is quite short and you're using IE, IE will happily ignore the useful content sent back by the server and show you its own generic error page instead. You can turn this off in IE's options, or use a different browser.

How to detect the device orientation using CSS media queries?

I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:

For Mobile

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.

}


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

For Tablet

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

Desktop

make as per your design requirement enjoy...(:

Thanks, Jitu

How to access form methods and controls from a class in C#?

You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

public void DoSomethingWithText(string formText)
{
   // do something text in here
}

or exposing properties on your form class and setting the form text in there - eg

string SomeProperty
{
   get 
   {
      return textBox1.Text;
   }
   set
   {
      textBox1.Text = value;
   }
}

Transport security has blocked a cleartext HTTP

Go to your Info.plist

  1. Right Click on empty space and Click on Add Row
  2. Write the Key Name as NSAppTransportSecurity, Under it
  3. Select Exception Domains, Add a new item to this
  4. Write down your domain name that needs to get accessed
  5. Change the Domain type from String to Dictionary, add a new Item
  6. NSTemporaryExceptionAllowsInsecureHTTPLoads, that will be a boolean with a true value. Look at the picture to follow it correctly

How to make pylab.savefig() save image for 'maximized' window instead of default size

You set the size on initialization:

fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!

Edit:

If the problem is with x-axis ticks - You can set them "manually":

fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here

And so on with other aspects of Your plot. You can configure it all. Here's an example:

from numpy import arange
import matplotlib
# import matplotlib as mpl
import matplotlib.pyplot
# import matplotlib.pyplot as plt

x1 = [1,2,3]
y1 = [4,5,6]
x2 = [1,2,3]
y2 = [5,5,5]

# initialization
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # The size of the figure is specified as (width, height) in inches

# lines:
l1 = fig2.add_subplot(111).plot(x1,y1, label=r"Text $formula$", "r-", lw=2)
l2 = fig2.add_subplot(111).plot(x2,y2, label=r"$legend2$" ,"g--", lw=3)
fig2.add_subplot(111).legend((l1,l2), loc=0)

# axes:
fig2.add_subplot(111).grid(True)
fig2.add_subplot(111).set_xticks(arange(1,3,0.5))
fig2.add_subplot(111).axis(xmin=3, xmax=6) # there're also ymin, ymax
fig2.add_subplot(111).axis([0,4,3,6]) # all!
fig2.add_subplot(111).set_xlim([0,4])
fig2.add_subplot(111).set_ylim([3,6])

# labels:
fig2.add_subplot(111).set_xlabel(r"x $2^2$", fontsize=15, color = "r")
fig2.add_subplot(111).set_ylabel(r"y $2^2$")
fig2.add_subplot(111).set_title(r"title $6^4$")
fig2.add_subplot(111).text(2, 5.5, r"an equation: $E=mc^2$", fontsize=15, color = "y")
fig2.add_subplot(111).text(3, 2, unicode('f\374r', 'latin-1'))

# saving:
fig2.savefig("fig2.png")

So - what exactly do You want to be configured?

if statements matching multiple values

An extensionmethod like this would do it...

public static bool In<T>(this T item, params T[] items)
{
    return items.Contains(item);
}

Use it like this:

Console.WriteLine(1.In(1,2,3));
Console.WriteLine("a".In("a", "b"));

In a Git repository, how to properly rename a directory?

You can rename the directory using the file system. Then you can do git rm <old directory> and git add <new directory> (Help page). Then you can commit and push.

Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status

C# Sort and OrderBy comparison

In a nutshell :

List/Array Sort() :

  • Unstable sort.
  • Done in-place.
  • Use Introsort/Quicksort.
  • Custom comparison is done by providing a comparer. If comparison is expensive, it might be slower than OrderBy() (which allow to use keys, see below).

OrderBy/ThenBy() :

  • Stable sort.
  • Not in-place.
  • Use Quicksort. Quicksort is not a stable sort. Here is the trick : when sorting, if two elements have equal key, it compares their initial order (which has been stored before sorting).
  • Allows to use keys (using lambdas) to sort elements on their values (eg : x => x.Id). All keys are extracted first before sorting. This might result in better performance than using Sort() and a custom comparer.

Sources: MDSN, reference source and dotnet/coreclr repository (GitHub).

Some of the statements listed above are based on current .NET framework implementation (4.7.2). It might change in the future.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How to order results with findBy() in Doctrine

$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));

How to enable CORS on Firefox?

Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:

_x000D_
_x000D_
<?php_x000D_
  $file = file($_GET['url']);_x000D_
  echo implode('', $file);_x000D_
?>
_x000D_
_x000D_
_x000D_

javascript is doing this:

_x000D_
_x000D_
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
  if (this.readyState == 4 && this.status == 200) {_x000D_
    // File content is now in the this.responseText_x000D_
  }_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
_x000D_
_x000D_

In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

Making a request to a RESTful API using python

So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.

Raw Request

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

Sample call with Requests

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

It's actually a simple answer.

Your function is returning a string rather than the div node. appendChild can only append a node.

For example, if you try to appendChild the string:

var z = '<p>test satu dua tiga</p>'; // is a string 
document.body.appendChild(z);

The above code will never work. What will work is:

var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

How to implement 2D vector array?

//initialize the 2D vector first

vector<vector<int>> matrix;

//initialize the 1D vector you would like to insert into matrix

vector<int> row;

//initializing row with values

row.push_back(val1);

row.push_back(val2);

//now inserting values into matrix

matrix.push_back(row);

//output- [[val1,val2]]

How to change symbol for decimal point in double.ToString()?

Create an extension method?

Console.WriteLine(value.ToGBString());

// ...

public static class DoubleExtensions
{
    public static string ToGBString(this double value)
    {
        return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
    }
}

Removing duplicates from a String in Java

This is another approach

void remove_duplicate (char* str, int len) {
    unsigned int index = 0;
    int c = 0;
    int i = 0;
    while (c < len) {
        /* this is just example more check can be added for
           capital letter, space and special chars */

        int pos = str[c] - 'a';
        if ((index & (1<<pos)) == 0) {
            str[i++] = str[c];
            index |= (1<<pos);
        }
        c++;
    }
    str[i] = 0;
}

PHP Warning: Module already loaded in Unknown on line 0

I had the same issue after upgrading from Fedora Server 24 (PHP 5) to 25 (PHP 7). After investigation, I found that /etc/php.d/ had two different .ini files loading extension=geoip.so.

Previous version of distros had this file named 50-geoip.ini but the recent was changed to 40-geoip.ini, and I suspect that in the version-upgrade process the old hasn't been removed, while the new one has been created.

That was the actual case of the issue. After removing stray 50-geoip.ini from /etc/php.d/ and restarting httpd it just worked flawlessly.

Swift programmatically navigate to another view controller/scene

SWIFT 4.x

The Strings in double quotes always confuse me, so I think answer to this question needs some graphical presentation to clear this out.

For a banking app, I have a LoginViewController and a BalanceViewController. Each have their respective screens.

The app starts and shows the Login screen. When login is successful, app opens the Balance screen.

Here is how it looks:

enter image description here

enter image description here

The login success is handled like this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Balance", bundle: nil)
let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "balance") as! BalanceViewController
self.present(balanceViewController, animated: true, completion: nil)

As you can see, the storyboard ID 'balance' in small letters is what goes in the second line of the code, and this is the ID which is defined in the storyboard settings, as in the attached screenshot.

The term 'Balance' with capital 'B' is the name of the storyboard file, which is used in the first line of the code.

We know that using hard coded Strings in code is a very bad practice, but somehow in iOS development it has become a common practice, and Xcode doesn't even warn about them.

How do I prevent site scraping?

If you want to see a great example, check out http://www.bkstr.com/. They use a j/s algorithm to set a cookie, then reloads the page so it can use the cookie to validate that the request is being run within a browser. A desktop app built to scrape could definitely get by this, but it would stop most cURL type scraping.

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

Retrieving data from a POST method in ASP.NET

You can get a form value posted to a page using code similiar to this (C#) -

string formValue;
if (!string.IsNullOrEmpty(Request.Form["txtFormValue"]))
{
  formValue= Request.Form["txtFormValue"];
}

or this (VB)

Dim formValue As String
If Not String.IsNullOrEmpty(Request.Form("txtFormValue")) Then
    formValue = Request.Form("txtFormValue")
End If

Once you have the values you need you can then construct a SQL statement and and write the data to a database.

How do I invoke a Java method when given the method name as a string?

For those who are calling the method within the same class from a non-static method, see below codes:

class Person {
    public void method1() {
        try {
            Method m2 = this.getClass().getDeclaredMethod("method2");
            m1.invoke(this);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void method2() {
        // Do something
    }

}

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

<button> vs. <input type="button" />. Which to use?

This article seems to offer a pretty good overview of the difference.

From the page:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.

The Button Element - W3C

linux find regex

Well, you may try this '.*[0-9]'

MySQL dump by query

MySQL Workbench also has this feature neatly in the GUI. Simply run a query, click the save icon next to Export/Import:

enter image description here

Then choose "SQL INSERT statements (*.sql)" in the list.

enter image description here

Enter a name, click save, confirm the table name and you will have your dump file.

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

Gradle store on local file system

You can use the gradle argument --project-cache-dir "/Users/whatever/.gradle/" to force the gradle cache directory.

In this way you can be darn sure you know what directory is being used (as well as create different caches for different projects)

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

Configuring Hibernate logging using Log4j XML config file?

The answers were useful. After the change, I got duplicate logging of SQL statements, one in the log4j log file and one on the standard console. I changed the persistence.xml file to say show_sql to false to get rid of logging from the standard console. Keeping format_sql true also affects the log4j log file, so I kept that true.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:d:\temp\database\cap1000;shutdown=true"></property>
            <property name="dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        </properties>
    </persistence-unit>
</persistence>

MVC which submit button has been pressed

In Core 2.2 Razor pages this syntax works:

    <button type="submit" name="Submit">Save</button>
    <button type="submit" name="Cancel">Cancel</button>
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
        return Page();
    var sub = Request.Form["Submit"];
    var can = Request.Form["Cancel"];
    if (sub.Count > 0)
       {
       .......

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

Even in base Python you can do the computation in generic form

result = sum(x**2 for x in some_vector) ** 0.5

x ** 2 is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).

Using instead x ** 0.5 to take the square root doesn't do the exact same computations as math.sqrt as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.

I often use x ** 0.5 simply because I don't want to add math just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.

Call a function with argument list in python

A small addition to previous answers, since I couldn't find a solution for a problem, which is not worth opening a new question, but led me here.

Here is a small code snippet, which combines lists, zip() and *args, to provide a wrapper that can deal with an unknown amount of functions with an unknown amount of arguments.

def f1(var1, var2, var3):
    print(var1+var2+var3)

def f2(var1, var2):
    print(var1*var2)

def f3():
    print('f3, empty')

def wrapper(a,b, func_list, arg_list):
    print(a)
    for f,var in zip(func_list,arg_list):
        f(*var)
    print(b)

f_list = [f1, f2, f3]
a_list = [[1,2,3], [4,5], []]

wrapper('begin', 'end', f_list, a_list)

Keep in mind, that zip() does not provide a safety check for lists of unequal length, see zip iterators asserting for equal length in python.

How can I rebuild indexes and update stats in MySQL innoDB?

You can also use the provided CLI tool mysqlcheck to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.

Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

How do you change text to bold in Android?

It's very easy

setTypeface(Typeface.DEFAULT_BOLD);

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

sqlcmd works, System.Data.SqlClient not working - Server not found in Kerberos database. You should add RestrictedKrbHost SPN

https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-kile/445e4499-7e49-4f2a-8d82-aaf2d1ee3c47

5.1.2 SPNs with Serviceclass Equal to "RestrictedKrbHost"

Supporting the "RestrictedKrbHost" service class allows client applications to use Kerberos authentication when they do not have the identity of the service but have the server name. This does not provide client-to-service mutual authentication, but rather client-to-server computer authentication. Services of different privilege levels have the same session key and could decrypt each other's data if the underlying service does not ensure that data cannot be accessed by higher services.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Solution with JavaScript debugging enabled

From the Chrome browser, go to: Settings>Advanced>System and disable "Continue running background apps when Google Chrome is closed".

IMPORTANT! The option above must be set for the correct Chrome User Profile!
Visual Studio has its own Chrome User Profile, preferences you set when using your "normal" Chrome browser wont have any affect on the Chrome browser launched from VS (with JS debugging enabled).

  1. Run your project from VS with "Enable JavaScript debugging..." enabled. The Chrome browser should open and you'll get the error in VS.
  2. Go back to the same instance of Chrome that VS started and disable "Continue running background apps when Google Chrome is closed" as explained above.
    If you don't have "Enable JavaScript debugging..." enabled/checked, the Chrome instance would use your Default User Profile and the error would persist.
  3. Stop and rerun your project, Chrome should load the project as expected without any errors and with JS debugging enabled.

Whenever you stop debugging, you must close the Chrome instance initiated by VS or the error will return the next time you run the project. If there are other Chrome instances, you can leave these open.

To make sure Chrome is using the correct User Profile, go to chrome://version/ by typing it in the url bar, then look at the value for Profile Path. On Windows, the correct value should look something like this:
"C:\Users\[UserName]\AppData\Local\Microsoft\VisualStudio\15.*\WebTools\ChromeUserData_*\Default"

If Chrome is using the browser default or if you're logged in to Chrome with an account, it will look something like this:
"C:\Users\[UserName]\AppData\Local\Google\Chrome\User Data\[ProfileName] OR Default"

Bonus note. If you use Chrome Extensions when debugging, these has to be installed when the VS Profile is active.

How do I match any character across multiple lines in a regular expression?

For Eclipse worked following expression:

Foo

jadajada Bar"

Regular-Expression:

Foo[\S\s]{1,10}.*Bar*

Replace HTML Table with Divs

This ought to do the trick.

<style>
div.block{
  overflow:hidden;
}
div.block label{
  width:160px;
  display:block;
  float:left;
  text-align:left;
}
div.block .input{
  margin-left:4px;
  float:left;
}
</style>

<div class="block">
  <label>First field</label>
  <input class="input" type="text" id="txtFirstName"/>
</div>
<div class="block">
  <label>Second field</label>
  <input class="input" type="text" id="txtLastName"/>
</div>

I hope you get the concept.

TypeError: $.ajax(...) is not a function?

I encountered the same question, and my solution was: add the JQuery script.

Especially, we should make sure the corresponding JQuery is loaded when we debug our js under the firefox/chrome.

How to set date format in HTML date input tag?

We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.

let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0]  //In dd-mm-yyyy format

How do I know if jQuery has an Ajax request pending?

$.active returns the number of active Ajax requests.

More info here

Centering a background image, using CSS

The only thing that worked for me is..

margin: 0 auto

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

"Fade" borders in CSS

Add this class css to your style sheet

.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}

set width to the width of your image. and use this html for image

<div class="border_gradient">
        <img src="image.png" />
</div>

though it may not give the same exact border, it will some gradient looks on the border.

source: CSS3 Borders

How to force Eclipse to ask for default workspace?

I can confirm that I am having the same issue. I am also using eclipse classic with CDT. The funny thing is that it only started happening earlier this evening. Before then, I was always prompted for the workspace. Checking "Prompt for workspace on startup" has no effect. I am not launching eclipse using a startup script, so the -data flag is not set on launch. I have removed the line "osgi.instance.area.default" from the configuration/config.ini, but that had no effect.

A few strange quirks that are incidental to this problem: If I delete the "workspace" workspace it creates it again upon launch. However, when I switch to one of my "real" workspaces I notice that the "workspace" workspace is not listed as an option to be switched to.

As would be expected, reinstalling eclipse resolves the issue. But it would be nicer to find a way to fix the problem without resorting to that.

Do you know the Maven profile for mvnrepository.com?

            <?xml version="1.0" encoding="UTF-8"?>

            <!--
            Licensed to the Apache Software Foundation (ASF) under one
            or more contributor license agreements.  See the NOTICE file
            distributed with this work for additional information
            regarding copyright ownership.  The ASF licenses this file
            to you under the Apache License, Version 2.0 (the
            "License"); you may not use this file except in compliance
            with the License.  You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
            Unless required by applicable law or agreed to in writing,
            software distributed under the License is distributed on an
            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
            KIND, either express or implied.  See the License for the
            specific language governing permissions and limitations
            under the License.
            -->

            <!--
             | This is the configuration file for Maven. It can be specified at two levels:
             |
             |  1. User Level. This settings.xml file provides configuration for a single user,
             |                 and is normally provided in ${user.home}/.m2/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -s /path/to/user/settings.xml
             |
             |  2. Global Level. This settings.xml file provides configuration for all Maven
             |                 users on a machine (assuming they're all using the same Maven
             |                 installation). It's normally provided in
             |                 ${maven.conf}/settings.xml.
             |
             |                 NOTE: This location can be overridden with the CLI option:
             |
             |                 -gs /path/to/global/settings.xml
             |
             | The sections in this sample file are intended to give you a running start at
             | getting the most out of your Maven installation. Where appropriate, the default
             | values (values used when the setting is not specified) are provided.
             |
             |-->
            <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
              <!-- localRepository
               | The path to the local repository maven will use to store artifacts.
               |
               | Default: ${user.home}/.m2/repository
              <localRepository>/path/to/local/repo</localRepository>
              -->

              <!-- interactiveMode
               | This will determine whether maven prompts you when it needs input. If set to false,
               | maven will use a sensible default value, perhaps based on some other setting, for
               | the parameter in question.
               |
               | Default: true
              <interactiveMode>true</interactiveMode>
              -->

              <!-- offline
               | Determines whether maven should attempt to connect to the network when executing a build.
               | This will have an effect on artifact downloads, artifact deployment, and others.
               |
               | Default: false
              <offline>false</offline>
              -->

              <!-- pluginGroups
               | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
               | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
               | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
               |-->
              <pluginGroups>
                <!-- pluginGroup
                 | Specifies a further group identifier to use for plugin lookup.
                <pluginGroup>com.your.plugins</pluginGroup>
                -->
              </pluginGroups>

              <!-- proxies
               | This is a list of proxies which can be used on this machine to connect to the network.
               | Unless otherwise specified (by system property or command-line switch), the first proxy
               | specification in this list marked as active will be used.
               |-->
              <proxies>
                <!-- proxy
                 | Specification for one proxy, to be used in connecting to the network.
                 |
                <proxy>
                  <id>optional</id>
                  <active>false</active>
                  <protocol>http</protocol>
                  <username>proxyuser</username>
                  <password>proxypass</password>
                  <host>proxy.host.net</host>
                  <port>80</port>
                  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
                </proxy>
                -->
              </proxies>

              <!-- servers
               | This is a list of authentication profiles, keyed by the server-id used within the system.
               | Authentication profiles can be used whenever maven must make a connection to a remote server.
               |-->
              <servers>
                <!-- server
                 | Specifies the authentication information to use when connecting to a particular server, identified by
                 | a unique name within the system (referred to by the 'id' attribute below).
                 |
                 | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
                 |       used together.
                 |
                <server>
                  <id>deploymentRepo</id>
                  <username>repouser</username>
                  <password>repopwd</password>
                </server>
                -->

                <!-- Another sample, using keys to authenticate.
                <server>
                  <id>siteServer</id>
                  <privateKey>/path/to/private/key</privateKey>
                  <passphrase>optional; leave empty if not used.</passphrase>
                </server>
                -->
              </servers>

              <!-- mirrors
               | This is a list of mirrors to be used in downloading artifacts from remote repositories.
               |
               | It works like this: a POM may declare a repository to use in resolving certain artifacts.
               | However, this repository may have problems with heavy traffic at times, so people have mirrored
               | it to several places.
               |
               | That repository definition will have a unique id, so we can create a mirror reference for that
               | repository, to be used as an alternate download site. The mirror site will be the preferred
               | server for that repository.
               |-->
              <mirrors>
                <!-- mirror
                 | Specifies a repository mirror site to use instead of a given repository. The repository that
                 | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
                 | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
                 |
                <mirror>
                  <id>mirrorId</id>
                  <mirrorOf>repositoryId</mirrorOf>
                  <name>Human Readable Name for this Mirror.</name>
                  <url>http://my.repository.com/repo/path</url>
                </mirror>
                 -->
              </mirrors>

              <!-- profiles
               | This is a list of profiles which can be activated in a variety of ways, and which can modify
               | the build process. Profiles provided in the settings.xml are intended to provide local machine-
               | specific paths and repository locations which allow the build to work in the local environment.
               |
               | For example, if you have an integration testing plugin - like cactus - that needs to know where
               | your Tomcat instance is installed, you can provide a variable here such that the variable is
               | dereferenced during the build process to configure the cactus plugin.
               |
               | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
               | section of this document (settings.xml) - will be discussed later. Another way essentially
               | relies on the detection of a system property, either matching a particular value for the property,
               | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
               | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
               | Finally, the list of active profiles can be specified directly from the command line.
               |
               | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
               |       repositories, plugin repositories, and free-form properties to be used as configuration
               |       variables for plugins in the POM.
               |
               |-->
              <profiles>

              <profile>
                <id>maven-https</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
                <repositories>
                    <repository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </repository>
                </repositories>
                <pluginRepositories>
                    <pluginRepository>
                        <id>central</id>
                        <url>https://repo1.maven.org/maven2</url>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                    </pluginRepository>
                </pluginRepositories> 
            </profile>

                <!-- profile
                 | Specifies a set of introductions to the build process, to be activated using one or more of the
                 | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
                 | or the command line, profiles have to have an ID that is unique.
                 |
                 | An encouraged best practice for profile identification is to use a consistent naming convention
                 | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
                 | This will make it more intuitive to understand what the set of introduced profiles is attempting
                 | to accomplish, particularly when you only have a list of profile id's for debug.
                 |
                 | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
                <profile>
                  <id>jdk-1.4</id>
                  <activation>
                    <jdk>1.4</jdk>
                  </activation>
                  <repositories>
                    <repository>
                      <id>jdk14</id>
                      <name>Repository for JDK 1.4 builds</name>
                      <url>http://www.myhost.com/maven/jdk14</url>
                      <layout>default</layout>
                      <snapshotPolicy>always</snapshotPolicy>
                    </repository>

                  </repositories>
                </profile>
                -->

                <!--
                 | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
                 | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
                 | might hypothetically look like:
                 |
                 | ...
                 | <plugin>
                 |   <groupId>org.myco.myplugins</groupId>
                 |   <artifactId>myplugin</artifactId>
                 |
                 |   <configuration>
                 |     <tomcatLocation>${tomcatPath}</tomcatLocation>
                 |   </configuration>
                 | </plugin>
                 | ...
                 |
                 | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
                 |       anything, you could just leave off the <value/> inside the activation-property.
                 |
                <profile>
                  <id>env-dev</id>
                  <activation>
                    <property>
                      <name>target-env</name>
                      <value>dev</value>
                    </property>
                  </activation>
                  <properties>
                    <tomcatPath>/path/to/tomcat/instance</tomcatPath>
                  </properties>
                </profile>
                -->
              </profiles>

              <!-- activeProfiles
               | List of profiles that are active for all builds.
               |
              <activeProfiles>
                <activeProfile>alwaysActiveProfile</activeProfile>
                <activeProfile>anotherAlwaysActiveProfile</activeProfile>
              </activeProfiles>
              -->
            </settings>

Confused by python file mode "w+"

Both seems to be working same but there is a catch.

r+ :-

  • Open the file for Reading and Writing
  • Once Opened in the beginning file pointer will point to 0
  • Now if you will want to Read then it will start reading from beginning
  • if you want to Write then start writing, But the write process will begin from pointer 0. So there would be overwrite of characters, if there is any
  • In this case File should be present, either will FileNotFoundError will be raised.

w+ :-

  • Open the file for Reading and Writing
  • If file exist, File will be opened and all data will be erased,
  • If file does not exist, then new file will be created
  • In the beginning file pointer will point to 0 (as there is not data)
  • Now if you want to write something, then write
  • File pointer will be Now pointing to end of file (after write process)
  • If you want to read the data now, seek to specific point. (for beginning seek(0))

So, Overall saying both are meant to open the file to read and write but difference is whether we want to erase the data in the beginning and then do read/write or just start as it is.

abc.txt - in beginning

1234567
abcdefg
0987654
1234

Code for r+

with open('abc.txt', 'r+') as f:      # abc.txt should exist before opening
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0
567
abcdefg
0987654
1234

abc.txt - After Run:

abcd567
abcdefg
0987654
1234Sunny

Resetting abc.txt as initial

Code for w+

with open('abc.txt', 'w+') as f:     
    print(f.tell())                   # Should give ==> 0
    f.write('abcd')                   
    print(f.read())                   # Pointer is pointing to index 3 => 4th position
    f.write('Sunny')                  # After read pointer is at End of file

Output

0


abc.txt - After Run:

abcdSunny

Run git pull over all subdirectories

Most compact method, assuming all sub-dirs are git repos:

ls | parallel git -C {} pull

Navigation bar show/hide

If you want to detect the status of navigation bar wether it is hidden/shown. You can simply use following code to detect -

if self.navigationController?.isNavigationBarHidden{
    print("Show navigation bar")
} else {
    print("hide navigation bar")
}

Difference between subprocess.Popen and os.system

os.system is equivalent to Unix system command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed

Whereas:

The popen() function opens a process by creating a pipe, forking, and invoking the shell.

If you are thinking which one to use, then use subprocess definitely because you have all the facilities for execution, plus additional control over the process.

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

How do I set a variable to the output of a command in Bash?

Just to be different:

MOREF=$(sudo run command against $VAR1 | grep name | cut -c7-)

Changing specific text's color using NSMutableAttributedString in Swift

Swift 4.1

NSAttributedStringKey.foregroundColor

for example if you want to change font in NavBar:

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]

In HTML5, should the main navigation be inside or outside the <header> element?

To expand on what @JoshuaMaddox said, in the MDN Learning Area, under the "Introduction to HTML" section, the Document and website structure sub-section says (bold/emphasis is by me):

Header

Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.

Navigation bar

Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.

How to check if element in groovy array/hash/collection/list?

.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()

[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')

Default SecurityProtocol in .NET 4.5

The registry change mechanism worked for me after a struggle. Actually my application was running as 32bit. So I had to change the value under path.

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319

The value type needs to be DWORD and value above 0 .Better use 1.Registry settings to get .Net 4.0 app use TLS 1.2 provided .Net 4.5 is installed in the machine.

linux: kill background task

This should kill all background processes:

jobs -p | xargs kill -9

How to convert JSON to CSV format and store in a variable

Here is the latest answer using a well optimized and nice csv plugin: (The code may not work on stackoverflow here but will work in your project as i have tested it myself)

Using jquery and jquery.csv library (Very well optimized and perfectly escapes everything) https://github.com/typeiii/jquery-csv

_x000D_
_x000D_
// Create an array of objects
const data = [
    { name: "Item 1", color: "Green", size: "X-Large" },
    { name: "Item 2", color: "Green", size: "X-Large" },
    { name: "Item 3", color: "Green", size: "X-Large" }
];

// Convert to csv
const csv = $.csv.fromObjects(data);

// Download file as csv function
const downloadBlobAsFile = function(csv, filename){
    var downloadLink = document.createElement("a");
    var blob = new Blob([csv], { type: 'text/csv' });
    var url = URL.createObjectURL(blob);
    downloadLink.href = url;
    downloadLink.download = filename;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

// Download csv file
downloadBlobAsFile(csv, 'filename.csv');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.tutorialjinni.com/jquery-csv/1.0.11/jquery.csv.min.js"></script>
_x000D_
_x000D_
_x000D_

Checking for an empty file in C++

C++17 solution:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

Assumes you have the filepath location stored, I don't think you can extract a filepath from an std::ifstream object.

How do implement a breadth first traversal?

public void breadthFirstSearch(Node root, Consumer<String> c) {
    List<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
        Node n = queue.remove(0);
        c.accept(n.value);

        if (n.left != null)
            queue.add(n.left);
        if (n.right != null)
            queue.add(n.right);
    }
}

And the Node:

public static class Node {
    String value;
    Node left;
    Node right;

    public Node(final String value, final Node left, final Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

Should Jquery code go in header or footer?

Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .

I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.

and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.

How to set text size of textview dynamically for different screens

I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
  // exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How to check the extension of a filename in a bash script?

Make

if [ "$file" == "*.txt" ]

like this:

if [[ $file == *.txt ]]

That is, double brackets and no quotes.

The right side of == is a shell pattern. If you need a regular expression, use =~ then.

Styling Google Maps InfoWindow

You can modify the whole InfoWindow using jquery alone...

var popup = new google.maps.InfoWindow({
    content:'<p id="hook">Hello World!</p>'
});

Here the <p> element will act as a hook into the actual InfoWindow. Once the domready fires, the element will become active and accessible using javascript/jquery, like $('#hook').parent().parent().parent().parent().

The below code just sets a 2 pixel border around the InfoWindow.

google.maps.event.addListener(popup, 'domready', function() {
    var l = $('#hook').parent().parent().parent().siblings();
    for (var i = 0; i < l.length; i++) {
        if($(l[i]).css('z-index') == 'auto') {
            $(l[i]).css('border-radius', '16px 16px 16px 16px');
            $(l[i]).css('border', '2px solid red');
        }
    }
});

You can do anything like setting a new CSS class or just adding a new element.

Play around with the elements to get what you need...

Add IIS 7 AppPool Identities as SQL Server Logons

I figured it out through trial and error... the real chink in the armor was a little known setting in IIS in the Configuration Editor for the website in

Section: system.webServer/security/authentication/windowsAuthentication

From: ApplicationHost.config <locationpath='ServerName/SiteName' />

called useAppPoolCredentials (which is set to False by default. Set this to True and life becomes great again!!! Hope this saves pain for the next guy....

enter image description here

How to add images to README.md on GitHub?

In my case i use imgur and use the direct link this way.

![img](http://i.imgur.com/yourfilename.png)

How to parseInt in Angular.js

Inside template this working finely.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>

</body>
</html>

Declare multiple module.exports in Node.js

module.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

main.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);