Programs & Examples On #Selectionchanged

ComboBox- SelectionChanged event has old value, not new value

If you really need the SelectionChanged event, then the best answer is SwDevMan81's answer. However, if you are starting with WPF, then you might want to learn how to do things the WPF way, which is different than the old Windows Forms days that used to rely on events like SelectionChanged, with WPF and Model View ViewModel pattern, you should use bindings. Here is a code example:

// In the Views folder: /Views/MyWindow.xaml:
// ...
<ComboBox ItemsSource="{Binding MyViewModel.MyProperties, RelativeSource={RelativeSource AncestorType=Window}}"
         SelectedItem="{Binding MyViewModel.MyProperty  , RelativeSource={RelativeSource AncestorType=Window}}" />
// ...



// In the Views folder: /Views/MyWindow.xaml.cs:
public partial class MyWindow : Window
{
    public  MyViewModelClass MyViewModel {
        get { return _viewModel; }
        private set { _viewModel = value;}
    }

    public MyWindow()
    {
        MyViewModel.PropertyChanged += MyViewModel_PropertyChanged;

    }

    void MyViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "MyProperty")
        {
            // Do Work
            // Put your logic here!
        }
    }
}

using System.ComponentModel;

// In your ViewModel folder: /ViewModels/MyViewModelClass.cs:
public class MyViewModelClass : INotifyPropertyChanged
{
    // INotifyPropertyChanged implementation:
    private void NotifyPropertyChanged(string propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
    public event PropertyChangedEventHandler PropertyChanged;

    // Selected option:
    private string _myProperty;
    public  string  MyProperty {
        get { return _myProperty; }
        set { _myProperty = value; NotifyPropertyChanged("MyProperty"); }
    }

    // Available options:
    private List<string> _myProperties;
    public  List<string>  MyProperties {
        get { return _myProperties; }
        set { _myProperties = value; NotifyPropertyChanged("MyProperties"); }
    }

}

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

How to pass html string to webview on android

I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.

String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Find details on WebView

How to create an Array with AngularJS's ng-model

You can do a variety of things. What I would do is this.

Create an array on scope that will be your data structure for the phone numbers.

$scope.telephone = '';
$scope.numbers = [];

Then in your html I would have this

<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>

Then when your user clicks submit, run submitNumber(), which pushes the new telephone number into the numbers array.

$scope.submitNumber = function(){
  $scope.numbers.push($scope.telephone);
}

Run script with rc.local: script works, but not at boot

You might also have made it work by specifying the full path to node. Furthermore, when you want to run a shell command as a daemon you should close stdin by adding 1<&- before the &.

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

How do you determine what technology a website is built on?

Some people might even deliberately obscure the technology they use. After all, it wouldn't take me long to tweak apache so that ".asp" actually ran perl scripts and put "powered by Microsoft IIS" into my footer despite the fact I used MySQL.

That way you'd spend all your time trying to hack my site using vulnerabilities it doesn't actually have.

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode() does NOT work for URIs.

Let us take your original URL:

http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

and convert it to a URI template with two variables (on multiple lines for clarity):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

Now let us build a variable map with these three variables using the library mentioned in the link:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

This is GUARANTEED to return a fully functional URL!

Install sbt on ubuntu

No command sbt found

It's saying that sbt is not on your path. Try to run ./sbt from ~/bin/sbt/bin or wherever the sbt executable is to verify that it runs correctly. Also check that you have execute permissions on the sbt executable. If this works , then add ~/bin/sbt/bin to your path and sbt should run from anywhere.

See this question about adding a directory to your path.

To verify the path is set correctly use the which command on LINUX. The output will look something like this:

$ which sbt
/usr/bin/sbt

Lastly, to verify sbt is working try running sbt -help or likewise. The output with -help will look something like this:

$ sbt -help
Usage: sbt [options]

  -h | -help         print this message
  ...

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Why .NET String is immutable?

Making strings immutable has many advantages. It provides automatic thread safety, and makes strings behave like an intrinsic type in a simple, effective manner. It also allows for extra efficiencies at runtime (such as allowing effective string interning to reduce resource usage), and has huge security advantages, since it's impossible for an third party API call to change your strings.

StringBuilder was added in order to address the one major disadvantage of immutable strings - runtime construction of immutable types causes a lot of GC pressure and is inherently slow. By making an explicit, mutable class to handle this, this issue is addressed without adding unneeded complication to the string class.

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I had the same problem when using bootstrap-datewidget and i loaded jquery in the header instead of loading it at the end of the body and it worked.

Add/Delete table rows dynamically using JavaScript

Here Is full code with HTML,CSS and JS.

<style><style id='generate-style-inline-css' type='text/css'>
    body {
        background-color: #efefef;
        color: #3a3a3a;
    }

    a,
    a:visited {
        color: #1e73be;
    }

    a:hover,
    a:focus,
    a:active {
        color: #000000;
    }

    body .grid-container {
        max-width: 1200px;
    }

    body,
    button,
    input,
    select,
    textarea {
        font-family: "Open Sans", sans-serif;
    }

    .entry-content>[class*="wp-block-"]:not(:last-child) {
        margin-bottom: 1.5em;
    }

    .main-navigation .main-nav ul ul li a {
        font-size: 14px;
    }

    @media (max-width:768px) {
        .main-title {
            font-size: 30px;
        }
        h1 {
            font-size: 30px;
        }
        h2 {
            font-size: 25px;
        }
    }

    .top-bar {
        background-color: #636363;
        color: #ffffff;
    }

    .top-bar a,
    .top-bar a:visited {
        color: #ffffff;
    }

    .top-bar a:hover {
        color: #303030;
    }

    .site-header {
        background-color: #ffffff;
        color: #3a3a3a;
    }

    .site-header a,
    .site-header a:visited {
        color: #3a3a3a;
    }

    .main-title a,
    .main-title a:hover,
    .main-title a:visited {
        color: #222222;
    }

    .site-description {
        color: #757575;
    }

    .main-navigation,
    .main-navigation ul ul {
        background-color: #222222;
    }

    .main-navigation .main-nav ul li a,
    .menu-toggle {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li:hover>a,
    .main-navigation .main-nav ul li:focus>a,
    .main-navigation .main-nav ul li.sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    button.menu-toggle:hover,
    button.menu-toggle:focus,
    .main-navigation .mobile-bar-items a,
    .main-navigation .mobile-bar-items a:hover,
    .main-navigation .mobile-bar-items a:focus {
        color: #ffffff;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"],
    .navigation-search input[type="search"]:active {
        color: #3f3f3f;
        background-color: #3f3f3f;
    }

    .navigation-search input[type="search"]:focus {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .main-navigation ul ul {
        background-color: #3f3f3f;
    }

    .main-navigation .main-nav ul ul li a {
        color: #ffffff;
    }

    .main-navigation .main-nav ul ul li:hover>a,
    .main-navigation .main-nav ul ul li:focus>a,
    .main-navigation .main-nav ul ul li.sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation . main-nav ul ul li[class*="current-menu-"]>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover,
    .main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a {
        color: #ffffff;
        background-color: #4f4f4f;
    }

    .separate-containers .inside-article,
    .separate-containers .comments-area,
    .separate-containers .page-header,
    .one-container .container,
    .separate-containers .paging-navigation,
    .inside-page-header {
        background-color: #ffffff;
    }

    .entry-meta {
        color: #595959;
    }

    .entry-meta a,
    .entry-meta a:visited {
        color: #595959;
    }

    .entry-meta a:hover {
        color: #1e73be;
    }

    .sidebar .widget {
        background-color: #ffffff;
    }

    .sidebar .widget .widget-title {
        color: #000000;
    }

    .footer-widgets {
        background-color: #ffffff;
    }

    .footer-widgets .widget-title {
        color: #000000;
    }

    .site-info {
        color: #ffffff;
        background-color: #222222;
    }

    .site-info a,
    .site-info a:visited {
        color: #ffffff;
    }

    .site-info a:hover {
        color: #606060;
    }

    .footer-bar .widget_nav_menu .current-menu-item a {
        color: #606060;
    }

    input[type="text"],
    input[type="email"],
    input[type="url"],
    input[type="password"],
    input[type="search"],
    input[type="tel"],
    input[type="number"],
    textarea,
    select {
        color: #666666;
        background-color: #fafafa;
        border-color: #cccccc;
    }

    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="url"]:focus,
    input[type="password"]:focus,
    input[type="search"]:focus,
    input[type="tel"]:focus,
    input[type="number"]:focus,
    textarea:focus,
    select:focus {
        color: #666666;
        background-color: #ffffff;
        border-color: #bfbfbf;
    }

    button,
    html input[type="button"],
    input[type="reset"],
    input[type="submit"],
    a.button,
    a.button:visited,
    a.wp-block-button__link:not(.has-background) {
        color: #ffffff;
        background-color: #666666;
    }

    button:hover,
    html input[type="button"]:hover,
    input[type="reset"]:hover,
    input[type="submit"]:hover,
    a.button:hover,
    button:focus,
    html input[type="button"]:focus,
    input[type="reset"]:focus,
    input[type="submit"]:focus,
    a.button:focus,
    a.wp-block-button__link:not(.has-background):active,
    a.wp-block-button__link:not(.has-background):focus,
    a.wp-block-button__link:not(.has-background):hover {
        color: #ffffff;
        background-color: #3f3f3f;
    }

    .generate-back-to-top,
    .generate-back-to-top:visited {
        background-color: rgba( 0, 0, 0, 0.4);
        color: #ffffff;
    }

    .generate-back-to-top:hover,
    .generate-back-to-top:focus {
        background-color: rgba( 0, 0, 0, 0.6);
        color: #ffffff;
    }

    .entry-content .alignwide,
    body:not(.no-sidebar) .entry-content .alignfull {
        margin-left: -40px;
        width: calc(100% + 80px);
        max-width: calc(100% + 80px);
    }

    @media (max-width:768px) {
        .separate-containers .inside-article,
        .separate-containers .comments-area,
        .separate-containers .page-header,
        .separate-containers .paging-navigation,
        .one-container .site-content,
        .inside-page-header {
            padding: 30px;
        }
        .entry-content .alignwide,
        body:not(.no-sidebar) .entry-content .alignfull {
            margin-left: -30px;
            width: calc(100% + 60px);
            max-width: calc(100% + 60px);
        }
    }

    .rtl .menu-item-has-children .dropdown-menu-toggle {
        padding-left: 20px;
    }

    .rtl .main-navigation .main-nav ul li.menu-item-has-children>a {
        padding-right: 20px;
    }

    .one-container .sidebar .widget {
        padding: 0px;
    }

    .append_row {
        color: black !important;
        background-color: #FFD6D6 !important;
        border: 1px #ccc solid !important;
    }

    .append_column {
        color: black !important;
        background-color: #D6FFD6 !important;
        border: 1px #ccc solid !important;
    }

    table#my-table td {
        width: 50px;
        height: 27px;
        border: 1px solid #D3D3D3;
        text-align: center;
        padding: 0;
    }

    div#my-container input {
        padding: 5px;
        font-size: 12px !important;
        width: 100px;
        margin: 2px;
    }

    .row {
        background-color: #FFD6D6 !important;
    }

    .col {
        background-color: #D6FFD6 !important;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.11.0.js"></script>
    <script>

    // append row to the HTML table
    function appendRow() {
        var tbl = document.getElementById('my-table'), // table reference
            row = tbl.insertRow(tbl.rows.length),      // append table row
            i;
        // insert table cells to the new row
        for (i = 0; i < tbl.rows[0].cells.length; i++) {
            createCell(row.insertCell(i), i, 'row');
        }
    }

    // create DIV element and append to the table cell
    function createCell(cell, text, style) {
        var div = document.createElement('div'), // create DIV element
            txt = document.createTextNode(text); // create text node
        div.appendChild(txt);                    // append text node to the DIV
        div.setAttribute('class', style);        // set DIV class attribute
        div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
        cell.appendChild(div);                   // append DIV to the table cell
    }

    // append column to the HTML table
    function appendColumn() {
        var tbl = document.getElementById('my-table'), // table reference
            i;
        // open loop for each row and append cell
        for (i = 0; i < tbl.rows.length; i++) {
            createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
        }
    }

    // delete table rows with index greater then 0
    function deleteRows() {
        var tbl = document.getElementById('my-table'), // table reference
            lastRow = tbl.rows.length - 1,             // set the last row index
            i;
        // delete rows with index greater then 0
        for (i = lastRow; i > 0; i--) {
            tbl.deleteRow(i);
        }
    }

    // delete table columns with index greater then 0
    function deleteColumns() {
        var tbl = document.getElementById('my-table'), // table reference
            lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
            i, j;
        // delete cells with index greater then 0 (for each row)
        for (i = 0; i < tbl.rows.length; i++) {
            for (j = lastCol; j > 0; j--) {
                tbl.rows[i].deleteCell(j);
            }
        }
    }
    </script>
    <div id="my-container">
    <center><br>
    <input type="button" value="Add row" onclick="javascript:appendRow()" class="append_row"><br>
    <input type="button" value="Add column" onclick="javascript:appendColumn()" class="append_column"><br>
    <input type="button" value="Delete rows" onclick="javascript:deleteRows()" class="delete"><br>
    <input type="button" value="Delete columns" onclick="javascript:deleteColumns()" class="delete"><br>
    <input type="button" value="Delete both" onclick="javascript:deleteColumns();deleteRows()" class="delete"><p></p>
    <table id="my-table" align="center" cellspacing="0" cellpadding="0" border="0">
    <tbody><tr>
    <td>Small</td>
    </tr>
    </tbody></table>
    <p></p></center>
    </div>

How can I scroll up more (increase the scroll buffer) in iTerm2?

There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal or you can just pump up number of lines that you want to have in history in the same place.

How to swap two variables in JavaScript

Till ES5, to swap two numbers, you have to create a temp variable and then swap it. But in ES6, its very easy to swap two numbers using array destructuring. See example.

let x,y;
[x,y]=[2,3];
console.log(x,y);      // return 2,3

[x,y]=[y,x];
console.log(x,y);      // return 3,2

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

How can I obtain the element-wise logical NOT of a pandas Series?

To invert a boolean Series, use ~s:

In [7]: s = pd.Series([True, True, False, True])

In [8]: ~s
Out[8]: 
0    False
1    False
2     True
3    False
dtype: bool

Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:

In [119]: s = pd.Series([True, True, False, True]*10000)

In [10]:  %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop

In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop

In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop

As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray; they are now subclasses of pd.NDFrame. This might have something to do with why np.invert(s) is no longer as fast as ~s or -s.

Caveat: timeit results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.

SeekBar and media player in android

Try this Code:

public class MainActivity extends AppCompatActivity {

MediaPlayer mplayer;

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

            //You create MediaPlayer variable ==> set the path and start the audio.

    mplayer = MediaPlayer.create(this, R.raw.example);
    mplayer.start();

            //Find the seek bar by Id (which you have to create in layout)
            // Set seekBar max with length of audio
           // You need a Timer variable to set progress with position of audio

    final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setMax(mplayer.getDuration());

    new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    seekBar.setProgress(mplayer.getCurrentPosition());
                }
            }, 0, 1000);


            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            // Update the progress depending on seek bar
                    mplayer.seekTo(progress);

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }

get an element's id

Yes you can just use the .id property of the dom element, for example:

myDOMElement.id

Or, something like this:

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
  alert(inputs[i].id);
}

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Centering a div block without the width

Slight variation on Mike M. Lin's answer

If you add overflow: auto; ( or hidden ) to div.product_container, then you don't need div.clear.

This is derived from this article -> http://www.quirksmode.org/css/clearing.html

Here is modified HTML:

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
</div>

And here is modified CSS:

.product_container {
  overflow: auto;
  /* width property only required if you want to support IE6 */
  width: 100%;
}

.outer-center {
  float: right;
  right: 50%;
  position: relative;
}

.inner-center {
  float: right;
  right: -50%;
  position: relative;
}

The reason, why it's better without div.clear (apart that it feels wrong to have an empty element) is Firefox'es overzealous margin assignment.

If, for example, you have this html:

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div style="clear: both;"></div>
</div>
<p style="margin-top: 11px;">Some text</p>

then, in Firefox (8.0 at the point of writing), you will see 11px margin before product_container. What's worse, is that you will get a vertical scroll bar for the whole page, even if the content fits nicely into the screen dimensions.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.

It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.

bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
    DWORD dwHandle;
    DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
    if (dwLen) {
        LPBYTE lpData = new BYTE[dwLen];
        if (lpData) {
            if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
                UINT uLen;  
                VS_FIXEDFILEINFO *lpBuffer;  
                VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);  
                *majorPart = HIWORD(lpBuffer->dwFileVersionMS);
                *minorPart = LOWORD(lpBuffer->dwFileVersionMS);
                *buildPart = HIWORD(lpBuffer->dwFileVersionLS);
                *privatePart = LOWORD(lpBuffer->dwFileVersionLS);
                delete[] lpData;
                return true;
            }
        }
    }
    return false;
}

int _tmain(int argc,_TCHAR* argv[])
{
    _TCHAR filename[MAX_PATH];
    _TCHAR frameworkroot[MAX_PATH];
    if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
        return 1;
    _tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return 2;
    do {
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
            _tcslen(FindFileData.cAlternateFileName) != 0) {
            _tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
            filename[_tcslen(frameworkroot)] = 0;
            _tcscat_s(filename,FindFileData.cFileName);
            _tcscat_s(filename,_T("\\mscorlib.dll"));
            WORD majorPart,minorPart,buildPart,privatePart;
            if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
                _tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
            }
        }
    } while (FindNextFile(hFind,&FindFileData) != 0);
    FindClose(hFind);
    return 0;
}

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I use this:

interface IObjectKeys {
  [key: string]: string | number;
}

interface IDevice extends IObjectKeys {
  id: number;
  room_id: number;
  name: string;
  type: string;
  description: string;
}

If you use the optional property in your object:

interface IDevice extends IObjectKeys {
  id: number;
  room_id?: number;
  name?: string;
  type?: string;
  description?: string;
}

... you should add 'undefined' value into the IObjectKeys interface:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

Display XML content in HTML page

Simple solution is to embed inside of a <textarea> element, which will preserve both the formatting and the angle brackets. I have also removed the border with style="border:none;" which makes the textarea invisible.

Here is a sample: http://jsfiddle.net/y9fqf/1/

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

In Xcode 8 beta 4 does not work...

Use:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    print("Are we there yet?")
}

for async two ways:

DispatchQueue.main.async {
    print("Async1")
}

DispatchQueue.main.async( execute: {
    print("Async2")
})

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Android Studio AVD - Emulator: Process finished with exit code 1

Open AVD manager and click on the drop down along side with your emulator and select the show in disk and delete the file with .lock extension. After deleted, run your emulator. That works for me.

Add URL link in CSS Background Image?

Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:

<div class="wrapWithBackgroundImage">
    <a href="#" class="invisibleLink"></a>
</div>

.wrapWithBackgroundImage {
    background-image: url(...);
}
.invisibleLink {
    display: block;
    left: 55px; top: 55px;
    position: absolute;
    height: 55px width: 55px;
}

How to show SVG file on React Native?

you can do this using a simple way

first, you should take installation,

  1. npm install -s react-native-svg
  2. react-native link react-native-svg
  3. npm install -s react-native-svg-transformer

then, you should add the following code in your metro.config.js file

_x000D_
_x000D_
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  return {
    transformer: {
      babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== "svg"),
      sourceExts: [...sourceExts, "svg"]
    }
  };
})();
_x000D_
_x000D_
_x000D_

after that, you should create a new file in your root directory with the name of declarations.d.js with the following code

_x000D_
_x000D_
declare module "*.svg" {
  import { SvgProps } from "react-native-svg";
  const content: React.FC<SvgProps>;
  export default content;
}
_x000D_
_x000D_
_x000D_

Finally, This is a import mathod

_x000D_
_x000D_
import USER from "../../assets/icons/user.svg"
_x000D_
_x000D_
_x000D_

and, this is for jsx

_x000D_
_x000D_
<USER width="100%" height="100%"/>
_x000D_
_x000D_
_x000D_

Android: How to turn screen on and off programmatically?

     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    screenLock.acquire();

  //later
  screenLock.release();

//User Manifest file

Case insensitive std::string.find()

I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger shouldn't match jäger but <jäger> should.

It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.

/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
    /* Fail fast if the base string was smaller than what we're looking for */
    if (subString.length() > baseString.length()) 
        return false;

    auto it = std::search(
        baseString.begin(), baseString.end(), subString.begin(), subString.end(),
        [](char ch1, char ch2)
        {
            return std::toupper(ch1) == std::toupper(ch2);
        }
    );

    if(it == baseString.end())
        return false;

    size_t match_start_offset = it - baseString.begin();

    std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);

    /* Typical special characters and whitespace to split the substring up. */
    size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");

    /* Pass fast if the remainder of the base string where
       the match started is the same length as the substring. */
    if (match_end_pos == std::wstring::npos && match_start.length() == subString.length()) 
        return true;

    std::wstring extracted_match = match_start.substr(0, match_end_pos);

    return (extracted_match.length() == subString.length());
}

How can I get browser to prompt to save password?

Simple 2020 aproach

This will automatically enable autocomplete and save password in browsers.

  • autocomplete="on" (form)
  • autocomplete="username" (input, email/username)
  • autocomplete="current-password" (input, password)
<form autocomplete="on">
  <input id="user-text-field" type="email" autocomplete="username"/>
  <input id="password-text-field" type="password" autocomplete="current-password"/>
</form>

Check out more at Apple's documentation: Enabling Password AutoFill on an HTML Input Element

Java generics - get class?

I'm not 100% sure if this works in all cases (needs at least Java 1.5):

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main 
{
    public class A
    {   
    }

    public class B extends A
    {       
    }


    public Map<A, B> map = new HashMap<Main.A, Main.B>();

    public static void main(String[] args) 
    {

        try
        {
            Field field = Main.class.getField("map");           
            System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());

            Type genericType = field.getGenericType();

            if(genericType instanceof ParameterizedType)
            {
                ParameterizedType type = (ParameterizedType) genericType;               
                Type[] typeArguments = type.getActualTypeArguments();

                for(Type typeArgument : typeArguments) 
                {   
                    Class<?> classType = ((Class<?>)typeArgument);                  
                    System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }    
}

This will output:

Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B

ComboBox.SelectedText doesn't give me the SelectedText

Here's how I would approach the problem, assuming you want to change the text of say, a label

    private void comboBoxtest_SelectedIndexChanged(object sender, EventArgs e)
    {
        var combotext = comboBoxtest.Text;
        var status = "The status of my combo box is" + combotext;
        label1.Text = status;
    }

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to get the request parameters in Symfony 2?

For symfony 4 users:

$query = $request->query->get('query');

How can I introduce multiple conditions in LIKE operator?

I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.

This worked for me in Oracle 11g:

REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*'); 

How to sort a HashSet?

A HashSet does not guarantee any order of its elements. If you need this guarantee, consider using a TreeSet to hold your elements.

However if you just need your elements sorted for this one occurrence, then just temporarily create a List and sort that:

Set<?> yourHashSet = new HashSet<>();

...

List<?> sortedList = new ArrayList<>(yourHashSet);
Collections.sort(sortedList);

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

Method has the same erasure as another method in type

The problem is that Set<Integer> and Set<String> are actually treated as a Set from the JVM. Selecting a type for the Set (String or Integer in your case) is only syntactic sugar used by the compiler. The JVM can't distinguish between Set<String> and Set<Integer>.

How can I do an UPDATE statement with JOIN in SQL Server?

Simplified update query using JOIN-ing multiple tables.

   UPDATE
        first_table ft
        JOIN second_table st ON st.some_id = ft.some_id
        JOIN third_table tt  ON tt.some_id = st.some_id
        .....
    SET
        ft.some_column = some_value
    WHERE ft.some_column = 123456 AND st.some_column = 123456

Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.

count number of lines in terminal output

"abcd4yyyy" | grep 4 -c gives the count as 1

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

How to get box-shadow on left & right sides only

Classical approach: Negative spread

CSS box-shadow uses 4 parameters: h-shadow, v-shadow, blur, spread:

box-shadow: 10px 0 8px -8px black;

The v-shadow (verical shadow) is set to 0.

The blur parameter adds the gradient effect, but adds also a little shadow on vertical borders (the one we want to get rid of).

Negative spread reduces the shadow on all borders: you can play with it trying to remove that little vertical shadow without affecting too much the one obn the sides (it's easier for small shadows, 5 to 10px.)

Here a fiddle example.


Second approach: Absolute div on the side

Add an empty div in your element, and style it with absolute positioning so it doesen't affect the element content.

Here the fiddle with an example of left-shadow.

<div id="container">
  <div class="shadow"></div>
</div>

.shadow{
    position:absolute;
    height: 100%;
    width: 4px;
    left:0px;
    top:0px;
    box-shadow: -4px 0 3px black;
}

Third: Masking shadow

If you have a fixed background, you can hide the side-shadow effect with two masking shadows having the same color of the background and blur = 0, example:

box-shadow: 
    0 -6px white,          // Top Masking Shadow
    0 6px white,           // Bottom Masking Shadow
    7px 0 4px -3px black,  // Left-shadow
    -7px 0 4px -3px black; // Right-shadow

I've added again a negative spread (-3px) to the black shadow, so it doesn't stretch beyond the corners.

Here the fiddle.

Draw a line in a div

_x000D_
_x000D_
$('.line').click(function() {_x000D_
  $(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
  border: 0;_x000D_
  background-color: #000;_x000D_
  height: 3px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
  background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
_x000D_
_x000D_

POST request via RestTemplate in JSON

I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.

After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.

The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.

how to display excel sheet in html page

Like you, I cannot get MS Office Web Components to work. I would not consider Google Docs since Google seems to think they own anything that passes through their hands. I have tried MS Publish Objects but the quality of the generated html/css is truely awful.

The secret of converting an Excel worksheet to html that will display correctly on a smartphone is to create clean, lean html/css.

The structure of the HTML is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    HEAD
  </head>
  <body>
    BODY
  </body>
</html>

There are useful html elements that can replace "HEAD" but it is not clear to me how you would generate them from an Excel worksheet. They would need to be added separately.

The obvious output for a worksheet or a range is an html table so the following assumes BODY will be replaced by an html table.

The structure of an html table is:

<table TABLE-ATTRIBUTES>
  <tr TABLE-ROW-ATTRIBUTES>
    <td TABLE-CELL-ATTRIBUTES>CELL-VALUE</td>
    More <td>...</td> elements as necessary
  </tr>
  More <tr>...</tr> as necessary
</table>  

Include as few TABLE-ATTRIBUTES, TABLE-ROW-ATTRIBUTES and TABLE-CELL-ATTRIBUTES as possible. Do not set column widths in pixels. Use css attributes rather than html attributes.

A table attribute worth considering is style = "border-collapse: collapse;". The default is separate with a gap around each cell. With collapse the cells touch as they do with Excel.

Three table attribute worth considering are style="background-color:aliceblue;", style="color:#0000FF;" and style="text-align:right;". With the first, you can specify the background colour to be any of the fifty or so named html colours. With the second, you can specify the font colour to be any of 256*256*256 colours. With the third you can right-align numeric values.

The above covers only a fraction of the formatting information that could be converted from Excel to html/css. I am developing an add-in that will convert as much Excel formatting as possible but I hope the above helps anyone with simple requirements.

Which maven dependencies to include for spring 3.0?

You can try this

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>`

How to check for an undefined or null variable in JavaScript?

Open the Developer tools in your browser and just try the code shown in the below image.

Img1 Img2

Printing without newline (print 'a',) prints a space, how to remove?

Just as a side note:

Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.

The way I would do it is as follows:

from sys import stdout
printf = stdout.write

Now you have a "print function" that prints out any string you give it without returning the new line character each time.

printf("Hello,")
printf("World!")

The output will be: Hello, World!

However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.

printf(str(2) + " " + str(4))

The output will be: 2 4

Getting JSONObject from JSONArray

start from

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member

Iterating

for(int i = 0; i < deletedtrs_array.length(); i++){
    JSONObject obj = deletedtrs_array.getJSONObject(i);
    Log.d("Item no."+i, obj.toString());

    // create object of type DeletedTrsWrapper like this
    DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);

    // String company_id = obj.getString("companyid");
    // String username = obj.getString("username");
    // String date = obj.getString("date");
    // int report_id = obj.getInt("reportid");
}

Own object type

class DeletedTrsWrapper {

    public String company_id;
    public String username;
    public String date;
    public int report_id;

    public DeletedTrsWrapper(JSONObject obj){
        company_id = obj.getString("companyid");
        username = obj.getString("username");
        date = obj.getString("date");
        report_id = obj.getInt("reportid");
    }
}

GUI Tool for PostgreSQL

There is a comprehensive list of tools on the PostgreSQL Wiki:

https://wiki.postgresql.org/wiki/PostgreSQL_Clients

And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.

How to get the sizes of the tables of a MySQL database?

Try the following shell command (replace DB_NAME with your database name):

mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head

For Drupal/drush solution, check the following example script which will display the biggest tables in use:

#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20

Split string in C every white space

Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.

int print_words(const char *string, FILE *f)
{
   static const char space_characters[] = " \t";
   const char *next_space;

   // Find the next space in the string
   //
   while ((next_space = strpbrk(string, space_characters)))
   {
      const char *p;

      // If there are non-space characters between what we found
      // and what we started from, print them.
      //
      if (next_space != string)
      {
         for (p=string; p<next_space; p++)
         {
            if(fputc(*p, f) == EOF)
            {
               return -1;
            }
         }

         // Print a newline
         //
         if (fputc('\n', f) == EOF)
         {
            return -1;
         }
      }

      // Advance next_space until we hit a non-space character
      //
      while (*next_space && strchr(space_characters, *next_space))
      {
         next_space++;
      }

      // Advance the string
      //
      string = next_space;
   }

   // Handle the case where there are no spaces left in the string
   //
   if (*string)
   {
      if (fprintf(f, "%s\n", string) < 0)
      {
         return -1;
      }
   }

   return 0;
}

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

In Java, how do I check if a string contains a substring (ignoring case)?

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);

REST API Best practice: How to accept list of parameter values as input

I will side with nategood's answer as it is complete and it seemed to have please your needs. Though, I would like to add a comment on identifying multiple (1 or more) resource that way:

http://our.api.com/Product/101404,7267261

In doing so, you:

Complexify the clients by forcing them to interpret your response as an array, which to me is counter intuitive if I make the following request: http://our.api.com/Product/101404

Create redundant APIs with one API for getting all products and the one above for getting 1 or many. Since you shouldn't show more than 1 page of details to a user for the sake of UX, I believe having more than 1 ID would be useless and purely used for filtering the products.

It might not be that problematic, but you will either have to handle this yourself server side by returning a single entity (by verifying if your response contains one or more) or let clients manage it.

Example

I want to order a book from Amazing. I know exactly which book it is and I see it in the listing when navigating for Horror books:

  1. 10 000 amazing lines, 0 amazing test
  2. The return of the amazing monster
  3. Let's duplicate amazing code
  4. The amazing beginning of the end

After selecting the second book, I am redirected to a page detailing the book part of a list:

--------------------------------------------
Book #1
--------------------------------------------
    Title: The return of the amazing monster
    Summary:
    Pages:
    Publisher:
--------------------------------------------

Or in a page giving me the full details of that book only?

---------------------------------
The return of the amazing monster
---------------------------------
Summary:
Pages:
Publisher:
---------------------------------

My Opinion

I would suggest using the ID in the path variable when unicity is guarantied when getting this resource's details. For example, the APIs below suggest multiple ways to get the details for a specific resource (assuming a product has a unique ID and a spec for that product has a unique name and you can navigate top down):

/products/{id}
/products/{id}/specs/{name}

The moment you need more than 1 resource, I would suggest filtering from a larger collection. For the same example:

/products?ids=

Of course, this is my opinion as it is not imposed.

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

How to remove leading and trailing spaces from a string

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

Create an empty data.frame

The most efficient way to do this is to use structure to create a list that has the class "data.frame":

structure(list(Date = as.Date(character()), File = character(), User = character()), 
          class = "data.frame")
# [1] Date File User
# <0 rows> (or 0-length row.names)

To put this into perspective compared to the presently accepted answer, here's a simple benchmark:

s <- function() structure(list(Date = as.Date(character()), 
                               File = character(), 
                               User = character()), 
                          class = "data.frame")
d <- function() data.frame(Date = as.Date(character()),
                           File = character(), 
                           User = character(), 
                           stringsAsFactors = FALSE) 
library("microbenchmark")
microbenchmark(s(), d())
# Unit: microseconds
#  expr     min       lq     mean   median      uq      max neval
#   s()  58.503  66.5860  90.7682  82.1735 101.803  469.560   100
#   d() 370.644 382.5755 523.3397 420.1025 604.654 1565.711   100

Revert a jQuery draggable object back to its original container on out event of droppable

I've found another easy way to deal with this problem, you just need the attribute " connectToSortable:" to draggable like as below code:

$("#a1,#a2").draggable({
        connectToSortable: "#b,#a",
        revert: 'invalid',
    });

PS: More detail and example
How to move Draggable objects between source area and target area with jQuery

How to Disable landscape mode in Android?

Add this android:screenOrientation="portrait" in your manifest file where you declare your activity like this

<activity android:name=".yourActivity"
    ....
    android:screenOrientation="portrait" />

If you want to do using java code try

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

before you call setContentView method for your activity in onCreate().

Hope this help and easily understandable for all...

Unable to ping vmware guest from another vmware guest

There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.

For me below solution is worked:

  • Disabled the VMware Network Adapter VMNet8
  • Removed the network from the VM
  • Enabled the VMware Network Adapter VMNet8
  • Re-added the Network to VM, and set it to NAT
  • Restarted the machine

Check this blog post for detailed solution.

UICollectionView spacing margins

For adding margins to specified cells, you can use this custom flow layout. https://github.com/voyages-sncf-technologies/VSCollectionViewCellInsetFlowLayout/

extension ViewController : VSCollectionViewDelegateCellInsetFlowLayout 
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
        if indexPath.item == 0 {
            return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
        }
        return UIEdgeInsets.zero
    }
}

How to print a percentage value in python?

There is a way more convenient 'percent'-formatting option for the .format() format method:

>>> '{:.1%}'.format(1/3.0)
'33.3%'

Where do I find old versions of Android NDK?

Here are the links for Windows, Mac and Linux. Latest revision of 18.x, 17.x, 16.x, 15.x, 14.x, 13.x, 12.x, 11.x, 10.x, 9.x, 8.x and 7.x versions.

Update: Download Latest and Old NDK releases from Android official site.


Android NDK, Revision 18b (January 2019)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 17c (June 2018)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 16b (December 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 15c (July 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 14b (March 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 13b (October 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 12b (June 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 11c (March 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 10e (May 2015)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r9d

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r8e

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r7c

Windows 32-bit | Mac OS X 64-bit | Linux 64-bit

Highlight label if checkbox is checked

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

CSS vertical alignment of inline/inline-block elements

vertical-align applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:

div > * {
    vertical-align:middle;  // Align children to middle of line
}

See: http://jsfiddle.net/dfmx123/TFPx8/1186/

NOTE: vertical-align is relative to the current text line, not the full height of the parent div. If you wanted the parent div to be taller and still have the elements vertically centered, set the div's line-height property instead of its height. Follow jsfiddle link above for an example.

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

How do I compile a .cpp file on Linux?

Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"

How do I base64 encode (decode) in C?

Small improvement to the code from ryyst (who got the most votes) is to not use dynamically allocated decoding table but rather static const precomputed table. This eliminates the use of pointer and initialization of the table, and also avoids memory leakage if one forgets to clean up the decoding table with base64_cleanup() (by the way, in base64_cleanup(), after calling free(decoding_table), one should have decoding_table=NULL, otherwise accidentally calling base64_decode after base64_cleanup() will crash or cause undetermined behavior). Another solution could be to use std::unique_ptr...but I'm satisfied with just having const char[256] on the stack and avoid using pointers alltogether - the code looks cleaner and shorter this way.

The decoding table is computed as follows:

const char encoding_table[] = { 
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '+', '/' };

unsigned char decoding_table[256];

for (int i = 0; i < 256; i++)
    decoding_table[i] = '\0';

for (int i = 0; i < 64; i++)
    decoding_table[(unsigned char)encoding_table[i]] = i;

for (int i = 0; i < 256; i++)
    cout << "0x" << (int(decoding_table[i]) < 16 ? "0" : "") << hex << int(decoding_table[i]) << (i != 255 ? "," : "") << ((i+1) % 16 == 0 ? '\n' : '\0');

cin.ignore();

and the modified code I am using is:

        static const char encoding_table[] = { 
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/' };

        static const unsigned char decoding_table[256] = {
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,
            0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
            0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

        char* base64_encode(const unsigned char *data, size_t input_length, size_t &output_length) {

            const int mod_table[] = { 0, 2, 1 };

            output_length = 4 * ((input_length + 2) / 3);

            char *encoded_data = (char*)malloc(output_length);

            if (encoded_data == nullptr)
                return nullptr;

            for (int i = 0, j = 0; i < input_length;) {

                uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
                uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
                uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;

                uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

                encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
                encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
                encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
                encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];

            }

            for (int i = 0; i < mod_table[input_length % 3]; i++)
                encoded_data[output_length - 1 - i] = '=';

            return encoded_data;

        };

        unsigned char* base64_decode(const char *data, size_t input_length, size_t &output_length) {        

            if (input_length % 4 != 0)
                return nullptr;

            output_length = input_length / 4 * 3;

            if (data[input_length - 1] == '=') (output_length)--;
            if (data[input_length - 2] == '=') (output_length)--;

            unsigned char* decoded_data = (unsigned char*)malloc(output_length);

            if (decoded_data == nullptr)
                return nullptr;

            for (int i = 0, j = 0; i < input_length;) {

                uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
                uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
                uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
                uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];

                uint32_t triple = (sextet_a << 3 * 6)
                    + (sextet_b << 2 * 6)
                    + (sextet_c << 1 * 6)
                    + (sextet_d << 0 * 6);

                if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
                if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
                if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;

            }

            return decoded_data;

        };

How to use youtube-dl from a python program?

Here is a way.

We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']. Then, invoke youtube_dl.main(opts). In this way, we write our custom .py module, import youtube_dl and then invoke the main() function.

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

What is the technology behind wechat, whatsapp and other messenger apps?

WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.

Let's trace a series of messages flowing back and forth:

Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.

Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.

Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.

Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.

WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.

Laravel $q->where() between dates

Didn't wan to mess with carbon. So here's my solution

$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');

$new_releases = Game::whereBetween('release', array($start, $end))->get();

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

Manually put files to Android emulator SD card

In Visual Studio 2019 (Xamarin):

  1. Click on the Device Monitor (DDMS) button.

enter image description here

  1. Go to the File Explorer tab and click the button with a phone and a right-pointing arrow on top of it.

enter image description here

Truncate a SQLite table if it exists?

**It is Simple, just follow 2 steps. Step #1. Fire query "Delete from tableName", It will delete all records from table.

Step #2. There is table named "sqlite_sequence" in Sqlite Database, just browse it and you can set sequence table wise to "0" so it will start from auto id "1".** See the screenshot attached.

enter image description here

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You shouldn't use LIs in email. They are unpredictable across email clients. Instead you have to code each bullet point like this:

<table width="100%" cellspacing="0" border="0" cellpadding="0">
    <tr>
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the first bullet point</td>
    </tr>
    <tr>
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the second bullet point</td>
    </tr>
</table>

This will ensure that your bullets work in every email client.

Visual Studio Code - Convert spaces to tabs

Ctrl+Shift+P, then "Convert Indentation to Tabs"

How to query GROUP BY Month in a Year

For Oracle:

select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);

How can I select the row with the highest ID in MySQL?

Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue, so Yes you can do it with the following query:

select * from tabel_name where employee_no='123' and id=(
   select max(id) from table_name where employee_no='123' and leave_type='5'
)

How do I get the path of the Python script I am running in?

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

Android Studio suddenly cannot resolve symbols

I tried everything listed here. Then I checked my androidmanifest.xml I'd had some stoopid mismatched due to folder renames & package renames.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

How do I read any request header in PHP

strtolower is lacking in several of the proposed solutions, RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. The whole thing, not just the value part.

So suggestions like only parsing HTTP_ entries are wrong.

Better would be like this:

if (!function_exists('getallheaders')) {
    foreach ($_SERVER as $name => $value) {
        /* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */
        if (strtolower(substr($name, 0, 5)) == 'http_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    $this->request_headers = $headers;
} else {
    $this->request_headers = getallheaders();
}

Notice the subtle differences with previous suggestions. The function here also works on php-fpm (+nginx).

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

CPU optimization with GPU

There are performance gains you can get by installing TensorFlow from the source even if you have a GPU and use it for training and inference. The reason is that some TF operations only have CPU implementation and cannot run on your GPU.

Also, there are some performance enhancement tips that makes good use of your CPU. TensorFlow's performance guide recommends the following:

Placing input pipeline operations on the CPU can significantly improve performance. Utilizing the CPU for the input pipeline frees the GPU to focus on training.

For best performance, you should write your code to utilize your CPU and GPU to work in tandem, and not dump it all on your GPU if you have one. Having your TensorFlow binaries optimized for your CPU could pay off hours of saved running time and you have to do it once.

Split string in Lua?

I like this short solution

function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

How can I format DateTime to web UTC format?

The best format to use is "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK".

The last K on string will be changed to 'Z' if the date is UTC or with timezone (+-hh:mm) if is local. (http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)

As LukeH said, is good to use the ToUniversalTime if you want that all the dates will be UTC.

The final code is:

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");

How to `wget` a list of URLs in a text file?

try:

wget -i text_file.txt

(check man wget)

Convert Unix timestamp to a date string

With GNU's date you can do:

date -d "@$TIMESTAMP"
# date -d @0
Wed Dec 31 19:00:00 EST 1969

(From: BASH: Convert Unix Timestamp to a Date)

On OS X, use date -r.

date -r "$TIMESTAMP"

Alternatively, use strftime(). It's not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.

echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
# echo 0 | gawk '{print strftime("%c", $0)}'
Wed 31 Dec 1969 07:00:00 PM EST

How to reset Android Studio

Linux Android Studio 0.8.6:

rm -R ~/.AndroidStudioBeta/config/

Linux Android Studio 1.0.0:

rm -R ~/.AndroidStudio/config/

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Old answer "Problem resolved by switching to amazoncorretto" News answer: I used corretto latest , but is similar jdk 1.8. so anyway we need add dependencies manually

NSString with \n or line break

\n\r seems working for me.

I am using Xcode 4.6 with IOS 6.0 as target. Tested on iPhone 4S. Try it by yourself.

Feng Chiu

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

That is invalid syntax. You are mixing relational expressions with scalar operators (OR). Specifically you cannot combine expr IN (select ...) OR (select ...). You probably want expr IN (select ...) OR expr IN (select ...). Using union would also work: expr IN (select... UNION select...)

How can I make a float top with CSS?

I just make with JQuery.

I tested in Firefox and IE10.

In my problem the items have different heights.

<!DOCTYPE html>
<html>
<head>
    <style>
        .item {
            border: 1px solid #FF0;
            width: 100px;
            position: relative;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
    <script>
        function itemClicked(e) {
            if (navigator.appName == 'Microsoft Internet Explorer')
                e.removeNode();
            else
                e.remove();
            reposition();
        }

        function reposition() {
            var px = 0;
            var py = 0;
            var margeY = 0;
            var limitContainer = $('#divContainer').innerHeight();
            var voltaY=false;

            $('#divContainer .item').each(function(key, value){
                var c = $(value);

                if ((py+c.outerHeight()) > limitContainer) {
                    px+=100;
                    margeY-=py;
                    py=0;
                    voltaY=true;
                }

                c.animate({
                    left:px+'px',
                    top:margeY+'px'
                });

                voltaY=false;
                py+=c.outerHeight();
            });
        }

        function addItem() {
            $('#divContainer').append('<div class="item" style="height: '+Math.floor(Math.random()*3+1)*20+'px;" onclick="itemClicked(this);"></div>');
            reposition();
        }

    </script>
    <div id="divMarge" style="height: 100px;"></div>
    <div id="divContainer" style="height: 200px; border: 1px solid #F00;">
        <!--div class="item"></div-->
    </div>
    <div style="border: 1px solid #00F;">
        <input type="button" value="Add Item" onclick="addItem();" />
    </div>
</body>
</html>

How can I loop through a C++ map of maps?

for(std::map<std::string, std::map<std::string, std::string> >::iterator outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(std::map<std::string, std::string>::iterator inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

or nicer in C++0x:

for(auto outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(auto inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

What is the use of printStackTrace() method in Java?

What is the use of e.printStackTrace() method in Java?

Well, the purpose of using this method e.printStackTrace(); is to see what exactly wrong is.

For example, we want to handle an exception. Let's have a look at the following Example.

public class Main{

  public static void main(String[] args) {

    int a = 12;
    int b = 2;

    try {
       int result = a / (b - 2);
       System.out.println(result);
    }

    catch (Exception e)
    {
       System.out.println("Error: " + e.getMessage());
       e.printStackTrace();
    }
  }
}

I've used method e.printStackTrace(); in order to show exactly what is wrong.

In the output, we can see the following result.

Error: / by zero

java.lang.ArithmeticException: / by zero

  at Main.main(Main.java:10)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Default behavior of "git push" without a branch specified

I just committed my code to a branch and pushed it to github, like this:

git branch SimonLowMemoryExperiments
git checkout SimonLowMemoryExperiments
git add .
git commit -a -m "Lots of experimentation with identifying the memory problems"
git push origin SimonLowMemoryExperiments

document.getElementById replacement in angular4 / typescript?

You can just inject the DOCUMENT token into the constructor and use the same functions on it

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(@Inject(DOCUMENT) document) {
      document.getElementById('el');
   }
}

Or if the element you want to get is in that component, you can use template references.

JavaScript OR (||) variable assignment explanation

It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.

it's the same as

if(x)
  z = x;
else
  z = y;

It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

Find CRLF in Notepad++

I've not had much luck with \r\n regular expressions from the find/replace window.

However, this works in Notepad++ v4.1.2:

  1. Use the "View | Show end of line" menu to enable display of end of line characters. (Carriage return line feeds should show up as a single shaded CRLF 'character'.)

  2. Select one of the CRLF 'characters' (put the cursor just in front of one, hold down the SHIFT key, and then pressing the RIGHT CURSOR key once).

  3. Copy the CRLF character to the clipboard.

  4. Make sure that you don't have the find or find/replace dialog open.

  5. Open the find/replace dialog. The 'Find what' field shows the contents of the clipboard: in this case the CRLF character - which shows up as 2 'box characters' (presumably it's an unprintable character?)

  6. Ensure that the 'Regular expression' option is OFF.

Now you should be able to count, find, or replace as desired.

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

example:

c++ -Wall filefork.cpp -lrt -O2

For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

Some older gcc version doesn't care about the position.

Python convert decimal to hex

A version using iteration:

def toHex(decimal):
    hex_str = ''
    digits = "0123456789ABCDEF"
    if decimal == 0:
       return '0'

    while decimal != 0:
        hex_str += digits[decimal % 16]
        decimal = decimal // 16

    return hex_str[::-1] # reverse the string

numbers = [0, 16, 20, 45, 255, 456, 789, 1024]
print([toHex(x) for x in numbers])
print([hex(x) for x in numbers])

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

Only local connections are allowed Chrome and Selenium webdriver

You need to pass --whitelisted-ips= into chrome driver (not chrome!). If you use ChromeDriver locally/directly (not using RemoteWebDriver) from code, it shouldn't be your problem.

If you use it remotely (eg. selenium hub/grid) you need to set system property when node starts, like in command:

java -Dwebdriver.chrome.whitelistedIps= testClass etc...

or docker by passing JAVA_OPTS env

  chrome:
    image: selenium/node-chrome:3.141.59
    container_name: chrome
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
      - JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

Deleting a file in VBA

set a reference to the Scripting.Runtime library and then use the FileSystemObject:

Dim fso as New FileSystemObject, aFile as File

if (fso.FileExists("PathToFile")) then
    aFile = fso.GetFile("PathToFile")
    aFile.Delete
End if

Unable to verify leaf signature

I had an issue with my Apache configuration after installing a GoDaddy certificate on a subdomain. I originally thought it might be an issue with Node not sending a Server Name Indicator (SNI), but that wasn't the case. Analyzing the subdomain's SSL certificate with https://www.ssllabs.com/ssltest/ returned the error Chain issues: Incomplete.

After adding the GoDaddy provided gd_bundle-g2-g1.crt file via the SSLCertificateChainFile Apache directive, Node was able to connect over HTTPS and the error went away.

How to cherry pick a range of commits and merge into another branch?

As of git v1.7.2 cherry pick can accept a range of commits:

git cherry-pick learned to pick a range of commits (e.g. cherry-pick A..B and cherry-pick --stdin), so did git revert; these do not support the nicer sequencing control rebase [-i] has, though.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

./xx.py: line 1: import: command not found

It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:

#!/usr/bin/python

and for the time being run using

python xx.py

For you here is one explanation:

>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>> 

>>> print "%s" %xyz

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print "%s" %xyz
NameError: name 'xyz' is not defined

At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!

LaTeX Optional Arguments

All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with

\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:

\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...

Amazon S3 boto - how to create a folder?

Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto

k = bucket.new_key('abc/123/')
k.set_contents_from_string('')

Or use the console

Big-oh vs big-theta

I'm a mathematician and I have seen and needed big-O O(n), big-Theta T(n), and big-Omega O(n) notation time and again, and not just for complexity of algorithms. As people said, big-Theta is a two-sided bound. Strictly speaking, you should use it when you want to explain that that is how well an algorithm can do, and that either that algorithm can't do better or that no algorithm can do better. For instance, if you say "Sorting requires T(n(log n)) comparisons for worst-case input", then you're explaining that there is a sorting algorithm that uses O(n(log n)) comparisons for any input; and that for every sorting algorithm, there is an input that forces it to make O(n(log n)) comparisons.

Now, one narrow reason that people use O instead of O is to drop disclaimers about worst or average cases. If you say "sorting requires O(n(log n)) comparisons", then the statement still holds true for favorable input. Another narrow reason is that even if one algorithm to do X takes time T(f(n)), another algorithm might do better, so you can only say that the complexity of X itself is O(f(n)).

However, there is a broader reason that people informally use O. At a human level, it's a pain to always make two-sided statements when the converse side is "obvious" from context. Since I'm a mathematician, I would ideally always be careful to say "I will take an umbrella if and only if it rains" or "I can juggle 4 balls but not 5", instead of "I will take an umbrella if it rains" or "I can juggle 4 balls". But the other halves of such statements are often obviously intended or obviously not intended. It's just human nature to be sloppy about the obvious. It's confusing to split hairs.

Unfortunately, in a rigorous area such as math or theory of algorithms, it's also confusing not to split hairs. People will inevitably say O when they should have said O or T. Skipping details because they're "obvious" always leads to misunderstandings. There is no solution for that.

How do you add an in-app purchase to an iOS application?

Swift Answer

This is meant to supplement my Objective-C answer for Swift users, to keep the Objective-C answer from getting too big.

Setup

First, set up the in-app purchase on appstoreconnect.apple.com. Follow the beginning part of my Objective-C answer (steps 1-13, under the App Store Connect header) for instructions on doing that.

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Now that you've set up your in-app purchase information on App Store Connect, we need to add Apple's framework for in-app-purchases, StoreKit, to the app.

Go into your Xcode project, and go to the application manager (blue page-like icon at the top of the left bar where your app's files are). Click on your app under targets on the left (it should be the first option), then go to "Capabilities" at the top. On the list, you should see an option "In-App Purchase". Turn this capability ON, and Xcode will add StoreKit to your project.

Coding

Now, we're going to start coding!

First, make a new swift file that will manage all of your in-app-purchases. I'm going to call it IAPManager.swift.

In this file, we're going to create a new class, called IAPManager that is a SKProductsRequestDelegate and SKPaymentTransactionObserver. At the top, make sure you import Foundation and StoreKit

import Foundation
import StoreKit

public class IAPManager: NSObject, SKProductsRequestDelegate,
                         SKPaymentTransactionObserver {
}

Next, we're going to add a variable to define the identifier for our in-app purchase (you could also use an enum, which would be easier to maintain if you have multiple IAPs).

// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
let removeAdsID = "com.skiplit.removeAds"

Let's add an initializer for our class next:

// This is the initializer for your IAPManager class
//
// A better, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager (you'll see those calls in the code below).

let productID: String
init(productID: String){
    self.productID = productID
}

Now, we're going to add the required functions for SKProductsRequestDelegate and SKPaymentTransactionObserver to work:

We'll add the RemoveAdsManager class later

// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
    // Let's try to get the first product from the response
    // to the request
    if let product = response.products.first{
        // We were able to get the product! Make a new payment
        // using this product
        let payment = SKPayment(product: product)

        // add the new payment to the queue
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(payment)
    }
    else{
        // Something went wrong! It is likely that either
        // the user doesn't have internet connection, or
        // your product ID is wrong!
        //
        // Tell the user in requestFailed() by sending an alert,
        // or something of the sort

        RemoveAdsManager.removeAdsFailure()
    }
}

// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
    // For every transaction in the transaction queue...
    for transaction in queue.transactions{
        // If that transaction was restored
        if transaction.transactionState == .restored{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is. However, this is useful if you have multiple IAPs!
            // You'll need to figure out which one was restored
            if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                // Restore the user's purchases
                RemoveAdsManager.restoreRemoveAdsSuccess()
            }

            // finish the payment
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }
}

// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
    for transaction in transactions{
        // get the producted ID from the transaction
        let productID = transaction.payment.productIdentifier

        // In this case, we have only one IAP, so we don't need to check
        // what IAP it is.
        // However, if you have multiple IAPs, you'll need to use productID
        // to check what functions you should run here!

        switch transaction.transactionState{
        case .purchasing:
            // if the user is currently purchasing the IAP,
            // we don't need to do anything.
            //
            // You could use this to show the user
            // an activity indicator, or something like that
            break
        case .purchased:
            // the user successfully purchased the IAP!
            RemoveAdsManager.removeAdsSuccess()
            SKPaymentQueue.default().finishTransaction(transaction)
        case .restored:
                // the user restored their IAP!
                IAPTestingHandler.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
        case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
        case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
        }
    }
}

Now let's add some functions that can be used to start a purchase or a restore purchases:

// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
    // If the user can make payments
    if SKPaymentQueue.canMakePayments(){
        // Create a new request
        let request = SKProductsRequest(productIdentifiers: [productID])
        // Set the request delegate to self, so we receive a response
        request.delegate = self
        // start the request
        request.start()
    }
    else{
        // Otherwise, tell the user that
        // they are not authorized to make payments,
        // due to parental controls, etc
    }
}

// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
    // restore purchases, and give responses to self
    SKPaymentQueue.default().add(self)
    SKPaymentQueue.default().restoreCompletedTransactions()
}

Next, let's add a new utilities class to manage our IAPs. All of this code could be in one class, but having it multiple makes it a little cleaner. I'm going to make a new class called RemoveAdsManager, and in it, put a few functions

public class RemoveAdsManager{

    class func removeAds()
    class func restoreRemoveAds()

    class func areAdsRemoved() -> Bool

    class func removeAdsSuccess()
    class func restoreRemoveAdsSuccess()
    class func removeAdsDeferred()
    class func removeAdsFailure()
}

The first three functions, removeAds, restoreRemoveAds, and areAdsRemoved, are functions that you'll call to do certain actions. The last four are one that will be called by IAPManager.

Let's add some code to the first two functions, removeAds and restoreRemoveAds:

// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
    // Before starting the purchase, you could tell the
    // user that their purchase is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginPurchase()
}

// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
    // Before starting the purchase, you could tell the
    // user that the restore action is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginRestorePurchases()
}

And lastly, let's add some code to the last five functions.

// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
    // This is the code that is run to check
    // if the user has the IAP.

    return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}

// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
    // This is the code that is run to actually
    // give the IAP to the user!
    //
    // I'm using UserDefaults in this example,
    // but you may want to use Keychain,
    // or some other method, as UserDefaults
    // can be modified by users using their
    // computer, if they know how to, more
    // easily than Keychain

    UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
    UserDefaults.standard.synchronize()
}

// This will be called by IAPManager
// when the user sucessfully restores
//  their purchases
class func restoreRemoveAdsSuccess(){
    // Give the user their IAP back! Likely all you'll need to
    // do is call the same function you call when a user
    // sucessfully completes their purchase. In this case, removeAdsSuccess()

    removeAdsSuccess()
}

// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
    // Send the user a message explaining that the IAP
    // failed for some reason, and to try again later
}

// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
    // Send the user a message explaining that the IAP
    // was deferred, and pending an external action, like
    // Ask to Buy.
}

Putting it all together, we get something like this:

import Foundation
import StoreKit

public class RemoveAdsManager{

    // Call this when the user wants
    // to remove ads, like when they
    // press a "remove ads" button
    class func removeAds(){
        // Before starting the purchase, you could tell the
        // user that their purchase is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginPurchase()
    }

    // Call this when the user wants
    // to restore their IAP purchases,
    // like when they press a "restore
    // purchases" button.
    class func restoreRemoveAds(){
        // Before starting the purchase, you could tell the
        // user that the restore action is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginRestorePurchases()
    }

    // Call this to check whether or not
    // ads are removed. You can use the
    // result of this to hide or show
    // ads
    class func areAdsRemoved() -> Bool{
        // This is the code that is run to check
        // if the user has the IAP.

        return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
    }

    // This will be called by IAPManager
    // when the user sucessfully purchases
    // the IAP
    class func removeAdsSuccess(){
        // This is the code that is run to actually
        // give the IAP to the user!
        //
        // I'm using UserDefaults in this example,
        // but you may want to use Keychain,
        // or some other method, as UserDefaults
        // can be modified by users using their
        // computer, if they know how to, more
        // easily than Keychain

        UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
        UserDefaults.standard.synchronize()
    }

    // This will be called by IAPManager
    // when the user sucessfully restores
    //  their purchases
    class func restoreRemoveAdsSuccess(){
        // Give the user their IAP back! Likely all you'll need to
        // do is call the same function you call when a user
        // sucessfully completes their purchase. In this case, removeAdsSuccess()
        removeAdsSuccess()
    }

    // This will be called by IAPManager
    // when the IAP failed
    class func removeAdsFailure(){
        // Send the user a message explaining that the IAP
        // failed for some reason, and to try again later
    }

    // This will be called by IAPManager
    // when the IAP gets deferred.
    class func removeAdsDeferred(){
        // Send the user a message explaining that the IAP
        // was deferred, and pending an external action, like
        // Ask to Buy.
    }

}

public class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{

    // This should the ID of the in-app-purchase you made on AppStore Connect.
    // if you have multiple IAPs, you'll need to store their identifiers in
    // other variables, too (or, preferably in an enum).
    static let removeAdsID = "com.skiplit.removeAds"

    // This is the initializer for your IAPManager class
    //
    // An alternative, and more scaleable way of doing this
    // is to also accept a callback in the initializer, and call
    // that callback in places like the paymentQueue function, and
    // in all functions in this class, in place of calls to functions
    // in RemoveAdsManager.
    let productID: String
    init(productID: String){
        self.productID = productID
    }

    // Call this when you want to begin a purchase
    // for the productID you gave to the initializer
    public func beginPurchase(){
        // If the user can make payments
        if SKPaymentQueue.canMakePayments(){
            // Create a new request
            let request = SKProductsRequest(productIdentifiers: [productID])
            request.delegate = self
            request.start()
        }
        else{
            // Otherwise, tell the user that
            // they are not authorized to make payments,
            // due to parental controls, etc
        }
    }

    // Call this when you want to restore all purchases
    // regardless of the productID you gave to the initializer
    public func beginRestorePurchases(){
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // This is called when a SKProductsRequest receives a response
    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
        // Let's try to get the first product from the response
        // to the request
        if let product = response.products.first{
            // We were able to get the product! Make a new payment
            // using this product
            let payment = SKPayment(product: product)

            // add the new payment to the queue
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().add(payment)
        }
        else{
            // Something went wrong! It is likely that either
            // the user doesn't have internet connection, or
            // your product ID is wrong!
            //
            // Tell the user in requestFailed() by sending an alert,
            // or something of the sort

            RemoveAdsManager.removeAdsFailure()
        }
    }

    // This is called when the user restores their IAP sucessfully
    private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
        // For every transaction in the transaction queue...
        for transaction in queue.transactions{
            // If that transaction was restored
            if transaction.transactionState == .restored{
                // get the producted ID from the transaction
                let productID = transaction.payment.productIdentifier

                // In this case, we have only one IAP, so we don't need to check
                // what IAP it is. However, this is useful if you have multiple IAPs!
                // You'll need to figure out which one was restored
                if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                    // Restore the user's purchases
                    RemoveAdsManager.restoreRemoveAdsSuccess()
                }

                // finish the payment
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
    }

    // This is called when the state of the IAP changes -- from purchasing to purchased, for example.
    // This is where the magic happens :)
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
        for transaction in transactions{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is.
            // However, if you have multiple IAPs, you'll need to use productID
            // to check what functions you should run here!

            switch transaction.transactionState{
            case .purchasing:
                // if the user is currently purchasing the IAP,
                // we don't need to do anything.
                //
                // You could use this to show the user
                // an activity indicator, or something like that
                break
            case .purchased:
                // the user sucessfully purchased the IAP!
                RemoveAdsManager.removeAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                // the user restored their IAP!
                RemoveAdsManager.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
            case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
            }
        }
    }

}

Lastly, you need to add some way for the user to start the purchase and call RemoveAdsManager.removeAds() and start a restore and call RemoveAdsManager.restoreRemoveAds(), like a button somewhere! Keep in mind that, per the App Store guidelines, you do need to provide a button to restore purchases somewhere.

Submitting for review

The last thing to do is submit your IAP for review on App Store Connect! For detailed instructions on doing that, you can follow the last part of my Objective-C answer, under the Submitting for review header.

Invoke-customs are only supported starting with android 0 --min-api 26

If you have Java 7 so include the below following snippet within your app-level build.gradle :

compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

}

How to modify JsonNode in Java?

The @Sharon-Ben-Asher answer is ok.

But in my case, for an array i have to use:

((ArrayNode) jsonNode).add("value");

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

OpenCV !_src.empty() in function 'cvtColor' error

I kept getting this error too:

Traceback (most recent call last):
  File "face_detector.py", line 6, in <module>
    gray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor

My cv2.cvtColor(...) was working fine with \photo.jpg but not with \news.jpg. For me, I finally realized that when working on Windows with python, those escape characters will get you every time!! So my "bad" photo was being escaped because of the file name beginning with "n". Python took the \n as an escape character and OpenCV couldn't find the file!

Solution:
Preface file names in Windows python with r"...\...\" as in

cv2.imread(r".\images\news.jpg")

Java: how do I get a class literal from a generic type?

You can't due to type erasure.

Java generics are little more than syntactic sugar for Object casts. To demonstrate:

List<Integer> list1 = new ArrayList<Integer>();
List<String> list2 = (List<String>)list1;
list2.add("foo"); // perfectly legal

The only instance where generic type information is retained at runtime is with Field.getGenericType() if interrogating a class's members via reflection.

All of this is why Object.getClass() has this signature:

public final native Class<?> getClass();

The important part being Class<?>.

To put it another way, from the Java Generics FAQ:

Why is there no class literal for concrete parameterized types?

Because parameterized type has no exact runtime type representation.

A class literal denotes a Class object that represents a given type. For instance, the class literal String.class denotes the Class object that represents the type String and is identical to the Class object that is returned when method getClass is invoked on a String object. A class literal can be used for runtime type checks and for reflection.

Parameterized types lose their type arguments when they are translated to byte code during compilation in a process called type erasure . As a side effect of type erasure, all instantiations of a generic type share the same runtime representation, namely that of the corresponding raw type . In other words, parameterized types do not have type representation of their own. Consequently, there is no point in forming class literals such as List<String>.class , List<Long>.class and List<?>.class , since no such Class objects exist. Only the raw type List has a Class object that represents its runtime type. It is referred to as List.class.

How to copy a map?

As stated in seong's comment:

Also see http://golang.org/doc/effective_go.html#maps. The important part is really the "reference to underlying data structure". This also applies to slices.

However, none of the solutions here seem to offer a solution for a proper deep copy that also covers slices.

I've slightly altered Francesco Casula's answer to accommodate for both maps and slices.


This should cover both copying your map itself, as well as copying any child maps or slices. Both of which are affected by the same "underlying data structure" issue. It also includes a utility function for performing the same type of Deep Copy on a slice directly.

Keep in mind that the slices in the resulting map will be of type []interface{}, so when using them, you will need to use type assertion to retrieve the value in the expected type.

Example Usage

copy := CopyableMap(originalMap).DeepCopy()

Source File (util.go)

package utils

type CopyableMap   map[string]interface{}
type CopyableSlice []interface{}

// DeepCopy will create a deep copy of this map. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (m CopyableMap) DeepCopy() map[string]interface{} {
    result := map[string]interface{}{}

    for k,v := range m {
        // Handle maps
        mapvalue,isMap := v.(map[string]interface{})
        if isMap {
            result[k] = CopyableMap(mapvalue).DeepCopy()
            continue
        }

        // Handle slices
        slicevalue,isSlice := v.([]interface{})
        if isSlice {
            result[k] = CopyableSlice(slicevalue).DeepCopy()
            continue
        }

        result[k] = v
    }

    return result
}

// DeepCopy will create a deep copy of this slice. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (s CopyableSlice) DeepCopy() []interface{} {
    result := []interface{}{}

    for _,v := range s {
        // Handle maps
        mapvalue,isMap := v.(map[string]interface{})
        if isMap {
            result = append(result, CopyableMap(mapvalue).DeepCopy())
            continue
        }

        // Handle slices
        slicevalue,isSlice := v.([]interface{})
        if isSlice {
            result = append(result, CopyableSlice(slicevalue).DeepCopy())
            continue
        }

        result = append(result, v)
    }

    return result
}

Test File (util_tests.go)

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
        "c": []interface{} {
            "d", "e", map[string]interface{} {
                "f": "g",
            },
        },
    }

    m2 := CopyableMap(m1).DeepCopy()

    m1["a"] = "zzz"
    delete(m1, "b")
    m1["c"].([]interface{})[1] = "x"
    m1["c"].([]interface{})[2].(map[string]interface{})["f"] = "h"

    require.Equal(t, map[string]interface{}{
        "a": "zzz", 
        "c": []interface{} {
            "d", "x", map[string]interface{} {
                "f": "h",
            },
        },
    }, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
        "c": []interface{} {
            "d", "e", map[string]interface{} {
                "f": "g",
            },
        },
    }, m2)
}

Java Delegates?

Not really, no.

You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).

You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (@blueskyprojects.com)

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

How to filter input type="file" dialog by specific file type?

You can use the accept attribute along with the . It doesn't work in IE and Safari.

Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.

For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Select2 for Bootstrap 3 native plugin

https://fk.github.io/select2-bootstrap-css/index.html

this plugin uses select2 jquery plugin

nuget

PM> Install-Package Select2-Bootstrap

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

javascript: pause setTimeout();

If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:

    public timer(fn: (...args: any[]) => void, countdown: number): { onCancel: () => void, onPause: () => void, onResume: () => void } {
        let ident: NodeJS.Timeout | number;
        let complete = false;
        let totalTimeRun: number;
        const onTimeDiff = (date1: number, date2: number) => {
            return date2 ? date2 - date1 : new Date().getTime() - date1;
        };

        const handlers = {
            onCancel: () => {
                clearTimeout(ident as NodeJS.Timeout);
            },
            onPause: () => {
                clearTimeout(ident as NodeJS.Timeout);
                totalTimeRun = onTimeDiff(startTime, null);
                complete = totalTimeRun >= countdown;
            },
            onResume: () => {
                ident = complete ? -1 : setTimeout(fn, countdown - totalTimeRun);
            }
        };

        const startTime = new Date().getTime();
        ident = setTimeout(fn, countdown);

        return handlers;
    }

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

if you are using httpd/apache, you can add a file something like ws.conf and add this code to it. Also, this solution can proxy something like this "http://localhost:6001/socket.io" to just this "http://localhost/socket.io"

<VirtualHost *:80>
    RewriteEngine on

    #redirect WebSocket
    RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyPass        /socket.io http://localhost:6001/socket.io
    ProxyPassReverse /socket.io http://localhost:6001/socket.io
</VirtualHost>

"ssl module in Python is not available" when installing package with pip3

I had the same issue with python3.8.5 installation on Debian9. I have done a build, but when I have tried to download some modules, pip3.8 issued following error:

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

I have searched for the root of my problem and found out that there is a system dependent portion of the python build which is called by system independent one. In case of missing ssl you just needed to open python terminal and check whether is _ssl present:

>>> help('modules')
.
.
_sre                enum                pwd                 wave
_ssl                errno               py_compile          weakref
_stat               faulthandler        pyclbr              webbrowser
.
.

If not your system dependent ssl module part is missing. You can check it also by listing content of <python_installation_root>/lib/python3.8/lib-dynload:

>ls ./lib/python3.8/lib-dynload | grep ssl
_ssl.cpython-38-x86_64-linux-gnu.so

The problem was caused as written by PengShaw by missing libssl-dev during the build. Therefore you have to follow the recommended python installation flow. First install prerequisites and then build and install the python. Installation without devel versions of libs resulted in my case in the missing system dependent part. In this case _ssl.

Note that the devel lib name differs for Debian and CentOS, therefore check whether the installation hints posted on net are suitable for your specific Linux system type:

For Debian:
sudo apt install -y libbz2-dev libffi-dev libssl-dev
./configure --enable-optimizations
make
make altinstall


For CentOS:
sudo yum -y install bzip2-devel libffi-devel openssl-devel
./configure --enable-optimizations
make
make altinstall

It is for sure a good idea to list configuration options prior the configuration and evtl. use some additional options:

./configure --help

Last but not least in case you use --prefix for a non-default installation location, remember to add your <python_installation_root>/lib to your LD_LIBRARY_PATH .

How to reload a page using Angularjs?

$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

How to create a timeline with LaTeX?

The tikz package seems to have what you want.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}

\begin{document}

  \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
    % draw horizontal line   
    \draw (0,0) -- (2,0);
    \draw[snake] (2,0) -- (4,0);
    \draw (4,0) -- (5,0);
    \draw[snake] (5,0) -- (7,0);

    % draw vertical lines
    \foreach \x in {0,1,2,4,5,7}
      \draw (\x cm,3pt) -- (\x cm,-3pt);

    % draw nodes
    \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
    \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
    \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
    \draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
    \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
    \draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
  \end{tikzpicture}

\end{document}

I'm not too expert with tikz, but this does give a good timeline, which looks like:

enter image description here

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I've seen several answers and that's the only procedure that let me fix that without any conflicts.

If you want all changes from branch_new in branch_old, then:

git checkout branch_new
git merge -s ours branch_old
git checkout branch_old
git merge branch_new

once applied those four commands you can push the branch_old without any problem

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Eloquent ->first() if ->exists()

An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.

    try {
        $user = User::where('mobile', Input::get('mobile'))->first();
    } catch (ErrorException $e) {
        // Do stuff here that you need to do if it doesn't exist.
        return View::make('some.view')->with('msg', $e->getMessage());
    }

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

AngularJS Folder Structure

enter image description here

Sort By Type

On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.

Sort By Feature (preferred)

On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.

A well written blog post: http://www.johnpapa.net/angular-growth-structure/

Example App: https://github.com/angular-app/angular-app

Conda environments not showing up in Jupyter Notebook

    $ conda install nb_conda_kernels

(in the conda environment where you run jupyter notebook) will make all conda envs available automatically. For access to other environments, the respective kernels must be installed. Here's the ref.

Converting double to integer in Java

For the datatype Double to int, you can use the following:

Double double = 5.00;

int integer = double.intValue();

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

prevent property from being serialized in web API

For some reason [IgnoreDataMember] does not always work for me, and I sometimes get StackOverflowException (or similar). So instead (or in addition) i've started using a pattern looking something like this when POSTing in Objects to my API:

[Route("api/myroute")]
[AcceptVerbs("POST")]
public IHttpActionResult PostMyObject(JObject myObject)
{
    MyObject myObjectConverted = myObject.ToObject<MyObject>();

    //Do some stuff with the object

    return Ok(myObjectConverted);
}

So basically i pass in an JObject and convert it after it has been recieved to aviod problems caused by the built-in serializer that sometimes cause an infinite loop while parsing the objects.

If someone know a reason that this is in any way a bad idea, please let me know.

It may be worth noting that it is the following code for an EntityFramework Class-property that causes the problem (If two classes refer to each-other):

[Serializable]
public partial class MyObject
{
   [IgnoreDataMember]
   public MyOtherObject MyOtherObject => MyOtherObject.GetById(MyOtherObjectId);
}

[Serializable]
public partial class MyOtherObject
{
   [IgnoreDataMember]
   public List<MyObject> MyObjects => MyObject.GetByMyOtherObjectId(Id);
}

how to generate web service out of wsdl

This may be very late in answering. But might be helpful to needy: How to convert WSDL to SVC :

  1. Assuming you are having .wsdl file at location "E:\" for ease in access further.
  2. Prepare the command for each .wsdl file as: E:\YourServiceFileName.wsdl
  3. Permissions: Assuming you are having the Administrative rights to perform permissions. Open directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
  4. Right click to amd64 => Security => Edit => Add User => Everyone Or Current User => Allow all permissions => OK.
  5. Prepare the Commands for each file in text editor as: wsdl.exe E:\YourServiceFileName.wsdl /l:CS /server.
  6. Now open Visual studio command prompt from : C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x64 Native Tools Command Prompt.
  7. Execute above command.
  8. Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated.

    9.Move generated CS file to appropriate location.

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

How to send Basic Auth with axios

The reason the code in your question does not authenticate is because you are sending the auth in the data object, not in the config, which will put it in the headers. Per the axios docs, the request method alias for post is:

axios.post(url[, data[, config]])

Therefore, for your code to work, you need to send an empty object for data:

var session_url = 'http://api_address/api/session_endpoint';
var username = 'user';
var password = 'password';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.post(session_url, {}, {
  headers: { 'Authorization': + basicAuth }
}).then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});

The same is true for using the auth parameter mentioned by @luschn. The following code is equivalent, but uses the auth parameter instead (and also passes an empty data object):

var session_url = 'http://api_address/api/session_endpoint';
var uname = 'user';
var pass = 'password';
axios.post(session_url, {}, {
  auth: {
    username: uname,
    password: pass
  }
}).then(function(response) {
  console.log('Authenticated');
}).catch(function(error) {
  console.log('Error on Authentication');
});

How to get values and keys from HashMap?

You have to follow the following sequence of opeartions:

  • Convert Map to MapSet with map.entrySet();
  • Get the iterator with Mapset.iterator();
  • Get Map.Entry with iterator.next();
  • use Entry.getKey() and Entry.getValue()
# define Map
for (Map.Entry entry: map.entrySet)
    System.out.println(entry.getKey() + entry.getValue);

Program to find prime numbers

static void Main(string[] args)
    {  int i,j;
        Console.WriteLine("prime no between 1 to 100");
    for (i = 2; i <= 100; i++)
    {
        int count = 0;
        for (j = 1; j <= i; j++)
        {

            if (i % j == 0)
            { count=count+1; }
        }

        if ( count <= 2)
        { Console.WriteLine(i); }


    }
    Console.ReadKey();

    }

Convert CString to const char*

I used this conversion:

CString cs = "TEST";
char* c = cs.GetBuffer(m_ncs me.GetLength())

I hope this is useful.

Get current folder path

string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

From Path.GetDirectoryName

Returns the directory information for the specified path string.

From Application.ExecutablePath

Gets the path for the executable file that started the application, including the executable name.

Upload a file to Amazon S3 with NodeJS

var express = require('express')

app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);

var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')

    aws.config.update({
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    region: 'us-east-1'
    });
    s3 = new aws.S3();

   var upload = multer({
   storage: multerS3({
    s3: s3,
    dirname: "uploads",
    bucket: "Your bucket name",
    key: function (req, file, cb) {
        console.log(file);
        cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use  
     Date.now() for unique file keys
    }
  })
   });

 app.post('/upload', upload.single('photos'), function(req, res, next) {

 console.log('Successfully uploaded ', req.file)

 res.send('Successfully uploaded ' + req.file.length + ' files!')

})

How to sort an array based on the length of each element?

<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

Ways to circumvent the same-origin policy

The JSONP comes to mind:

JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

error: cast from 'void*' to 'int' loses precision

A function pointer is incompatible to void* (and any other non function pointer)

How do I remove the "extended attributes" on a file in Mac OS X?

Try using:

xattr -rd com.apple.quarantine directoryname

This takes care of recursively removing the pesky attribute everywhere.

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

Why is vertical-align:text-top; not working in CSS

something like

  position:relative;
  top:-5px;

just on the inline element itself works for me. Have to play with the top to get it centered vertically...

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Simply use the Body Tab and enter the post parameters there. Note that Body Tab is disabled if Get is selected.

Why is 22 the default port number for SFTP?

Not authoritative, but interesting: 21 is FTP, 23 is telnet. 22 is SSH...something in between (that can take the place of both).

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:

I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:

Step 1. in your backend, create a folder called security. we will work inside it.

Step 2. create a request config file named req.cnf with the following content (credit goes to: @Anshul)

req.cnf :

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

An explanation of this fields is here.

Step 3. navigate to the security folder in the terminal and type the following command :

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256

Step 4. then outside of security folder, in your express app do something like this: (credit goes to @Diego Mello)

backend 
 /security
 /server.js

server.js:

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
    res.send("IT'S WORKING!")
})

const httpsOptions = {
    key: fs.readFileSync('./security/cert.key'),
    cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
    .listen(port, () => {
        console.log('server running at ' + port)
    })

Step 5. start the server, node server.js, and go to https://localhost:3000.

At this point we have the server setup. But the browser should show a warning message.

We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store. (chrome also saves this in windows,)

Step 6. open Dev Tools in chrome, go to Security panel, then click on View Certificate. enter image description here

Step 7. go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:

go to details - copy file - next on export wizard

Step 8. leave DER encoding, click next, choose Browse, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.. You should be able to see your certificate on Desktop.

Step 9. Open chrome://settings/ by inserting it in the url box. Down below, click on Advanced / Advanced Options, then scroll down to find Manage Certificates.

choose manage certificates

Step 10. Go to Trusted Root Certification Authorities panel, and click import.

Go to Trusted Root Certification Authorities panel, and click import

We will import the localhost.cer certificate we just finished exporting in step 8.

Step 11. click browse, find the localhost.cer, leave the default values click next a bunch of times - until this warning appears, click yes.

confirm security exception

Step 12. close everything, and restart chrome. Then, when going to https://localhost:3000 you should see: gotta love the green

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

Change color and appearance of drop down arrow

It can be done by:

select{
  background: url(data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6IzQ0NDt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPmFycm93czwvdGl0bGU+PHJlY3QgY2xhc3M9ImNscy0xIiB3aWR0aD0iNC45NSIgaGVpZ2h0PSIxMCIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxLjQxIDQuNjcgMi40OCAzLjE4IDMuNTQgNC42NyAxLjQxIDQuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIi8+PC9zdmc+) no-repeat 100% 50%;
}

_x000D_
_x000D_
select{_x000D_
  background: url(data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6IzQ0NDt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPmFycm93czwvdGl0bGU+PHJlY3QgY2xhc3M9ImNscy0xIiB3aWR0aD0iNC45NSIgaGVpZ2h0PSIxMCIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxLjQxIDQuNjcgMi40OCAzLjE4IDMuNTQgNC42NyAxLjQxIDQuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIi8+PC9zdmc+) no-repeat 100% 50%;_x000D_
  _x000D_
  _x000D_
    -moz-appearance: none;_x000D_
    -webkit-appearance: none;_x000D_
    -webkit-border-radius: 0px;_x000D_
    appearance: none;_x000D_
    outline-width: 0;_x000D_
    _x000D_
    padding: 10px 10px 10px 5px;_x000D_
    display: block;_x000D_
    width: 10em;_x000D_
    border: none;_x000D_
    font-size: 1rem;_x000D_
    _x000D_
    border-bottom: 1px solid #757575;_x000D_
  }
_x000D_
<div class="styleSelect">_x000D_
  <select class="units">_x000D_
    <option value="Metres">Metres</option>_x000D_
    <option value="Feet">Feet</option>_x000D_
    <option value="Fathoms">Fathoms</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Download pdf file using jquery ajax

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a PDF file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.pdf";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

What is makeinfo, and how do I get it?

If you build packages from scratch:

Specifically, if you build bash from source, install docs, including man pages, will fail (silently) without makeinfo available.

Is there a concurrent List in Java's JDK?

ConcurrentLinkedQueue

If you don't care about having index-based access and just want the insertion-order-preserving characteristics of a List, you could consider a java.util.concurrent.ConcurrentLinkedQueue. Since it implements Iterable, once you've finished adding all the items, you can loop over the contents using the enhanced for syntax:

Queue<String> globalQueue = new ConcurrentLinkedQueue<String>();

//Multiple threads can safely call globalQueue.add()...

for (String href : globalQueue) {
    //do something with href
}

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

What is the difference between Linear search and Binary search?

For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN

Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.

Here is the javascript code, for html and css and full running example please refer to above codepen link.

var unsortedhaystack = [];
var haystack = [];
function init() {
  unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
  var t = timer('sort benchmark');
  haystack = unsortedhaystack.sort();
  t.stop();
}

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

function lineerSearch() {
  init();
  var t = timer('lineerSearch benchmark');
  var input = this.event.target.value;
  for(var i = 0;i<unsortedhaystack.length - 1;i++) {
    if (unsortedhaystack[i] === input) {
      document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return unsortedhaystack[i]; 
    }
  }
}

function binarySearch () {
  init();
  sortHaystack();
  var t = timer('binarySearch benchmark');
  var firstIndex = 0;
  var lastIndex = haystack.length-1;
  var input = this.event.target.value;

  //currently point in the half of the array
  var currentIndex = (haystack.length-1)/2 | 0;
  var iterations = 0;

  while (firstIndex <= lastIndex) {
    currentIndex = (firstIndex + lastIndex)/2 | 0;
    iterations++;
    if (haystack[currentIndex]  < input) {
      firstIndex = currentIndex + 1;
      //console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
    } else if (haystack[currentIndex] > input) {
      lastIndex = currentIndex - 1;
      //console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
    } else {
      document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return true;
    }
  }
}

Copying PostgreSQL database to another server

Here is an example using pg_basebackup

I chose to go this route because it backs up the entire database cluster (users, databases, etc.).

I'm posting this as a solution on here because it details every step I had to take, feel free to add recommendations or improvements after reading other answers on here and doing some more research.

For Postgres 12 and Ubuntu 18.04 I had to do these actions:


On the server that is currently running the database:

Update pg_hba.conf, for me located at /etc/postgresql/12/main/pg_hba.conf

Add the following line (substitute 192.168.0.100 with the IP address of the server you want to copy the database to).

host  replication  postgres  192.168.0.100/32  trust

Update postgresql.conf, for me located at /etc/postgresql/12/main/postgresql.conf. Add the following line:

listen_addresses = '*'

Restart postgres:

sudo service postgresql restart


On the host you want to copy the database cluster to:

sudo service postgresql stop

sudo su root

rm -rf /var/lib/postgresql/12/main/*

exit

sudo -u postgres pg_basebackup -h 192.168.0.101 -U postgres -D /var/lib/postgresql/12/main/

sudo service postgresql start

Big picture - stop the service, delete everything in the data directory (mine is in /var/lib/postgreql/12). The permissions on this directory are drwx------ with user and group postgres. I could only do this as root, not even with sudo -u postgres. I'm unsure why. Ensure you are doing this on the new server you want to copy the database to! You are deleting the entire database cluster.

Make sure to change the IP address from 192.168.0.101 to the IP address you are copying the database from. Copy the data from the original server with pg_basebackup. Start the service.

Update pg_hba.conf and postgresql.conf to match the original server configuration - before you made any changes adding the replication line and the listen_addresses line (in my care I had to add the ability to log-in locally via md5 to pg_hba.conf).

Note there are considerations for max_wal_senders and wal_level that can be found in the documentation. I did not have to do anything with this.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

Python: finding lowest integer

l is a list of strings. When you put numbers between single quotes like that, you are creating strings, which are just a sequence of characters. To make your code work properly, you would have to do this:

l = [-1.2, 0.0, 1]  # no quotation marks

x = 100.0
for i in l:
    if i < x:
        x = i
print x

If you must use a list of strings, you can try to let Python try to make a number out of each string. This is similar to Justin's answer, except it understands floating-point (decimal) numbers correctly.

l = ['-1.2', '0.0', '1']

x = 100.0
for i in l:
    inum = float(i)
    if inum < x:
        x = inum
print x

I hope that this is code that you are writing to learn either Python or programming in general. If this is the case, great. However, if this is production code, consider using Python's built-in functions.

l = ['-1.2', '0.0', '1']
lnums = map(float, l)  # turn strings to numbers
x = min(lnums)  # find minimum value
print x

How to remove elements from a generic list while iterating over it?

You can't use foreach, but you could iterate forwards and manage your loop index variable when you remove an item, like so:

for (int i = 0; i < elements.Count; i++)
{
    if (<condition>)
    {
        // Decrement the loop counter to iterate this index again, since later elements will get moved down during the remove operation.
        elements.RemoveAt(i--);
    }
}

Note that in general all of these techniques rely on the behaviour of the collection being iterated. The technique shown here will work with the standard List(T). (It is quite possible to write your own collection class and iterator that does allow item removal during a foreach loop.)

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

How to copy a file to another path?

Have a look at File.Copy()

Using File.Copy you can specify the new file name as part of the destination string.

So something like

File.Copy(@"c:\test.txt", @"c:\test\foo.txt");

See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)

Creating a simple configuration file and parser in C++

Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.

Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.

//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150

std::string ipName;
int nR, nC;

std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;

while (std::getline(fin, line)) {
 sin.str(line.substr(line.find("=")+1));
 if (line.find("Input name") != std::string::npos) {
  std::cout<<"Input name "<<sin.str()<<std::endl;
  sin >> ipName;
 }
 else if (line.find("Num. of rows") != std::string::npos) {
  sin >> nR;
 }
 else if (line.find("Num. of cols") != std::string::npos) {
  sin >> nC;
 }
 sin.clear();
}

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

error while loading shared libraries: libncurses.so.5:

In Fedora 28 use:

sudo dnf install ncurses-compat-libs

Jquery to open Bootstrap v3 modal of remote url

A different perspective to the same problem away from Javascript and using php:

<a data-toggle="modal" href="#myModal">LINK</a>

<div class="modal fade" tabindex="-1" aria-labelledby="gridSystemModalLabel" id="myModal" role="dialog" style="max-width: 90%;">
    <div class="modal-dialog" style="text-align: left;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Title</h4>
            </div>
            <div class="modal-body">
                <?php include( 'remotefile.php'); ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

and put in the remote.php file your basic html source.

How different is Scrum practice from Agile Practice?

Scrum comes under bigger umbrella called Agile. Kanban, eXtreme Programming (XP), Lean are said to come under Agile too.

My personal experience is: there is no separate word called "Agile Practice". Best practices exercised in SCRUM, XP may be cumulatively called as Agile Practice.

The following practices are visible in both XP and SCRUM, hence in Agile.

  1. User Story as Client requirement
  2. Pair Programming
  3. Test Driven Development (TDD)
  4. Team based estimation
  5. Refactoring
  6. Simple Design
  7. Evolutionary Design
  8. Retrospective
  9. Daily Stand up meeting
  10. Continuous Integration of code
  11. Client Demo etc.

For more details, you may wish to go through my blog: http://chandrimachoudhury.blogspot.in/

What is the easiest way to initialize a std::vector with hardcoded elements?

I build my own solution using va_arg. This solution is C++98 compliant.

#include <cstdarg>
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> initVector (int len, ...)
{
  std::vector<T> v;
  va_list vl;
  va_start(vl, len);
  for (int i = 0; i < len; ++i)
    v.push_back(va_arg(vl, T));
  va_end(vl);
  return v;
}

int main ()
{
  std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
  for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
    std::cout << *it << std::endl;
  return 0;
}

Demo

Can someone give an example of cosine similarity, in a very simple, graphical way?

For simplicity I am reducing the vector a and b:

Let :
    a : [1, 1, 0]
    b : [1, 0, 1]

Then cosine similarity (Theta):

 (Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5

then inverse of cos 0.5 is 60 degrees.

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Trim to remove white space

jQuery.trim() capital Q?

or $.trim()

Best way to get the max value in a Spark dataframe column

I used another solution (by @satprem rath) already present in this chain.

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

edit: to add more context.

While the above method printed the result, I faced issues when assigning the result to a variable to reuse later.

Hence, to get only the int value assigned to a variable:

from pyspark.sql.functions import max, min  

maxValueA = df.agg(max("A")).collect()[0][0]
maxValueB = df.agg(max("B")).collect()[0][0]

Capturing a form submit with jquery and .submit

Wrap the code in document ready and prevent the default submit action:

$(function() { //shorthand document.ready function
    $('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
        e.preventDefault();  //prevent form from submitting
        var data = $("#login_form :input").serializeArray();
        console.log(data); //use the console for debugging, F12 in Chrome, not alerts
    });
});

jQuery: print_r() display equivalent?

I've made a jQuery plugin for the equivalent of

<pre>
<?php echo print_r($data) ?>
</pre>

You can download it at https://github.com/tomasvanrijsse/jQuery.dump