Programs & Examples On #Font size

A CSS property which sets the size of a font, as specified in one of several different units.

How to set min-font-size in CSS

Use a media query. Example: This is something im using the original size is 1.0vw but when it hits 1000 the letter gets too small so I scale it up

@media(max-width:600px){
    body,input,textarea{
         font-size:2.0vw !important;
    }
}

This site I m working on is not responsive for >500px but you might need more. The pro,benefit for this solution is you keep font size scaling without having super mini letters and you can keep it js free.

UILabel font size?

**You can set font size by these properties **

timedisplayLabel= [[UILabel alloc]initWithFrame:CGRectMake(70, 194, 180, 60)];

[timedisplayLabel setTextAlignment:NSTextAlignmentLeft];

[timedisplayLabel setBackgroundColor:[UIColor clearColor]];

[timedisplayLabel setAdjustsFontSizeToFitWidth:YES];

[timedisplayLabel setTextColor:[UIColor blackColor]];

[timedisplayLabel setUserInteractionEnabled:NO];

[timedisplayLabel setFont:[UIFont fontWithName:@"digital-7" size:60]];

timedisplayLabel.layer.shadowColor =[[UIColor whiteColor ]CGColor ];

timedisplayLabel.layer.shadowOffset=(CGSizeMake(0, 0));

timedisplayLabel.layer.shadowOpacity=1;

timedisplayLabel.layer.shadowRadius=3.0;

timedisplayLabel.layer.masksToBounds=NO;

timedisplayLabel.shadowColor=[UIColor darkGrayColor];

timedisplayLabel.shadowOffset=CGSizeMake(0, 2);

Specifying Font and Size in HTML table

Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5. Consider this code for your case

<!DOCTYPE html>
<html>
<body>

<font size="2" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td>
    </tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td><td>master.mdf</td>
        <td>test_key_16</td><td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
    </tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td></tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td>
        <td>master.mdf</td>
        <td>test_key_16</td>
        <td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>

Keyboard shortcut to change font size in Eclipse?

In Eclipse Neon.3, as well as in the new Eclipse Photon (4.8.0), I can resize the font easily with Ctrl + Shift + + and -, without any plugin or special key binding.

At least in Editor Windows (this does not work in other Views like Console, Project Explorer etc).

CSS: 100% font size - 100% of what?

It's relative to default browser font-size unless you override it with a value in pt or px.

How can I change the font-size of a select option?

Add a CSS class to the <option> tag to style it: http://jsfiddle.net/Ahreu/

Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?

Change font size of UISegmentedControl

Extension for UISegmentedControl for setting Font Size.

extension UISegmentedControl {
    @available(iOS 8.2, *)
    func setFontSize(fontSize: CGFloat) {
            let normalTextAttributes: [NSObject : AnyObject]!
            if #available(iOS 9.0, *) {
                normalTextAttributes = [
                    NSFontAttributeName: UIFont.monospacedDigitSystemFontOfSize(fontSize, weight: UIFontWeightRegular)
                ]
            } else {
                normalTextAttributes = [
                    NSFontAttributeName: UIFont.systemFontOfSize(fontSize, weight: UIFontWeightRegular)
                ]
            }

        self.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
    }
 }

How to convert <font size="10"> to px?

According to The W3C:

This attribute sets the size of the font. Possible values:

  • An integer between 1 and 7. This sets the font to some fixed size, whose rendering depends on the user agent. Not all user agents may render all seven sizes.
  • A relative increase in font size. The value "+1" means one size larger. The value "-3" means three sizes smaller. All sizes belong to the scale of 1 to 7.

Hence, the conversion you're asking for is not possible. The browser is not required to use specific sizes with specific size attributes.

Also note that use of the font element is discouraged by W3 in favor of style sheets.

How to change Bootstrap's global default font size?

I just solved this type of problem. I was trying to increase

font-size to h4 size. I do not want to use h4 tag. I added my css after bootstrap.css it didn't work. The easiest way is this: On the HTML doc, type

<p class="h4">

You do not need to add anything to your css sheet. It works fine Question is suppose I want a size between h4 and h5? Answer why? Is this the only way to please your viewers? I will prefer this method to tampering with standard docs like bootstrap.

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

How to increase font size in the Xcode editor?

Update! - Behold Xcode 9 to the rescue! Now you can use cmd + to increase the fonts with Xcode 9. It took 5 Major releases for you to get it, Apple! But better late than never.

figured it out - however it was not very intuitive.

First some Pain Points

  1. When You try to change the font size directly using edit -> format -> font, nothing happens! - Not a good UX ... moreover why play dumb when you can tell user that they are using default or "System-owned" theme and they cannot change it? - Bad Design and more bad UX ... Why keep this option (Cmd t) alive, which by the way is most standard way to increase font size across most well behaved mac apps, if you do not want user to change the font this way?

  2. In Xcode preferences, when you try to change the font size by clicking on "fonts and colors", thats when XCode gives a pop-up saying what needs to be done. Also making a duplicate and then changing the fonts and colors is a lot of work rather than giving a button that says "Restore to Defaults" if Apple is so worried about the user messing up the default settings!

The solution is that - you need to duplicate the theme and then modify the copy you just made and apply that copy - phew!

Font scaling based on width of container

Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.

Just add the library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

And change font-size for correct by settings the coefficient of text:

$("#text_div").fitText(0.8);

You can set maximum and minimum values of text:

$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });

How to adjust text font size to fit textview

You can now do this without a third party library or a widget. It's built into TextView in API level 26. Add android:autoSizeTextType="uniform" to your TextView and set height to it. That's all. Use app:autoSizeTextType="uniform" for backward compatibility

https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform" />

You can also use TextViewCompat for compatibility.

Is there such a thing as min-font-size and max-font-size?

This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Responsive font size in CSS

I saw a great article from CSS-Tricks. It works just fine:

body {
    font-size: calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw -
    [minimum viewport width]) / ([maximum viewport width] - [minimum viewport width])));
}

For example:

body {
    font-size: calc(14px + (26 - 14) * ((100vw - 300px) / (1600 - 300)));
}

We can apply the same equation to the line-height property to make it change with the browser as well.

body {
    font-size: calc(14px + (26 - 14) * ((100vw - 300px) / (1600 - 300)));
    line-height: calc(1.3em + (1.5 - 1.2) * ((100vw - 300px)/(1600 - 300)));
}

font size in html code

just write the css attributes in a proper manner i.e:

font-size:35px;

How to change font size in Eclipse for Java text editors?

The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl + mousewheel zoom.

Under menu Help ? Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

Eclipse extension installation screen capture

Complete the installation and restart Eclipse. Then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl + - and Ctrl + = to zoom (although you may have to unbind those keys from Eclipse first).

Eclipse screen capture with the font size toolbar buttons circled

To get Ctrl + mouse wheel zooming, you can use AutoHotkey with the following script:

; Ctrl + mouse wheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
;
#IfWinActive ahk_class SWT_Window0
    ^WheelUp:: Send ^{=}
    ^WheelDown:: Send ^-
#IfWinActive

Set UIButton title UILabel font size programmatically

button.titleLabel.font = [UIFont systemFontOfSize:size];

should help

Auto-fit TextView for Android

After i tried Android official Autosizing TextView, i found if your Android version is prior to Android 8.0 (API level 26), you need use android.support.v7.widget.AppCompatTextView, and make sure your support library version is above 26.0.0. Example:

<android.support.v7.widget.AppCompatTextView
    android:layout_width="130dp"
    android:layout_height="32dp"
    android:maxLines="1"
    app:autoSizeMaxTextSize="22sp"
    app:autoSizeMinTextSize="12sp"
    app:autoSizeStepGranularity="2sp"
    app:autoSizeTextType="uniform" />

update:

According to @android-developer's reply, i check the AppCompatActivity source code, and found these two lines in onCreate

final AppCompatDelegate delegate = getDelegate(); delegate.installViewFactory();

and in AppCompatDelegateImpl's createView

    if (mAppCompatViewInflater == null) {
        mAppCompatViewInflater = new AppCompatViewInflater();
    }

it use AppCompatViewInflater inflater view, when AppCompatViewInflater createView it will use AppCompatTextView for "TextView".

public final View createView(){
    ...
    View view = null;
    switch (name) {
        case "TextView":
            view = new AppCompatTextView(context, attrs);
            break;
        case "ImageView":
            view = new AppCompatImageView(context, attrs);
            break;
        case "Button":
            view = new AppCompatButton(context, attrs);
            break;
    ...
}

In my project i don't use AppCompatActivity, so i need use <android.support.v7.widget.AppCompatTextView> in xml.

How to change the font size on a matplotlib plot

Based on the above stuff:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

Shortcut for changing font size

You'll probably find these shortcuts useful:

Ctrl+Shift+. to zoom in.

Ctrl+Shift+, to zoom out.

Those characters are period and comma, respectively.

How do I create a link using javascript?

Create links using JavaScript:

<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>

OR

<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>

OR

<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>

How to import set of icons into Android Studio project

For custom images you created yourself, you can do without the plugin:

Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.

It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

https://jsfiddle.net/mvora/mrLmkxmo/

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){
        this.name = 'XYZ';
    }

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';
    }


    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name = secondFileObject.name;
      var surname = secondFileObject.getSurname()
      alert(name);
      alert(surname );
    }

    firstFileFunction();

If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

Python equivalent of a given wget command

For Windows and Python 3.x, my two cents contribution about renaming the file on download :

  1. Install wget module : pip install wget
  2. Use wget :
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')

Truely working command line example :

python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"

Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.

Convert String to Date in MS Access Query

Use the DateValue() function to convert a string to date data type. That's the easiest way of doing this.

DateValue(String Date) 

How do I unset an element in an array in javascript?

Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.

If you know the key you should use splice i.e.

myArray.splice(key, 1);

For someone in Steven's position you can try something like this:

for (var key in myArray) {
    if (key == 'bar') {
        myArray.splice(key, 1);
    }
}

or

for (var key in myArray) {
    if (myArray[key] == 'bar') {
        myArray.splice(key, 1);
    }
}

How do I change the root directory of an Apache server?

I was working with LAMP and to change the document root folder, I have edited the default file which is there in the /etc/apache2/sites-available folder.

If you want to do the same, just edit as follows:

DocumentRoot /home/username/new_root_folder
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/username/new_root_folder>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

After this, if you type "localhost" in the browser, it will load the /home/username/new_root_folder content.

How to set an environment variable in a running docker container

There are generaly two options, because docker doesn't support this feature now:

  1. Create your own script, which will act like runner for your command. For example:

    #!/bin/bash
    export VAR1=VAL1
    export VAR2=VAL2
    your_cmd
    
  2. Run your command following way:

    docker exec -i CONTAINER_ID /bin/bash -c "export VAR1=VAL1 && export VAR2=VAL2 && your_cmd"
    

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

SQL Server loop - how do I loop through a set of records

By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;

SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')

OPEN @BusinessCursor;
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @msg = '{
              "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
              "Customer": {
                "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
              }
            }|'
        print @msg
    FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END

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_

SQL sum with condition

Try moving ValueDate:

select sum(CASE  
             WHEN ValueDate > @startMonthDate THEN cash 
              ELSE 0 
           END) 
 from Table a
where a.branch = p.branch 
  and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

Spring MVC: How to perform validation?

Put this bean in your configuration class.

 @Bean
  public Validator localValidatorFactoryBean() {
    return new LocalValidatorFactoryBean();
  }

and then You can use

 <T> BindingResult validate(T t) {
    DataBinder binder = new DataBinder(t);
    binder.setValidator(validator);
    binder.validate();
    return binder.getBindingResult();
}

for validating a bean manually. Then You will get all result in BindingResult and you can retrieve from there.

Bootstrap 3 Gutter Size

Add these helper classes to the stylesheet.less (you can use http://less2css.org/ to compile them to CSS )

.row.gutter-0 {
    margin-left: 0;
    margin-right: 0;
    [class*="col-"] {
        padding-left: 0;
        padding-right: 0;
    }
}

.row.gutter-10 {
    margin-left: -5px;
    margin-right: -5px;
    [class*="col-"] {
        padding-left: 5px;
        padding-right: 5px;
    }
}

.row.gutter-20 {
    margin-left: -10px;
    margin-right: -10px;
    [class*="col-"] {
        padding-left: 10px;
        padding-right: 10px;
    }
}

And here’s how you can use it in your HTML:

<div class="row gutter-0">
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
</div>

<div class="row gutter-10">
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
</div>

<div class="row gutter-20">
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
    <div class="col-sm-3 col-md-3 col-lg-3">

    </div>
</div>

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

Naming threads and thread-pools of ExecutorService

private class TaskThreadFactory implements ThreadFactory
{

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, "TASK_EXECUTION_THREAD");

        return t;
    }

}

Pass the ThreadFactory to an executorservice and you are good to go

How to show matplotlib plots in python

plt.plot(X,y) function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show() after plt.plot(X,y). So,

import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()

What is the difference between signed and unsigned int

In practice, there are two differences:

  1. printing (eg with cout in C++ or printf in C): unsigned integer bit representation is interpreted as a nonnegative integer by print functions.
  2. ordering: the ordering depends on signed or unsigned specifications.

this code can identify the integer using ordering criterion:

char a = 0;
a--;
if (0 < a)
    printf("unsigned");
else
    printf("signed");

char is considered signed in some compilers and unsigned in other compilers. The code above determines which one is considered in a compiler, using the ordering criterion. If a is unsigned, after a--, it will be greater than 0, but if it is signed it will be less than zero. But in both cases, the bit representation of a is the same. That is, in both cases a-- does the same change to the bit representation.

What is the difference between statically typed and dynamically typed languages?

http://en.wikipedia.org/wiki/Type_system

Static typing

A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. In static typing, types are associated with variables not values. Statically typed languages include Ada, C, C++, C#, JADE, Java, Fortran, Haskell, ML, Pascal, Perl (with respect to distinguishing scalars, arrays, hashes and subroutines) and Scala. Static typing is a limited form of program verification (see type safety): accordingly, it allows many type errors to be caught early in the development cycle. Static type checkers evaluate only the type information that can be determined at compile time, but are able to verify that the checked conditions hold for all possible executions of the program, which eliminates the need to repeat type checks every time the program is executed. Program execution may also be made more efficient (i.e. faster or taking reduced memory) by omitting runtime type checks and enabling other optimizations.

Because they evaluate type information during compilation, and therefore lack type information that is only available at run-time, static type checkers are conservative. They will reject some programs that may be well-behaved at run-time, but that cannot be statically determined to be well-typed. For example, even if an expression always evaluates to true at run-time, a program containing the code

if <complex test> then 42 else <type error>

will be rejected as ill-typed, because a static analysis cannot determine that the else branch won't be taken.[1] The conservative behaviour of static type checkers is advantageous when evaluates to false infrequently: A static type checker can detect type errors in rarely used code paths. Without static type checking, even code coverage tests with 100% code coverage may be unable to find such type errors. Code coverage tests may fail to detect such type errors because the combination of all places where values are created and all places where a certain value is used must be taken into account.

The most widely used statically typed languages are not formally type safe. They have "loopholes" in the programming language specification enabling programmers to write code that circumvents the verification performed by a static type checker and so address a wider range of problems. For example, Java and most C-style languages have type punning, and Haskell has such features as unsafePerformIO: such operations may be unsafe at runtime, in that they can cause unwanted behaviour due to incorrect typing of values when the program runs.

Dynamic typing

A programming language is said to be dynamically typed, or just 'dynamic', when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing, types are associated with values not variables. Dynamically typed languages include Groovy, JavaScript, Lisp, Lua, Objective-C, Perl (with respect to user-defined types but not built-in types), PHP, Prolog, Python, Ruby, Smalltalk and Tcl. Compared to static typing, dynamic typing can be more flexible (e.g. by allowing programs to generate types and functionality based on run-time data), though at the expense of fewer a priori guarantees. This is because a dynamically typed language accepts and attempts to execute some programs which may be ruled as invalid by a static type checker.

Dynamic typing may result in runtime type errors—that is, at runtime, a value may have an unexpected type, and an operation nonsensical for that type is applied. This operation may occur long after the place where the programming mistake was made—that is, the place where the wrong type of data passed into a place it should not have. This makes the bug difficult to locate.

Dynamically typed language systems, compared to their statically typed cousins, make fewer "compile-time" checks on the source code (but will check, for example, that the program is syntactically correct). Run-time checks can potentially be more sophisticated, since they can use dynamic information as well as any information that was present during compilation. On the other hand, runtime checks only assert that conditions hold in a particular execution of the program, and these checks are repeated for every execution of the program.

Development in dynamically typed languages is often supported by programming practices such as unit testing. Testing is a key practice in professional software development, and is particularly important in dynamically typed languages. In practice, the testing done to ensure correct program operation can detect a much wider range of errors than static type-checking, but conversely cannot search as comprehensively for the errors that both testing and static type checking are able to detect. Testing can be incorporated into the software build cycle, in which case it can be thought of as a "compile-time" check, in that the program user will not have to manually run such tests.

References

  1. Pierce, Benjamin (2002). Types and Programming Languages. MIT Press. ISBN 0-262-16209-1.

What is the difference between a field and a property?

In the background a property is compiled into methods. So a Name property is compiled into get_Name() and set_Name(string value). You can see this if you study the compiled code. So there is a (very) small performance overhead when using them. Normally you will always use a Property if you expose a field to the outside, and you will often use it internally if you need to do validation of the value.

What's the difference between "&nbsp;" and " "?

TLDR; In addition to the accepted answer; One is implicit and one is explicit.

When the HTML you've written or had generated by an application/library/framework is read by your browser it will do it's best to interpret what your HTML meant (which can vary from browser to browser). When you use the HTML entity codes, you are being more specific to the browser. You are explicitly telling it you wish to display a character to the user (and not that you are just spacing your HTML for easier readability for the developer for instance).

To be more concrete, if the output HTML were:

<html>
   <title>hello</title>
   <body>
       <p>
           Tell me and I will forget. Teach me and I
           may remember.  Involve me and I will learn.
       </p>
   </body>
</html>

The browser would only render one space between all of these words (even the ones that have been indented for better developer readability.

If, however, you put the same thing and only changed the <p> tag to:

<p>Hello&nbsp;&nbsp;&nbsp;There</p>

Then it would render the spaces, as you've instructed it more explicitly. There is some history of using these spaces for styling. This use has somewhat been diminished as CSS has matured. However, there are still valid uses for many of the HTML character entities: avoiding unexpectedly/unintentionally interpretation (e.g. if you wanted to display code). The w3 has a great page to show the other character codes.

word-wrap break-word does not work in this example

word-wrap property work's with display:inline-block:

display: inline-block;
word-wrap: break-word;
width: 100px;

Get a list of resources from classpath directory

I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem it looks like you can treat the objects in that ZIP as a "regular" file.

In the linked documentation above:

Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.

Once you have an instance of a zip file system, you can invoke the methods of the [java.nio.file.FileSystem][3] and [java.nio.file.Path][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.

The documentation for the jdk.zipfs module in [Java 11 states][5]:

The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [FileSystems.newFileSystem][6] if installed.

Here is a contrived example I did using your example resources. Note that a .zip is a .jar, but you could adapt your code to instead use classpath resources:

Setup

cd /tmp
mkdir -p x/y/z
touch x/y/z/{a,b,c}.html
echo 'hello world' > x/y/z/d
zip -r example.zip x

Java

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.stream.Collectors;

public class MkobitZipRead {

  public static void main(String[] args) throws IOException {
    final URI uri = URI.create("jar:file:/tmp/example.zip");
    try (
        final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
    ) {
      Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
      System.out.println("-----");
      final String manifest = Files.readAllLines(
          zipfs.getPath("x", "y", "z").resolve("d")
      ).stream().collect(Collectors.joining(System.lineSeparator()));
      System.out.println(manifest);
    }
  }

}

Output

Files in zip:/
Files in zip:/x/
Files in zip:/x/y/
Files in zip:/x/y/z/
Files in zip:/x/y/z/c.html
Files in zip:/x/y/z/b.html
Files in zip:/x/y/z/a.html
Files in zip:/x/y/z/d
-----
hello world

How to use Session attributes in Spring-mvc

Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:

@GetMapping
public String hello(HttpSession session) {
    session.setAttribute("name","value");
    return "hello";
}

p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.

What is the use of join() in Python threading?

Thanks for this thread -- it helped me a lot too.

I learned something about .join() today.

These threads run in parallel:

d.start()
t.start()
d.join()
t.join()

and these run sequentially (not what I wanted):

d.start()
d.join()
t.start()
t.join()

In particular, I was trying to clever and tidy:

class Kiki(threading.Thread):
    def __init__(self, time):
        super(Kiki, self).__init__()
        self.time = time
        self.start()
        self.join()

This works! But it runs sequentially. I can put the self.start() in __ init __, but not the self.join(). That has to be done after every thread has been started.

join() is what causes the main thread to wait for your thread to finish. Otherwise, your thread runs all by itself.

So one way to think of join() as a "hold" on the main thread -- it sort of de-threads your thread and executes sequentially in the main thread, before the main thread can continue. It assures that your thread is complete before the main thread moves forward. Note that this means it's ok if your thread is already finished before you call the join() -- the main thread is simply released immediately when join() is called.

In fact, it just now occurs to me that the main thread waits at d.join() until thread d finishes before it moves on to t.join().

In fact, to be very clear, consider this code:

import threading
import time

class Kiki(threading.Thread):
    def __init__(self, time):
        super(Kiki, self).__init__()
        self.time = time
        self.start()

    def run(self):
        print self.time, " seconds start!"
        for i in range(0,self.time):
            time.sleep(1)
            print "1 sec of ", self.time
        print self.time, " seconds finished!"


t1 = Kiki(3)
t2 = Kiki(2)
t3 = Kiki(1)
t1.join()
print "t1.join() finished"
t2.join()
print "t2.join() finished"
t3.join()
print "t3.join() finished"

It produces this output (note how the print statements are threaded into each other.)

$ python test_thread.py
32   seconds start! seconds start!1

 seconds start!
1 sec of  1
 1 sec of 1  seconds finished!
 21 sec of
3
1 sec of  3
1 sec of  2
2  seconds finished!
1 sec of  3
3  seconds finished!
t1.join() finished
t2.join() finished
t3.join() finished
$ 

The t1.join() is holding up the main thread. All three threads complete before the t1.join() finishes and the main thread moves on to execute the print then t2.join() then print then t3.join() then print.

Corrections welcome. I'm also new to threading.

(Note: in case you're interested, I'm writing code for a DrinkBot, and I need threading to run the ingredient pumps concurrently rather than sequentially -- less time to wait for each drink.)

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Remove all newlines from inside a string

As mentioned by @john, the most robust answer is:

string = "a\nb\rv"
new_string = " ".join(string.splitlines())

Is Visual Studio Community a 30 day trial?

Sign in and the 30 day trial will go away!

"And if you're already signed in, sign out then sign in again." –b1nary.atr0phy

printf %f with only 2 numbers after the decimal point?

as described in Formatter class, you need to declare precision. %.2f in your case.

Unix command to find lines common in two files

On limited version of Linux (like a QNAP (nas) I was working on):

  • comm did not exist
  • grep -f file1 file2 can cause some problems as said by @ChristopherSchultz and using grep -F -f file1 file2 was really slow (more than 5 minutes - not finished it - over 2-3 seconds with the method below on files over 20MB)

So here is what I did :

sort file1 > file1.sorted
sort file2 > file2.sorted

diff file1.sorted file2.sorted | grep "<" | sed 's/^< *//' > files.diff
diff file1.sorted files.diff | grep "<" | sed 's/^< *//' > files.same.sorted

If files.same.sorted shall have been in same order than the original ones, than add this line for same order than file1 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file1 > files.same

or, for same order than file2 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file2 > files.same

How do I detect IE 8 with jQuery?

Assuming...

  • ...that it's the crunky rendering engine of old versions of IE you're interested in detecting, to make a style look right in old IE (otherwise, use feature detection)
  • ...that you can't just add conditional comments to the HTML - e.g. for JS plugins that can be applied to any page (otherwise, just do the trick of conditional classes on <body> or <html>)

...then this is probably the best trick (based on this non-jQuery, slightly less flexible variant). It creates then tests for then removes an appropriate conditional comment.

(Conditional comments are ignored in IE10+ 'standards mode' - but that should be fine since IE10+ 'standards mode' doesn't have a crazy rendering engine!)

Drop in this function:

function isIE( version, comparison ){
    var $div = $('<div style="display:none;"/>');

    // Don't chain these, in IE8 chaining stops some versions of jQuery writing the conditional comment properly
    $div.appendTo($('body'));
    $div.html('<!--[if '+(comparison||'')+' IE '+(version||'')+']><a>&nbsp;</a><![endif]-->');

    var ieTest = $div.find('a').length;
    $div.remove();
    return ieTest;
}

Then use it like this:

if(isIE()){ /* runs in all versions of IE after 4 before standards-mode 10 */ }

if(isIE(8)){ /* runs in IE8 */ }

if(isIE(9)){ /* runs in IE9 */ }

if(isIE(8,'lte')){ /* runs in IE8 or below */ }

if(isIE(6,'lte')){ /* if you need this, I pity you... */ }

I'd also suggest caching the results of this function so you don't have to repeat it. For example, you could use the string (comparison||'')+' IE '+(version||'') as a key to store and check for the result of this test in an object somewhere.

Bootstrap col-md-offset-* not working

Changing col-md-offset-* to offset-md-* worked for me

Rollback a Git merge

Just reset the merge commit with git reset --hard HEAD^.

If you use --no-ff git always creates a merge, even if you did not commit anything in between. Without --no-ff git will just do a fast forward, meaning your branches HEAD will be set to HEAD of the merged branch. To resolve this find the commit-id you want to revert to and git reset --hard $COMMITID.

Spring JPA @Query with LIKE

@Query("select u from user u where u.username LIKE :username")
List<User> findUserByUsernameLike(@Param("username") String username);

How to open CSV file in R when R says "no such file or directory"?

Here is one way to do it. It uses the ability of R to construct file paths based on the platform and hence will work on both Mac OS and Windows. Moreover, you don't need to convert your xls file to csv, as there are many R packages that will help you read xls directly (e.g. gdata package).

# get user's home directory
home = setwd(Sys.getenv("HOME"));

# construct path to file
fpath = file.path(home, "Desktop", "RTrial.xls");

# load gdata library to read xls files
library(gdata);

# read xls file
Rtrial = read.xls(fpath);

Let me know if this works.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Mocking python function based on input arguments

Although side_effect can achieve the goal, it is not so convenient to setup side_effect function for each test case.

I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:

from nextmock import Mock

m = Mock()

m.with_args(1, 2, 3).returns(123)

assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123

It also supports argument matcher:

from nextmock import Arg, Mock

m = Mock()

m.with_args(1, 2, Arg.Any).returns(123)

assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123

Hope this package could make testing more pleasant. Feel free to give any feedback.

How to move (and overwrite) all files from one directory to another?

In linux shell, many commands accept multiple parameters and therefore could be used with wild cards. So, for example if you want to move all files from folder A to folder B, you write:

mv A/* B

If you want to move all files with a certain "look" to it, you could do like this:

mv A/*.txt B

Which copies all files that are blablabla.txt to folder B

Star (*) can substitute any number of characters or letters while ? can substitute one. For example if you have many files in the shape file_number.ext and you want to move only the ones that have two digit numbers, you could use a command like this:

mv A/file_??.ext B

Or more complicated examples:

mv A/fi*_??.e* B

For files that look like fi<-something->_<-two characters->.e<-something->

Unlike many commands in shell that require -R to (for example) copy or remove subfolders, mv does that itself.

Remember that mv overwrites without asking (unless the files being overwritten are read only or you don't have permission) so make sure you don't lose anything in the process.

For your future information, if you have subfolders that you want to copy, you could use the -R option, saying you want to do the command recursively. So it would look something like this:

cp A/* B -R

By the way, all I said works with rm (remove, delete) and cp (copy) too and beware, because once you delete, there is no turning back! Avoid commands like rm * -R unless you are sure what you are doing.

How to get last month/year in java?

You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).


Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id)
);

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),
    KEY(selector)
);

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)
]);

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')
]);

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    }
    // Remove the token from the DB regardless of success or failure.
}

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

How to get Android GPS location

Here's your problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

Latitude and Longitude are double-values, because they represent the location in degrees.

By casting them to int, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I was having the same problem in Linux Ubuntu 18. After the update from Ubuntu 17.10, every git command would show that message.

The way to solve it is to make sure that you have the correct permission on the id_rsa and id_rsa.pub.

Check the current chmod number by using stat --format '%a' <file>. It should be 600 for id_rsa and 644 for id_rsa.pub.

To change the permission on the files use

chmod 600 id_rsa
chmod 644 id_rsa.pub

That solved my issue with the update.

How to get the fields in an Object via reflection?

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

Overriding interface property type defined in Typescript d.ts file

It's funny I spend the day investigating possibility to solve the same case. I found that it not possible doing this way:

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

Cause A module may not know about all available types in your application. And it's quite boring port everything from everywhere and doing code like this.

export interface A {
    x: A | B | C | D ... Million Types Later
}

You have to define type later to have autocomplete works well.


So you can cheat a bit:

// a.ts - module
export interface A {
    x: string;
}

Left the some type by default, that allow autocomplete works, when overrides not required.

Then

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

Disable stupid exception here using @ts-ignore flag, saying us the we doing something wrong. And funny thing everything works as expected.

In my case I'm reducing the scope vision of type x, its allow me doing code more stricted. For example you have list of 100 properties, and you reduce it to 10, to avoid stupid situations

How to merge two sorted arrays into a sorted array?

This problem is related to the mergesort algorithm, in which two sorted sub-arrays are combined into a single sorted sub-array. The CLRS book gives an example of the algorithm and cleans up the need for checking if the end has been reached by adding a sentinel value (something that compares and "greater than any other value") to the end of each array.

I wrote this in Python, but it should translate nicely to Java too:

def func(a, b):
    class sentinel(object):
        def __lt__(*_):
            return False

    ax, bx, c = a[:] + [sentinel()], b[:] + [sentinel()], []
    i, j = 0, 0

    for k in range(len(a) + len(b)):
        if ax[i] < bx[j]:
            c.append(ax[i])
            i += 1
        else:
            c.append(bx[j])
            j += 1

    return c

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

How to find the port for MS SQL Server 2008?

This may also be done via a port scan, which is the only possible method if you don't have admin access to a remote server.

Using Nmap (http://nmap.org/zenmap/) to do an "Intense TCP scan" will give you results like this for all instances on the server:

[10.0.0.1\DATABASE]    
Instance name: DATABASE
Version: Microsoft SQL Server 2008 R2 RTM    
Product: Microsoft SQL Server 2008 R2    
Service pack level: RTM    
TCP port: 49843    
Named pipe: \\10.0.0.1\pipe\MSSQL$DATABASE\sql\query

Important note: To test with query analyzer or MS SQL Server Management Studio you must form your server name and port differently than you would normally connect to a port, over HTTP for instance, using a comma instead of a colon.

  • Management Studio Server Name: 10.0.0.1,49843
  • Connection String: Data Source=10.0.0.1,49843

however

  • JDBC Connection String: jdbc:microsoft:sqlserver://10.0.0.1:49843;DatabaseName=DATABASE

How to copy files from host to Docker container?

You can just trace the IP address of your local machine using

ifconfig

Then just enter into your Docker container and type

scp user_name@ip_address:/path_to_the_file destination

In any case if you don't have an SSH client and server installed, just install it using:

sudo apt-get install openssh-server

Accessing inventory host variable in Ansible playbook

[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:

{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }}

Dictionary returning a default value if the key does not exist

I created a DefaultableDictionary to do exactly what you are asking for!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace DefaultableDictionary {
    public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
        private readonly IDictionary<TKey, TValue> dictionary;
        private readonly TValue defaultValue;

        public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
            this.dictionary = dictionary;
            this.defaultValue = defaultValue;
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
            return dictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item) {
            dictionary.Add(item);
        }

        public void Clear() {
            dictionary.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item) {
            return dictionary.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
            dictionary.CopyTo(array, arrayIndex);
        }

        public bool Remove(KeyValuePair<TKey, TValue> item) {
            return dictionary.Remove(item);
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool IsReadOnly {
            get { return dictionary.IsReadOnly; }
        }

        public bool ContainsKey(TKey key) {
            return dictionary.ContainsKey(key);
        }

        public void Add(TKey key, TValue value) {
            dictionary.Add(key, value);
        }

        public bool Remove(TKey key) {
            return dictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
            if (!dictionary.TryGetValue(key, out value)) {
                value = defaultValue;
            }

            return true;
        }

        public TValue this[TKey key] {
            get
            {
                try
                {
                    return dictionary[key];
                } catch (KeyNotFoundException) {
                    return defaultValue;
                }
            }

            set { dictionary[key] = value; }
        }

        public ICollection<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public ICollection<TValue> Values {
            get
            {
                var values = new List<TValue>(dictionary.Values) {
                    defaultValue
                };
                return values;
            }
        }
    }

    public static class DefaultableDictionaryExtensions {
        public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
            return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
        }
    }
}

This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.

The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.

Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);

Blog post on the usage as well.

Insert multiple rows into single column

Another way to do this is with union:

INSERT INTO Data ( Col1 ) 
select 'hello'
union 
select 'world'

PHP "php://input" vs $_POST

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3

But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).

The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

Facebook Like-Button - hide count?

Adding the following to your css should hide the text element for users and keep FB Happy

.connect_widget_not_connected_text
{
    display:none !important; /*in your stylesheets to hide the counter!*/
}

-- Update

Try using a different approach.

http://www.facebook.com/share/

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

If this issue occurs, kindly check web.config in below section

Below section gives the version of particular dll used

after checking this section in web.config, open solution explorer and select reference from the project tree as shown . Solution Explorer->Reference

After expanding reference, find the dll which caused the error. Right click on the dll reference and check for version like shown in the image above.

If both config dll version and referenced dll is different you would get this exception. Make sure both are of same version which would help.

Read lines from a file into a Bash array

#!/bin/bash
IFS=$'\n' read  -d'' -r -a inlines  < testinput
IFS=$'\n' read  -d'' -r -a  outlines < testoutput
counter=0
cat testinput | while read line; 
do
    echo "$((${inlines[$counter]}-${outlines[$counter]}))"
    counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline; 
do
    echo value is: $((${a[$counter]}-${b[$counter]}))
    counter=$(($counter+1))
done

Getting value from appsettings.json in .net core

In my case it was simple as using the Bind() method on the Configuration object. And then add the object as singleton in the DI.

var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);

The Instruction object can be as complex as you want.

{  
 "InstructionSettings": {
    "Header": "uat_TEST",
    "SVSCode": "FICA",
    "CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
    "Username": "s_integrat",
    "Password": "X@nkmail6",
    "Defaults": {
    "Language": "ENG",
    "ContactDetails":{
       "StreetNumber": "9",
       "StreetName": "Nano Drive",
       "City": "Johannesburg",
       "Suburb": "Sandton",
       "Province": "Gauteng",
       "PostCode": "2196",
       "Email": "[email protected]",
       "CellNumber": "0833 468 378",
       "HomeNumber": "0833 468 378",
      }
      "CountryOfBirth": "710"
    }
  }

What's the algorithm to calculate aspect ratio?

I think this does what you are asking for:

webdeveloper.com - decimal to fraction

Width/height gets you a decimal, converted to a fraction with ":" in place of '/' gives you a "ratio".

Python csv string to array

The official doc for csv.reader() https://docs.python.org/2/library/csv.html is very helpful, which says

file objects and list objects are both suitable

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

Viewing full output of PS command

If you are specifying the output format manually you also need to make sure the args option is last in the list of output fields, otherwise it will be truncated.

ps -A -o args,pid,lstart gives

/usr/lib/postgresql/9.5/bin 29900 Thu May 11 10:41:59 2017
postgres: checkpointer proc 29902 Thu May 11 10:41:59 2017
postgres: writer process    29903 Thu May 11 10:41:59 2017
postgres: wal writer proces 29904 Thu May 11 10:41:59 2017
postgres: autovacuum launch 29905 Thu May 11 10:41:59 2017
postgres: stats collector p 29906 Thu May 11 10:41:59 2017
[kworker/2:0]               30188 Fri May 12 09:20:17 2017
/usr/lib/upower/upowerd     30651 Mon May  8 09:57:58 2017
/usr/sbin/apache2 -k start  31288 Fri May 12 07:35:01 2017
/usr/sbin/apache2 -k start  31289 Fri May 12 07:35:01 2017
/sbin/rpc.statd --no-notify 31635 Mon May  8 09:49:12 2017
/sbin/rpcbind -f -w         31637 Mon May  8 09:49:12 2017
[nfsiod]                    31645 Mon May  8 09:49:12 2017
[kworker/1:0]               31801 Fri May 12 09:49:15 2017
[kworker/u16:0]             32658 Fri May 12 11:00:51 2017

but ps -A -o pid,lstart,args gets you the full command line:

29900 Thu May 11 10:41:59 2017 /usr/lib/postgresql/9.5/bin/postgres -D /tmp/4493-d849-dc76-9215 -p 38103
29902 Thu May 11 10:41:59 2017 postgres: checkpointer process   
29903 Thu May 11 10:41:59 2017 postgres: writer process   
29904 Thu May 11 10:41:59 2017 postgres: wal writer process   
29905 Thu May 11 10:41:59 2017 postgres: autovacuum launcher process   
29906 Thu May 11 10:41:59 2017 postgres: stats collector process   
30188 Fri May 12 09:20:17 2017 [kworker/2:0]
30651 Mon May  8 09:57:58 2017 /usr/lib/upower/upowerd
31288 Fri May 12 07:35:01 2017 /usr/sbin/apache2 -k start
31289 Fri May 12 07:35:01 2017 /usr/sbin/apache2 -k start
31635 Mon May  8 09:49:12 2017 /sbin/rpc.statd --no-notify
31637 Mon May  8 09:49:12 2017 /sbin/rpcbind -f -w
31645 Mon May  8 09:49:12 2017 [nfsiod]
31801 Fri May 12 09:49:15 2017 [kworker/1:0]
32658 Fri May 12 11:00:51 2017 [kworker/u16:0]

Count the number of all words in a string

require(stringr)

Define a very simple function

str_words <- function(sentence) {

  str_count(sentence, " ") + 1

}

Check

str_words(This is a sentence with six words)

swift How to remove optional String Character

In swift3 you can easily remove optional

if let value = optionalvariable{
 //in value you will get non optional value
}

Can Flask have optional URL parameters?

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.

from flask import Flask

from flask_optional_routes import OptionalRoutes


app = Flask(__name__)
optional = OptionalRoutes(app)

@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

View tabular file such as CSV from command line

You can also use this:

column -s, -t < somefile.csv | less -#2 -N -S

column is a standard unix program that is very convenient -- it finds the appropriate width of each column, and displays the text as a nicely formatted table.

Note: whenever you have empty fields, you need to put some kind of placeholder in it, otherwise the column gets merged with following columns. The following example demonstrates how to use sed to insert a placeholder:

$ cat data.csv
1,2,3,4,5
1,,,,5
$ sed 's/,,/, ,/g;s/,,/, ,/g' data.csv | column -s, -t
1  2  3  4  5
1           5
$ cat data.csv
1,2,3,4,5
1,,,,5
$ column -s, -t < data.csv
1  2  3  4  5
1  5
$ sed 's/,,/, ,/g;s/,,/, ,/g' data.csv | column -s, -t
1  2  3  4  5
1           5

Note that the substitution of ,, for , , is done twice. If you do it only once, 1,,,4 will become 1, ,,4 since the second comma is matched already.

Enum Naming Convention - Plural

Microsoft recommends using singular for Enums unless the Enum represents bit fields (use the FlagsAttribute as well). See Enumeration Type Naming Conventions (a subset of Microsoft's Naming Guidelines).

To respond to your clarification, I see nothing wrong with either of the following:

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass { 
    public OrderStatus OrderStatus { get; set; }
}

or

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass {
    public OrderStatus Status { get; set; }
}

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How to pass values between Fragments

Communicating between fragments is fairly complicated (I find the listeners concept a little challenging to implement).

It is common to use a 'Event Bus" to abstract these communications. This is a 3rd party library that takes care of this communication for you.

'Otto' is one that is used often to do this, and might be worth looking into: http://square.github.io/otto/

Is there a method that calculates a factorial in Java?

i believe this would be the fastest way, by a lookup table:

private static final long[] FACTORIAL_TABLE = initFactorialTable();
private static long[] initFactorialTable() {
    final long[] factorialTable = new long[21];
    factorialTable[0] = 1;
    for (int i=1; i<factorialTable.length; i++)
        factorialTable[i] = factorialTable[i-1] * i;
    return factorialTable;
}
/**
 * Actually, even for {@code long}, it works only until 20 inclusively.
 */
public static long factorial(final int n) {
    if ((n < 0) || (n > 20))
        throw new OutOfRangeException("n", 0, 20);
    return FACTORIAL_TABLE[n];
}

For the native type long (8 bytes), it can only hold up to 20!

20! = 2432902008176640000(10) = 0x 21C3 677C 82B4 0000

Obviously, 21! will cause overflow.

Therefore, for native type long, only a maximum of 20! is allowed, meaningful, and correct.

What is a Maven artifact?

An artifact is a file, usually a JAR, that gets deployed to a Maven repository.

A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.

Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact.

A project's dependencies are specified as artifacts.

How to vertically align into the center of the content of a div with defined width/height?

This could also be done using display: flex with only a few lines of code. Here is an example:

.container {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

Live Demo

How to set app icon for Electron / Atom Shell App

electron-packager


Setting the icon property when creating the BrowserWindow only has an effect on Windows and Linux platforms. you have to package the .icns for max

To set the icon on OS X using electron-packager, set the icon using the --icon switch.

It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.

electron-builder


As a most recent solution, I found an alternative of using --icon switch. Here is what you can do.

  1. Create a directory named build in your project directory and put the .icns the icon in the directory as named icon.icns.
  2. run builder by executing command electron-builder --dir.

You will find your application icon will be automatically picked up from that directory location and used for an application while packaging.

Note: The given answer is for recent version of electron-builder and tested with electron-builder v21.2.0

npm install private github repositories by dependency in package.json

For those of you who came here for public directories, from the npm docs: https://docs.npmjs.com/files/package.json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls can be of the form:

git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish

The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master.

VBA equivalent to Excel's mod function

But if you just want to tell the difference between an odd iteration and an even iteration, this works just fine:

If i Mod 2 > 0 then 'this is an odd 
   'Do Something
Else 'it is even
   'Do Something Else
End If

How to test if a string is JSON or not?

Warning: For methods relying on JSON.parse - Arrays and quote surrounded strings will pass too (ie. console.log(JSON.parse('[3]'), JSON.parse('"\uD800"')))

To avoid all non-object JSON primitives (boolean, null, array, number, string), I suggest using the following:

/* Validate a possible object ie. o = { "a": 2 } */
const isJSONObject = (o) => 
  !!o && (typeof o === 'object') && !Array.isArray(o) && 
  (() => { try { return Boolean(JSON.stringify(o)); } catch { return false } })()

/* Validate a possible JSON object represented as string ie. s = '{ "a": 3 }' */
function isJSONObjectString(s) {
    try {
        const o = JSON.parse(s);
        return !!o && (typeof o === 'object') && !Array.isArray(o)
    } catch {
        return false
    }
}

Code Explanation

  • !!o - Not falsy (excludes null, which registers as typeof 'object')
  • (typeof o === 'object') - Excludes boolean, number, and string
  • !Array.isArray(o) - Exclude arrays (which register as typeof 'object')
  • try ... JSON.stringify / JSON.parse - Asks JavaScript engine to determine if valid JSON

Why not use the hasJsonStructure() answer?

Relying on toString() is not a good idea. This is because different JavaScript Engines may return a different string representation. In general, methods which rely on this may fail in different environments or may be subject to fail later should the engine ever change the string result

Why is catching an exception not a hack?

It was brought up that catching an exception to determine something's validity is never the right way to go. This is generally good advice, but not always. In this case, exception catching is likely is the best route because it relies on the JavaScript engine's implementation of validating JSON data.

Relying on the JS engine offers the following advantages:

  1. More thorough and continually up-to-date as JSON spec changes
  2. Likely to run faster (as it's lower level code)

When given the opportunity to lean on the JavaScript engine, I'd suggest doing it. Particularly so in this case. Although it may feel hacky to catch an exception, you're really just handling two possible return states from an external method.

How do I use CREATE OR REPLACE?

Does not work with Tables, only functions etc.

Here is a site with some examples.

Why is this HTTP request not working on AWS Lambda?

Yes, there's in fact many reasons why you can access AWS Lambda like and HTTP Endpoint.

The architecture of AWS Lambda

It's a microservice. Running inside EC2 with Amazon Linux AMI (Version 3.14.26–24.46.amzn1.x86_64) and runs with Node.js. The memory can be beetwen 128mb and 1gb. When the data source triggers the event, the details are passed to a Lambda function as parameter's.

What happen?

AWS Lambda run's inside a container, and the code is directly uploaded to this container with packages or modules. For example, we NEVER can do SSH for the linux machine running your lambda function. The only things that we can monitor are the logs, with CloudWatchLogs and the exception that came from the runtime.

AWS take care of launch and terminate the containers for us, and just run the code. So, even that you use require('http'), it's not going to work, because the place where this code runs, wasn't made for this.

Creating a selector from a method name with parameters

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);

-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here

-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

Windows 7 - Add Path

Try this in cmd:

cd address_of_sumatrapdf.exe_file && sumatrapdf.exe

Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.

MySQL integer field is returned as string in PHP

You can do this with...

  1. mysql_fetch_field()
  2. mysqli_result::fetch_field_direct or
  3. PDOStatement::getColumnMeta()

...depending on the extension you want to use. The first is not recommended because the mysql extension is deprecated. The third is still experimental.

The comments at these hyperlinks do a good job of explaining how to set your type from a plain old string to its original type in the database.

Some frameworks also abstract this (CodeIgniter provides $this->db->field_data()).

You could also do guesswork--like looping through your resulting rows and using is_numeric() on each. Something like:

foreach($result as &$row){
 foreach($row as &$value){
  if(is_numeric($value)){
   $value = (int) $value;
  }       
 }       
}

This would turn anything that looks like a number into one...definitely not perfect.

Using textures in THREE.js

Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...

  • CoffeeScript

    $(document).ready ->
    
        material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
    
        sphere   = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
    
        $(window).load ->
            renderer.render scene, camera
    
  • JavaScript

    $(document).ready(function() {
    
        material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
    
        sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
    
        $(window).load(function() {
            renderer.render(scene, camera);
        });
    });
    

Thanks...

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

Difference between long and int data types

On platforms where they both have the same size the answer is nothing. They both represent signed 4 byte values.

However you cannot depend on this being true. The size of long and int are not definitively defined by the standard. It's possible for compilers to give the types different sizes and hence break this assumption.

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

How to change the size of the radio button using CSS?

This css seems to do the trick:

input[type=radio] {
    border: 0px;
    width: 100%;
    height: 2em;
}

Setting the border to 0 seems to allow the user to change the size of the button and have the browser render it in that size for eg. the above height: 2em will render the button at twice the line height. This also works for checkboxes (input[type=checkbox]). Some browsers render better than others.

From a windows box it works in IE8+, FF21+, Chrome29+.

Java: Get month Integer from Date

Joda-Time

Alternatively, with the Joda-Time DateTime class.

//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))

…or…

int month = dateTime.getMonthOfYear();

How to limit google autocomplete results to City and Country only

I found a solution for myself

var acService = new google.maps.places.AutocompleteService();
var autocompleteItems = [];

acService.getPlacePredictions({
    types: ['(regions)']
}, function(predictions) {
    predictions.forEach(function(prediction) {
        if (prediction.types.some(function(x) {
                return x === "country" || x === "administrative_area1" || x === "locality";
            })) {
            if (prediction.terms.length < 3) {
                autocompleteItems.push(prediction);
            }
        }
    });
});

this solution only show city and country..

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

Sorting options elements alphabetically using jQuery

The jquery.selectboxes.js plugin has a sort method. You can implement the plugin, or dive into the code to see a way to sort the options.

How to autowire RestTemplate using annotations

You can add the method below to your class for providing a default implementation of RestTemplate:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java?

No.

Would this be the culprit to the funky characters?

Quite likely.

Is there an exponent operator in C#?

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.


You asked:

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

Can jQuery check whether input content has changed?

Yes, compare it to the value it was before it changed.

var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
    var currentValue = $(this).val();
    if(currentValue != previousValue) {
         previousValue = currentValue;
         alert("Value changed!");
    }
});

Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed.

nodemon command is not recognized in terminal for node js server

I was facing the same issue. I had installed nodemon as a dev-dependency and when I tried to start the server it gave the message that

nodemon is not recognized as internal or external command, operable program or batch file

Then I installed it globally and tried to start the server and it worked!

npm install -g nodemon

Determine if a String is an Integer in Java

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

Tomcat starts but home page cannot open with url http://localhost:8080

For windows user, type netstat -anin command prompt to see ports that are listening, this may come handy.

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

What's the scope of a variable initialized in an if statement?

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.

Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined.

App crashing when trying to use RecyclerView on android 5.0

using fragment

writing code in onCreateView()

RecyclerView recyVideo = view.findViewById(R.id.recyVideoFag);

using activity

writing code in onCreate() RecyclerView recyVideo = findViewById(R.id.recyVideoFag);

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

Get the value of checked checkbox?

In my project, I usually use this snippets:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.

PHP MySQL Google Chart JSON - Complete Example

You can do this more easy way. And 100% works that you want

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";  //your database password
    $dbname = "demo";  //your database name

    $con = new mysqli($servername, $username, $password, $dbname);

    if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
    }
    else
    {
        //echo ("Connect Successfully");
    }
    $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
    $aresult = $con->query($query);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Massive Electronics</title>
    <script type="text/javascript" src="loder.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});

        google.charts.setOnLoadCallback(drawChart);
        function drawChart(){
            var data = new google.visualization.DataTable();
            var data = google.visualization.arrayToDataTable([
                ['Date_time','Tempout'],
                <?php
                    while($row = mysqli_fetch_assoc($aresult)){
                        echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
                    }
                ?>
               ]);

            var options = {
                title: 'Date_time Vs Room Out Temp',
                curveType: 'function',
                legend: { position: 'bottom' }
            };

            var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
            chart.draw(data, options);
        }

    </script>
</head>
<body>
     <div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>

loder.js link here loder.js

Get JSON data from external URL and display it in a div as plain text

If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

And you would call it like this:

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
  }
});

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

Laravel Advanced Wheres how to pass variable into function?

If you are using Laravel eloquent you may try this as well.

$result = self::select('*')
                    ->with('user')
                    ->where('subscriptionPlan', function($query) use($activated){
                        $query->where('activated', '=', $roleId);
                    })
                    ->get();

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

How do I close a single buffer (out of many) in Vim?

[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]

Maybe switch to using tabs?

vim -p a/*.php opens the same files in tabs

gt and gT switch tabs back and forth

:q closes only the current tab

:qa closes everything and exits

:tabo closes everything but the current tab

PHP - concatenate or directly insert variables in string

It only matter of taste.
Use whatever you wish.

Most of time I am using second one but it depends.

Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

Save string to the NSUserDefaults?

[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

Error checking for NULL in VBScript

I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

Jackson serialization: ignore empty values (or null)

Or you can use GSON [https://code.google.com/p/google-gson/], where these null fields will be automatically removed.

SampleDTO.java

public class SampleDTO {

    String username;
    String email;
    String password;
    String birthday;
    String coinsPackage;
    String coins;
    String transactionId;
    boolean isLoggedIn;

    // getters/setters
}

Test.java

import com.google.gson.Gson;

public class Test {

    public static void main(String[] args) {
        SampleDTO objSampleDTO = new SampleDTO();
        Gson objGson = new Gson();
        System.out.println(objGson.toJson(objSampleDTO));
    }
}

OUTPUT:

{"isLoggedIn":false}

I used gson-2.2.4

Why am I seeing "TypeError: string indices must be integers"?

This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.

PUT vs. POST in REST

I'd like to add my "pragmatic" advice. Use PUT when you know the "id" by which the object you are saving can be retrieved. Using PUT won't work too well if you need, say, a database generated id to be returned for you to do future lookups or updates.

So: To save an existing user, or one where the client generates the id and it's been verified that the id is unique:

PUT /user/12345 HTTP/1.1  <-- create the user providing the id 12345
Host: mydomain.com

GET /user/12345 HTTP/1.1  <-- return that user
Host: mydomain.com

Otherwise, use POST to initially create the object, and PUT to update the object:

POST /user HTTP/1.1   <--- create the user, server returns 12345
Host: mydomain.com

PUT /user/12345 HTTP/1.1  <--- update the user
Host: mydomain.com

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I dont like exceptions I registered the OnSaveChanges and have this

var validationErrors = model.GetValidationErrors();

var h = validationErrors.SelectMany(x => x.ValidationErrors
                                          .Select(f => "Entity: " 
                                                      +(x.Entry.Entity) 
                                                      + " : " + f.PropertyName 
                                                      + "->" + f.ErrorMessage));

How to pass a value from one jsp to another jsp page?

Use below code for passing string from one jsp to another jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

Get exit code of a background process

I would change your approach slightly. Rather than checking every few seconds if the command is still alive and reporting a message, have another process that reports every few seconds that the command is still running and then kill that process when the command finishes. For example:

#!/bin/sh

cmd() { sleep 5; exit 24; }

cmd &   # Run the long running process
pid=$!  # Record the pid

# Spawn a process that coninually reports that the command is still running
while echo "$(date): $pid is still running"; do sleep 1; done &
echoer=$!

# Set a trap to kill the reporter when the process finishes
trap 'kill $echoer' 0

# Wait for the process to finish
if wait $pid; then
    echo "cmd succeeded"
else
    echo "cmd FAILED!! (returned $?)"
fi

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.

How can I check the system version of Android?

Build.VERSION.RELEASE;

That will give you the actual numbers of your version; aka 2.3.3 or 2.2. The problem with using Build.VERSION.SDK_INT is if you have a rooted phone or custom rom, you could have a none standard OS (aka my android is running 2.3.5) and that will return a null when using Build.VERSION.SDK_INT so Build.VERSION.RELEASE will work no matter what!

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

Create a folder and sub folder in Excel VBA

There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function

Likewise,

Function FileExists(FileName As String) As Boolean
     If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction

ImportError: No module named requests

If you are using Ubuntu, there is need to install requests

run this command:

pip install requests

if you face permission denied error, use sudo before command:

sudo pip install requests

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

Applying a single font to an entire website with CSS

As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:

body, input, textarea {
    font-family: Algerian;
}

body {
    font-family: Algerian !important;
}

There'll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you'd better use a monospace font there.

Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it'll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.

(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don't do that :) This font is terrible except for your children birthdays where it's welcome.

Modifying Objects within stream in Java8 while iterating

Yes, you can modify or update the values of objects in the list in your case likewise:

users.stream().forEach(u -> u.setProperty("some_value"))

However, the above statement will make updates on the source objects. Which may not be acceptable in most cases.

Luckily, we do have another way like:

List<Users> updatedUsers = users.stream().map(u -> u.setProperty("some_value")).collect(Collectors.toList());

Which returns an updated list back, without hampering the old one.

Want to show/hide div based on dropdown box selection

Wrap the code within $(document).ready(function(){...........}); handler , also remove the ; after if

$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
        $("#business").show();
      }
      else
      {
        $("#business").hide();
      }
    });
});

Fiddle Demo

How to make Sonar ignore some classes for codeCoverage metric?

I am able to achieve the necessary code coverage exclusions by updating jacoco-maven-plugin configuration in pom.xml

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.6</version>
                <executions>
                    <execution>
                        <id>pre-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <propertyName>jacocoArgLine</propertyName>
                            <destFile>${project.test.result.directory}/jacoco/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.test.result.directory}/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.test.result.directory}/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <excludes>
                        <exclude>**/GlobalExceptionHandler*.*</exclude>
                        <exclude>**/ErrorResponse*.*</exclude>
                    </excludes>
                </configuration>
            </plugin>

this configuration excludes the GlobalExceptionHandler.java and ErrorResponse.java in the jacoco coverage.

And the following two lines does the same for sonar coverage .

    <sonar.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.</sonar.exclusions>
        <sonar.coverage.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.* </sonar.coverage.exclusions>

What are OLTP and OLAP. What is the difference between them?

Here you will find a better solution OLTP vs. OLAP

  • OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.

  • OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.

How to configure Git post commit hook

I want to add to the answers above that it becomes a little more difficult if Jenkins authorization is enabled.

After enabling it I got an error message that anonymous user needs read permission.

I saw two possible solutions:

1: Changing my hook to:

curl --user name:passwd -s http://domain?token=whatevertokenuhave

2: setting project based authorization.

The former solutions has the disadvantage that I had to expose my passwd in the hook file. Unacceptable in my case.

The second works for me. In the global auth settings I had to enable Overall>Read for Anonymous user. In the project I wanted to trigger I had to enable Job>Build and Job>Read for Anonymous.

This is still not a perfect solution because now you can see the project in Jenkins without login. There might be an even better solution using the former approach with http login but I haven't figured it out.

Extract string between two strings in java

Jlordo approach covers specific situation. If you try to build an abstract method out of it, you can face a difficulty to check if 'textFrom' is before 'textTo'. Otherwise method can return a match for some other occurance of 'textFrom' in text.

Here is a ready-to-go abstract method that covers this disadvantage:

  /**
   * Get text between two strings. Passed limiting strings are not 
   * included into result.
   *
   * @param text     Text to search in.
   * @param textFrom Text to start cutting from (exclusive).
   * @param textTo   Text to stop cuutting at (exclusive).
   */
  public static String getBetweenStrings(
    String text,
    String textFrom,
    String textTo) {

    String result = "";

    // Cut the beginning of the text to not occasionally meet a      
    // 'textTo' value in it:
    result =
      text.substring(
        text.indexOf(textFrom) + textFrom.length(),
        text.length());

    // Cut the excessive ending of the text:
    result =
      result.substring(
        0,
        result.indexOf(textTo));

    return result;
  }

POST unchecked HTML checkboxes

I prefer to stay with solutions that do not require javascript (and yes, I know there will be some that now categorize me as a luddite) but if you are like me, and you want to be able to display a default / initial setting for a checkbox and then have it hold or update based on the form being submitted, try this (built on a couple of ideas above):

Set the variables determining the initial checkbox state and then use server checks to determine the display after each submit of the form.

The example below creates an array of arrays (for use in WordPress ; works equally well elsewhere) and then determines the checkbox state using server script without using either hidden fields or javascript.

<?php

$options_array = array (
    array('list_companies_shortcode' , 'shortcode_list_companies' , 'List Companies Shortcode'),
    array('list_contacts_shortcode' , 'shortcode_list_contacts' , 'List Contacts Shortcode'),
    array('test_checkbox_1' , 'checked' , 'Label for Checkbox 1' , 'checkbox' , 'Some text to instruct the user on this checkbox use' ),
    array('test_checkbox_2' , '' , 'Label for Checkbox 2' , 'checkbox' , 'Some other text to instruct the user on this checkbox use' )
 ) ;


$name_value_array = array() ;
$name_label_array = array() ;
$field_type_array = array() ;
$field_descriptor_array = array() ;
foreach ( $options_array as $option_entry ) {
    $name_value_array[ $option_entry[0] ] = $option_entry[1] ;
    $name_label_array[ $option_entry[0] ] = $option_entry[2] ;
    if ( isset( $option_entry[3] ) ) {
        $field_type_array[ $option_entry[0] ] = $option_entry[3] ;
        $field_descriptor_array[ $option_entry[0] ] = $option_entry[4] ;
    } else {
        $field_type_array[ option_entry[0] ] = 'text' ;
        $field_descriptor_array[ $option_entry[0] ] = NULL ;
    } 
}

echo "<form action='' method='POST'>" ;
    foreach ( $name_value_array as $setting_name => $setting_value ) {
        if ( isset( $_POST[ 'submit' ] ) ) {
            if ( isset( $_POST[ $setting_name ] ) ) {
                $setting_value = $_POST[ $setting_name ] ;
            } else {
                $setting_value = '' ;
            }
        }   
        $setting_label = $option_name_label_array[ $setting_name ] ;
        $setting_field_type = $field_type_array[ $setting_name ] ;
        $setting_field_descriptor = $field_descriptor_array [ $setting_name ] ;
        echo "<label for=$setting_name >$setting_label</label>" ;
        switch ( $setting_field_type ) {
            case 'checkbox':
                echo "<input type='checkbox' id=" . $setting_name . " name=" . $setting_name . " value='checked' " . $setting_value . " >(" . $setting_field_descriptor . ")</input><br />" ;
                break ;
            default:
                echo "<input type='text' id=" . $setting_name . " name=" . $setting_name . " value=" . $setting_value . " ></input><br />" ;
        }
    }
    echo "<input type='submit' value='Submit' name='submit' >" ;
echo "</form>" ;

What is Java Servlet?

A servlet at its very core is a java class; which can handle HTTP requests. Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).

Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).

Assuming you have a container, your servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you. You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc. Look at Resource 3.

Here is a fun exercise for you. Create a simple servlet like in Resource 3 and write a few System.out.println() statements in it's constructor method (Yes you can have a constructor of a servlet), init(), doGet(), doPost() methods and run the servlet in tomcat. See the console logs and tomcat logs.

Hope this helps, happy learning.

Resources

  1. Look how the HTTP servlet looks here(Tomcat example).

  2. Servlet Specification.

  3. Simple Servlet example.

  4. Start reading the book online/PDF It also provides you download of the whole book. May be this will help. if you are just starting servlets may be it's a good idea to read the material along with the servlet API. it's a slower process of learning, but is way more helpful in getting the basics clear.

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

For each row in an R dataframe

I was curious about the time performance of the non-vectorised options. For this purpose, I have used the function f defined by knguyen

f <- function(x, output) {
  wellName <- x[1]
  plateName <- x[2]
  wellID <- 1
  print(paste(wellID, x[3], x[4], sep=","))
  cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

and a dataframe like the one in his example:

n = 100; #number of rows for the data frame
d <- data.frame( name = LETTERS[ sample.int( 25, n, replace=T ) ],
                  plate = paste0( "P", 1:n ),
                  value1 = 1:n,
                  value2 = (1:n)*10 )

I included two vectorised functions (for sure quicker than the others) in order to compare the cat() approach with a write.table() one...

library("ggplot2")
library( "microbenchmark" )
library( foreach )
library( iterators )

tm <- microbenchmark(S1 =
                       apply(d, 1, f, output = 'outputfile1'),
                     S2 = 
                       for(i in 1:nrow(d)) {
                         row <- d[i,]
                         # do stuff with row
                         f(row, 'outputfile2')
                       },
                     S3 = 
                       foreach(d1=iter(d, by='row'), .combine=rbind) %dopar% f(d1,"outputfile3"),
                     S4= {
                       print( paste(wellID=rep(1,n), d[,3], d[,4], sep=",") )
                       cat( paste(wellID=rep(1,n), d[,3], d[,4], sep=","), file= 'outputfile4', sep='\n',append=T, fill = F)                           
                     },
                     S5 = {
                       print( (paste(wellID=rep(1,n), d[,3], d[,4], sep=",")) )
                       write.table(data.frame(rep(1,n), d[,3], d[,4]), file='outputfile5', row.names=F, col.names=F, sep=",", append=T )
                     },
                     times=100L)
autoplot(tm)

The resulting image shows that apply gives the best performance for a non-vectorised version, whereas write.table() seems to outperform cat(). ForEachRunningTime

C++ String Concatenation operator<<

For string concatenation in C++, you should use the + operator.

nametext = "Your name is" + name;

Should I use @EJB or @Inject

Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.

http://www.seamframework.org/107780.lace

or

https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 20:48 America/New_York | Link Gavin King

That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?

Basically, @Inject is always better, since:

it is more typesafe,
it supports @Alternatives, and
it is aware of the scope of the injected object.

I recommend against the use of @EJB except for declaring references to remote EJBs.

and

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 17:42 America/New_York | Link Gavin King

    Does it mean @EJB better with remote EJBs?

For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

Calling stored procedure from another stored procedure SQL Server

You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:

SELECT @NewIdOutputParam = SCOPE_IDENTITY()

Then in test1, retrieve it like so:

DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed

Sending the bearer token with axios

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Edit, Thanks to Jason Norwood-Young.

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.

How to remove specific element from an array using python

The sane way to do this is to use zip() and a List Comprehension / Generator Expression:

filtered = (
    (email, other) 
        for email, other in zip(emails, other_list) 
            if email == '[email protected]')

new_emails, new_other_list = zip(*filtered)

Also, if your'e not using array.array() or numpy.array(), then most likely you are using [] or list(), which give you Lists, not Arrays. Not the same thing.

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

Center image horizontally within a div

If you have to do this inline (such as when using an input box),
here is a quick hack that worked for me: surround your (image link in this case)
in a div with style="text-align:center"

<div style="text-align:center">

<a title="Example Image: Google Logo" href="https://www.google.com/" 
target="_blank" rel="noopener"><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="Google Logo. Click to visit Google.com" border="0" data-recalc-dims="1" /></a>

<h6><strong>This text will also be centered </strong></h6>

</div> /* ends centering style */

Refresh certain row of UITableView based on Int in Swift

Swift 4.1

use it when you delete row using selectedTag of row.

self.tableView.beginUpdates()

        self.yourArray.remove(at:  self.selectedTag)
        print(self.allGroups)

        let indexPath = NSIndexPath.init(row:  self.selectedTag, section: 0)

        self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)

        self.tableView.endUpdates()

        self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

what's the correct way to send a file from REST web service to client?

Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.

Client to call REST webservice:

package in.india.client.downloadfiledemo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;

public class DownloadFileClient {

    private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";

    public DownloadFileClient() {

        try {
            Client client = Client.create();
            WebResource objWebResource = client.resource(BASE_URI);
            ClientResponse response = objWebResource.path("/")
                    .type(MediaType.TEXT_HTML).get(ClientResponse.class);

            System.out.println("response : " + response);
            if (response.getStatus() == Status.OK.getStatusCode()
                    && response.hasEntity()) {
                MultiPart objMultiPart = response.getEntity(MultiPart.class);
                java.util.List<BodyPart> listBodyPart = objMultiPart
                        .getBodyParts();
                BodyPart filenameBodyPart = listBodyPart.get(0);
                BodyPart fileLengthBodyPart = listBodyPart.get(1);
                BodyPart fileBodyPart = listBodyPart.get(2);

                String filename = filenameBodyPart.getEntityAs(String.class);
                String fileLength = fileLengthBodyPart
                        .getEntityAs(String.class);
                File streamedFile = fileBodyPart.getEntityAs(File.class);

                BufferedInputStream objBufferedInputStream = new BufferedInputStream(
                        new FileInputStream(streamedFile));

                byte[] bytes = new byte[objBufferedInputStream.available()];

                objBufferedInputStream.read(bytes);

                String outFileName = "D:/"
                        + filename;
                System.out.println("File name is : " + filename
                        + " and length is : " + fileLength);
                FileOutputStream objFileOutputStream = new FileOutputStream(
                        outFileName);
                objFileOutputStream.write(bytes);
                objFileOutputStream.close();
                objBufferedInputStream.close();
                File receivedFile = new File(outFileName);
                System.out.print("Is the file size is same? :\t");
                System.out.println(Long.parseLong(fileLength) == receivedFile
                        .length());
            }
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new DownloadFileClient();
    }
}

Service to response client:

package in.india.service.downloadfiledemo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.multipart.MultiPart;

@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {

    @GET
    public Response getFile() {

        java.io.File objFile = new java.io.File(
                "D:/DanGilbert_2004-480p-en.mp4");
        MultiPart objMultiPart = new MultiPart();
        objMultiPart.type(new MediaType("multipart", "mixed"));
        objMultiPart
                .bodyPart(objFile.getName(), new MediaType("text", "plain"));
        objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
                "plain"));
        objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));

        return Response.ok(objMultiPart).build();

    }
}

JAR needed:

jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DownloadFileDemo</display-name>
    <servlet>
        <display-name>JAX-RS REST Servlet</display-name>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name> 
             <param-value>in.india.service.downloadfiledemo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Save file/open file dialog box, using Swing & Netbeans GUI editor

Here is an example

private void doOpenFile() {
    int result = myFileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        Path path = myFileChooser.getSelectedFile().toPath();

        try {
            String contentString = "";

            for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                contentString += s;
            }

            jText.setText(contentString);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void doSaveFile() {
    int result = myFileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        // We'll be making a mytmp.txt file, write in there, then move it to
        // the selected
        // file. This takes care of clearing that file, should there be
        // content in it.
        File targetFile = myFileChooser.getSelectedFile();

        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }

            FileWriter fw = new FileWriter(targetFile);

            fw.write(jText.getText());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Rerender view on browser resize with React

@SophieAlpert is right, +1, I just want to provide a modified version of her solution, without jQuery, based on this answer.

var WindowDimensions = React.createClass({
    render: function() {
        return <span>{this.state.width} x {this.state.height}</span>;
    },
    updateDimensions: function() {

    var w = window,
        d = document,
        documentElement = d.documentElement,
        body = d.getElementsByTagName('body')[0],
        width = w.innerWidth || documentElement.clientWidth || body.clientWidth,
        height = w.innerHeight|| documentElement.clientHeight|| body.clientHeight;

        this.setState({width: width, height: height});
        // if you are using ES2015 I'm pretty sure you can do this: this.setState({width, height});
    },
    componentWillMount: function() {
        this.updateDimensions();
    },
    componentDidMount: function() {
        window.addEventListener("resize", this.updateDimensions);
    },
    componentWillUnmount: function() {
        window.removeEventListener("resize", this.updateDimensions);
    }
});

Java swing application, close one window and open another when button is clicked

Call below method just after calling the method for opening new window, this will close the current window.

private void close(){
    WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing);
}

Also in properties of JFrame, make sure defaultCloseOperation is set as DISPOSE.

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */
}



/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

Eventually what solved the issue was:

  1. Clean every project individually (Right click> Clean).
  2. Rebuild every project individually (Right click> Rebuild).
  3. Rebuild the startup project.

I guess for some reason, just cleaning the solution had a different effect than specifically cleaning every project individually.

Edit:
As per @maplemale comment, It seems that sometimes removing and re-adding each reference is also required.

Update 2019:
This question got a lot of traffic in the past, but it seems that since VS 2017 was released, it got much less attention.
So another suggestion would be - Update to a newer version of VS (>= 2017) and among other new features this issue will also be solved

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

Java, "Variable name" cannot be resolved to a variable

I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

How can I upgrade NumPy?

I tried doing sudo pip uninstall numpy instead, because the rm didn't work at first.

Hopefully that helps.

Uninstalling then to install it again.

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

How do I control how Emacs makes backup files?

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.

How do I change the UUID of a virtual disk?

Though you have solved the problem, I just post the reason here for some others with the similar problem.

The reason is there's an space in your path(directory name VirtualBox VMs) which will separate the command. So the error appears.

Creating a blocking Queue<T> in .NET?

That looks very unsafe (very little synchronization); how about something like:

class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize)
            {
                Monitor.Wait(queue);
            }
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                // wake up any blocked dequeue
                Monitor.PulseAll(queue);
            }
        }
    }
    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                Monitor.Wait(queue);
            }
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                // wake up any blocked enqueue
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }
}

(edit)

In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):

bool closing;
public void Close()
{
    lock(queue)
    {
        closing = true;
        Monitor.PulseAll(queue);
    }
}
public bool TryDequeue(out T value)
{
    lock (queue)
    {
        while (queue.Count == 0)
        {
            if (closing)
            {
                value = default(T);
                return false;
            }
            Monitor.Wait(queue);
        }
        value = queue.Dequeue();
        if (queue.Count == maxSize - 1)
        {
            // wake up any blocked enqueue
            Monitor.PulseAll(queue);
        }
        return true;
    }
}

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How do I seed a random class to avoid getting duplicate random values

I use this for most situations, keep the seed if there is a need to repeat the sequence

    var seed = (int) DateTime.Now.Ticks;
    var random = new Random(seed);

or

    var random = new Random((int)DateTime.Now.Ticks);

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

how to check if item is selected from a comboBox in C#

Here is the perfect coding which checks whether the Combo Box Item is Selected or not

if (string.IsNullOrEmpty(comboBox1.Text))
{
    MessageBox.Show("No Item is Selected"); 
}
else
{
    MessageBox.Show("Item Selected is:" + comboBox1.Text);
}

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

Python Create unix timestamp five minutes in the future

Note that solutions with timedelta.total_seconds() work on python-2.7+. Use calendar.timegm(future.utctimetuple()) for lower versions of Python.

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Yes, in your formula, you can cbind the numeric variables to be aggregated:

aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
   year month         x1          x2
1  2000     1   7.862002   -7.469298
2  2001     1 276.758209  474.384252
3  2000     2  13.122369 -128.122613
...
23 2000    12  63.436507  449.794454
24 2001    12 999.472226  922.726589

See ?aggregate, the formula argument and the examples.

React.js, wait for setState to finish before triggering a function?

Why not one more answer? setState() and the setState()-triggered render() have both completed executing when you call componentDidMount() (the first time render() is executed) and/or componentDidUpdate() (any time after render() is executed). (Links are to ReactJS.org docs.)

Example with componentDidUpdate()

Caller, set reference and set state...

<Cmp ref={(inst) => {this.parent=inst}}>;
this.parent.setState({'data':'hello!'});

Render parent...

componentDidMount() {           // componentDidMount() gets called after first state set
    console.log(this.state.data);   // output: "hello!"
}
componentDidUpdate() {          // componentDidUpdate() gets called after all other states set
    console.log(this.state.data);   // output: "hello!"
}

Example with componentDidMount()

Caller, set reference and set state...

<Cmp ref={(inst) => {this.parent=inst}}>
this.parent.setState({'data':'hello!'});

Render parent...

render() {              // render() gets called anytime setState() is called
    return (
        <ChildComponent
            state={this.state}
        />
    );
}

After parent rerenders child, see state in componentDidUpdate().

componentDidMount() {           // componentDidMount() gets called anytime setState()/render() finish
console.log(this.props.state.data); // output: "hello!"
}

Delete all data in SQL Server database

Usually I will just use the undocumented proc sp_MSForEachTable

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' 
GO 

-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 
GO

See also: Delete all data in database (when you have FKs)

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

Yes, the source folder is not in Python's path if you cd to the tests directory.

You have 2 choices:

  1. Add the path manually to the test files, something like this:

    import sys, os
    myPath = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, myPath + '/../')
    
  2. Run the tests with the env var PYTHONPATH=../.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

How to add an image in Tkinter?

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

String Padding in C

The function itself looks fine to me. The problem could be that you aren't allocating enough space for your string to pad that many characters onto it. You could avoid this problem in the future by passing a size_of_string argument to the function and make sure you don't pad the string when the length is about to be greater than the size.

How do I use MySQL through XAMPP?

Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.

  • In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.

  • Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)

  • Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777

  • Find again and change line ServerName localhost:80 to ServerName localhost:7777

  • Save and re-start Apache. It should be running by now.

The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost it becomes http://localhost:7777.

Hello World in Python

Unfortunately the xkcd comic isn't completely up to date anymore.

https://imgs.xkcd.com/comics/python.png

Since Python 3.0 you have to write:

print("Hello world!")

And someone still has to write that antigravity library :(

How do I run a docker instance from a DockerFile?

You cannot start a container from a Dockerfile.

The process goes like this:

Dockerfile =[docker build]=> Docker image =[docker run]=> Docker container

To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].

[1]: you can also docker import an image from a tarball or again docker load.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Login with windows authentication mode and fist of all make sure that the sa authentication is enabled in the server, I am using SQL Server Management Studio, so I will show you how to do this there.

Right click on the server and click on Properties.

enter image description here

Now go to the Security section and select the option SQL Server and Windows Authentication mode

enter image description here

Once that is done, click OK. And then enable the sa login.

Go to your server, click on Security and then Logins, right click on sa and then click on Properties.

enter image description here

Now go tot Status and then select Enabled under Login. Then, click OK.

Now we can restart the SQLExpress, or the SQL you are using. Go to Services and Select the SQL Server and then click on Restart. Now open the SQL Server Management Studio and you should be able to login as sa user.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

Check if a temporary table exists and delete if it exists before creating a temporary table

I cannot reproduce the error.

Perhaps I'm not understanding the problem.

The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
GO
select company, stepid, fieldid from #Results
GO
ALTER TABLE #Results ADD foo VARCHAR(50) NULL
GO
select company, stepid, fieldid, foo from #Results
GO
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO

git: updates were rejected because the remote contains work that you do not have locally

This is how I solved this issue:

  1. git pull origin master
  2. git push origin master

This usually happens when your remote branch is not updated. And after this if you get an error like "Please enter a commit message" Refer to this ( For me xiaohu Wang answer worked :) )

Python: pandas merge multiple dataframes

If you are filtering by common date this will return it:

dfs = [df1, df2, df3]
checker = dfs[-1]
check = set(checker.loc[:, 0])

for df in dfs[:-1]:
    check = check.intersection(set(df.loc[:, 0]))

print(checker[checker.loc[:, 0].isin(check)])

Emulate Samsung Galaxy Tab

Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml

Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.

Happy Android developments guys!!!

How can I get form data with JavaScript/jQuery?

Based on jQuery.serializeArray, returns key-value pairs.

var data = $('#form').serializeArray().reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

Embedding Windows Media Player for all browsers

Use the following. It works in Firefox and Internet Explorer.

        <object id="MediaPlayer1" width="690" height="500" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
            codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
            standby="Loading Microsoft® Windows® Media Player components..." type="application/x-oleobject"
            >
            <param name="FileName" value='<%= GetSource() %>' />
            <param name="AutoStart" value="True" />
            <param name="DefaultFrame" value="mainFrame" />
            <param name="ShowStatusBar" value="0" />
            <param name="ShowPositionControls" value="0" />
            <param name="showcontrols" value="0" />
            <param name="ShowAudioControls" value="0" />
            <param name="ShowTracker" value="0" />
            <param name="EnablePositionControls" value="0" />


            <!-- BEGIN PLUG-IN HTML FOR FIREFOX-->
            <embed  type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"
                src='<%= GetSource() %>' align="middle" width="600" height="500" defaultframe="rightFrame"
                 id="MediaPlayer2" />

And in JavaScript,

    function playVideo() {
        try{
                if(-1 != navigator.userAgent.indexOf("MSIE"))
                {
                        var obj = document.getElementById("MediaPlayer1");
                            obj.Play();

                }
                else
                {
                            var player = document.getElementById("MediaPlayer2");
                            player.controls.play();

                }
             }  
        catch(error) {
            alert(error)
        } 


        }

System.web.mvc missing

Easiest way to solve this problem is install ASP.NET MVC 3 from Web Platforms installer.

enter image description here

http://www.microsoft.com/web/downloads/

Or by using Nuget command

Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1

Full screen background image in an activity

The easiest way:

Step 1: Open AndroidManifest.xml file

You can see the file here!

Step 2: Locate android:theme="@style/AppTheme" >

Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >

Step 4: Then Add ImageView & Image

Step 4: That's it!

Order of items in classes: Fields, Properties, Constructors, Methods

From StyleCop

private fields, public fields, constructors, properties, public methods, private methods

As StyleCop is part of the MS build process you could view that as a de facto standard

Export to xls using angularjs

$scope.ExportExcel= function () { //function define in html tag                          

                        //export to excel file
                        var tab_text = '<table border="1px" style="font-size:20px" ">';
                        var textRange;
                        var j = 0;
                        var tab = document.getElementById('TableExcel'); // id of table
                        var lines = tab.rows.length;

                        // the first headline of the table
                        if (lines > 0) {
                            tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
                        }

                        // table data lines, loop starting from 1
                        for (j = 1 ; j < lines; j++) {
                            tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";                                
                        }

                        tab_text = tab_text + "</table>";
                        tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");          //remove if u want links in your table
                        tab_text = tab_text.replace(/<img[^>]*>/gi, "");             // remove if u want images in your table
                        tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

                        // console.log(tab_text); // aktivate so see the result (press F12 in browser)               
                        var fileName = 'report.xls'                            
                        var exceldata = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" }) 

                        if (window.navigator.msSaveBlob) { // IE 10+
                            window.navigator.msSaveOrOpenBlob(exceldata, fileName);
                            //$scope.DataNullEventDetails = true;
                        } else {
                            var link = document.createElement('a'); //create link download file
                            link.href = window.URL.createObjectURL(exceldata); // set url for link download
                            link.setAttribute('download', fileName); //set attribute for link created
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }

                    }

        //html of button 

In Javascript, how to conditionally add a member to an object?

Using spread syntax with boolean (as suggested here) is not valid syntax. Spread can only be use with iterables.

I suggest the following:

const a = {
   ...(someCondition? {b: 5}: {} )
}

java.lang.IllegalStateException: Fragment not attached to Activity

In Fragment use isAdded() It will return true if the fragment is currently attached to Activity.

If you want to check inside the Activity

 Fragment fragment = new MyFragment();
   if(fragment.getActivity()!=null)
      { // your code here}
      else{
       //do something
       }

Hope it will help someone

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

use keyof typeof

const cat = {
    name: 'tuntun'
}

const key: string = 'name' 

cat[key as keyof typeof cat]

$ is not a function - jQuery error

There are quite lots of answer based on situation.

1) Try to replace '$' with "jQuery"

2) Check that code you are executed are always below the main jquery script.

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

});
</script>

3) Pass $ into the function and add "jQuery" as a main function like below.

<script type="text/javascript">
jQuery(document).ready(function($){

});
</script>