Programs & Examples On #Jawr

Jawr is a tunable packaging solution for JavaScript and CSS which allows for rapid development of resources in separate module files. Developers can work with a large set of split JavaScript files in development mode, then Jawr bundles all together into one or several files in a configurable way.

How to pause a YouTube player when hiding the iframe?

Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

    function toggleVideo(state) {
        if(state == 'hide'){
            $('#video-div').modal('hide');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
        else {
            $('#video-div').modal('show');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        }
    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .

For more on the html see RobW's answer.

Get the Id of current table row with Jquery

This:

<table id="test">
      <tr  id="TEST1" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact1" size="20" />  Number 
          <input type="text" id="number1" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1" id="contact1" /></td>
      </tr>


      <tr id="TEST2" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact2" size="20" />  Number 
          <input type="text" id="number2" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
      </tr>

      <tr id="TEST3" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact3" size="20" />  Number 
          <input type="text" id="number3" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
</tr>

and javascript:

$(function() {
  var bid, trid;
  $('#test tr').click(function() {
       trid = $(this).attr('id'); // table row ID 
       alert(trid);
  });

});

It worked here!

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Send POST data on redirect with JavaScript/jQuery?

Generic function to post any JavaScript object to the given URL.

function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}

PHP - get base64 img string decode and save as jpg (resulting empty image )

AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.

$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

Hope this will help.

PHP CODE WITH IMAGE DATA

$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

So Following is the php part of your program .. NOTE the change with comment Change is here

    $uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
     foreach ($uploadedPhotos as $file) {
      if($this->input->post($file)){                   
         $imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
         $photo = imagecreatefromstring($imageData); // <-- **Change is here**

        /* Set name of the photo for show in the form */
        $this->session->set_userdata('upload_'.$file,'ant');
        /*set time of the upload*/
        if(!$this->session->userdata('uploading_on_datetime')){
         $this->session->set_userdata('uploading_on_datetime',time());
        }
         $datetime_upload = $this->session->userdata('uploading_on_datetime',true);

        /* create temp dir with time and user id */
        $new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
        if(!is_dir($new_dir)){
        @mkdir($new_dir);
        }
        /* move uploaded file with new name */
        // @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
        imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**

      }
    }

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

How do I parse JSON in Android?

Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.

Get your JSON:

Assume you have a json string

String result = "{\"someKey\":\"someValue\"}";

Create a JSONObject:

JSONObject jObject = new JSONObject(result);

If your json string is an array, e.g.:

String result = "[{\"someKey\":\"someValue\"}]"

then you should use JSONArray as demonstrated below and not JSONObject

To get a specific string

String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer

int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long

long aJsonLong = jObject.getLong("LONGNAME");

To get a specific double

double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:

JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

What is difference between cacerts and keystore?

cacerts is where Java stores public certificates of root CAs. Java uses cacerts to authenticate the servers.

Keystore is where Java stores the private keys of the clients so that it can share it to the server when the server requests client authentication.

Finding length of char array

If you are expecting 4 as output then try this:

char a[]={0x00,0xdc,0x01,0x04};

Post parameter is always null

I know the OP was originally sending a single string, but for future reference, it is also worth noting that malformed JSON will also arrive as null into the post method. In my case, a missing comma between two properties caused what was otherwise fine, to break.

How to read integer values from text file

You might want to do something like this (if you're using java 5 and more)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
     tall[i++] = scanner.nextInt();
}

Via Julian Grenier from Reading Integers From A File In An Array

How do you make Git work with IntelliJ?

GitHub for Windows on Windows 7 currently installs Git in a path similar to this:

C:\Users\{username}\AppData\Local\GitHub\PortableGit_93e8418133eb85e81a81e5e19c272776524496c6\bin\git.exe

The guid after PortableGit_ may well be different on your system.

Create space at the beginning of a UITextField

Create UIView with required padding space and add it to textfield.leftView member and set textfield.leftViewMode member to UITextFieldViewMode.Always

// For example if you have textfield named title
@IBOutlet weak var title: UITextField!
// Create UIView 
let paddingView : UIView = UIView(frame: CGRectMake(0, 0, 5, 20))
//Change your required space instaed of 5.
title.leftView = paddingView
title.leftViewMode = UITextFieldViewMode.Always

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

How to filter files when using scp to copy dir recursively?

I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:-

rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \ 
/usr/project/backup/some/unknown/number/of/sub/folders/

Some other useful flags:

  • -r for recursive
  • -a for archive (mostly all files)
  • -v for verbose output
  • -e to specify ssh instead of the default (which should be ssh, actually)

Export DataTable to Excel File

            var lines = new List<string>();

            string[] columnNames = dt.Columns.Cast<DataColumn>().
                                              Select(column => column.ColumnName).
                                              ToArray();

            var header = string.Join(",", columnNames);
            lines.Add(header);
            var valueLines = dt.AsEnumerable()
                               .Select(row => string.Join(",", row.ItemArray));
            lines.AddRange(valueLines);
            File.WriteAllLines("excel.csv", lines);

Here dt refers to your DataTable pass as a paramter

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!

Edit: Setting the login as db owner solved the next problem, too

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Fixed header table with horizontal scrollbar and vertical scrollbar on

working example in jsFiddle

This can be achieved using div. It can be done with table too. But i always prefer div.

<body id="doc-body" style="width: 100%; height: 100%; overflow: hidden; position: fixed" onload="InitApp()"> 
    <div>
        <!--If you don't need header background color you don't need this div.-->
        <div id="div-header-hack" style="height: 20px; position: absolute; background-color: gray"></div>

        <div id="div-header" style="position: absolute; top: 0px; overflow: hidden; height: 20px; background-color: gray">                
        </div>

        <div id="div-item" style="position: absolute; top: 20px; overflow: auto" onscroll="ScrollHeader()">                
        </div>
    </div>
</body>

Javascript:
please refer jsFiddle for this part. Else this answer becomes very lengthy.

Creating a Shopping Cart using only HTML/JavaScript

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm

You can try following approach:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.

Documentation

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful.

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

linq query to return distinct field values from a list of objects

I think this is what your looking for:

    var objs= (from c in List_Objects 
orderby c.TypeID  select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());      

Similar to this Returning a Distinct IQueryable with LINQ?

How can I select the first day of a month in SQL?

It is probably quite fast. Why not create it as a sql function.

CREATE FUNCTION [dbo].[GetFirstDayOfMonth] ( @InputDate    DATETIME )
RETURNS DATETIME
BEGIN

    RETURN CAST(CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' + 
                CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01' AS DATETIME)

END
GO

How to instantiate, initialize and populate an array in TypeScript?

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

Checking if a string array contains a value, and if so, getting its position

I created an extension method for re-use.

   public static bool InArray(this string str, string[] values)
    {
        if (Array.IndexOf(values, str) > -1)
            return true;

        return false;
    }

How to call it:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(value.InArray(stringArray))
{
  //do something
}

Send and receive messages through NSNotificationCenter in Objective-C?

This one helped me:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}

Source: http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example

When should I use Lazy<T>?

I have been considering using Lazy<T> properties to help improve the performance of my own code (and to learn a bit more about it). I came here looking for answers about when to use it but it seems that everywhere I go there are phrases like:

Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

from MSDN Lazy<T> Class

I am left a bit confused because I am not sure where to draw the line. For example, I consider linear interpolation as a fairly quick computation but if I don't need to do it then can lazy initialisation help me to avoid doing it and is it worth it?

In the end I decided to try my own test and I thought I would share the results here. Unfortunately I am not really an expert at doing these sort of tests and so I am happy to get comments that suggest improvements.

Description

For my case, I was particularly interested to see if Lazy Properties could help improve a part of my code that does a lot of interpolation (most of it being unused) and so I have created a test that compared 3 approaches.

I created a separate test class with 20 test properties (lets call them t-properties) for each approach.

  • GetInterp Class: Runs linear interpolation every time a t-property is got.
  • InitInterp Class: Initialises the t-properties by running the linear interpolation for each one in the constructor. The get just returns a double.
  • InitLazy Class: Sets up the t-properties as Lazy properties so that linear interpolation is run once when the property is first got. Subsequent gets should just return an already calculated double.

The test results are measured in ms and are the average of 50 instantiations or 20 property gets. Each test was then run 5 times.

Test 1 Results: Instantiation (average of 50 instantiations)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.005668 0.005722 0.006704 0.006652 0.005572 0.0060636 6.72
InitInterp 0.08481  0.084908 0.099328 0.098626 0.083774 0.0902892 100.00
InitLazy   0.058436 0.05891  0.068046 0.068108 0.060648 0.0628296 69.59

Test 2 Results: First Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.263    0.268725 0.31373  0.263745 0.279675 0.277775 54.38
InitInterp 0.16316  0.161845 0.18675  0.163535 0.173625 0.169783 33.24
InitLazy   0.46932  0.55299  0.54726  0.47878  0.505635 0.510797 100.00

Test 3 Results: Second Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.08184  0.129325 0.112035 0.097575 0.098695 0.103894 85.30
InitInterp 0.102755 0.128865 0.111335 0.10137  0.106045 0.110074 90.37
InitLazy   0.19603  0.105715 0.107975 0.10034  0.098935 0.121799 100.00

Observations

GetInterp is fastest to instantiate as expected because its not doing anything. InitLazy is faster to instantiate than InitInterp suggesting that the overhead in setting up lazy properties is faster than my linear interpolation calculation. However, I am a bit confused here because InitInterp should be doing 20 linear interpolations (to set up it's t-properties) but it is only taking 0.09 ms to instantiate (test 1), compared to GetInterp which takes 0.28 ms to do just one linear interpolation the first time (test 2), and 0.1 ms to do it the second time (test 3).

It takes InitLazy almost 2 times longer than GetInterp to get a property the first time, while InitInterp is the fastest, because it populated its properties during instantiation. (At least that is what it should have done but why was it's instantiation result so much quicker than a single linear interpolation? When exactly is it doing these interpolations?)

Unfortunately it looks like there is some automatic code optimisation going on in my tests. It should take GetInterp the same time to get a property the first time as it does the second time, but it is showing as more than 2x faster. It looks like this optimisation is also affecting the other classes as well since they are all taking about the same amount of time for test 3. However, such optimisations may also take place in my own production code which may also be an important consideration.

Conclusions

While some results are as expected, there are also some very interesting unexpected results probably due to code optimisations. Even for classes that look like they are doing a lot of work in the constructor, the instantiation results show that they may still be very quick to create, compared to getting a double property. While experts in this field may be able to comment and investigate more thoroughly, my personal feeling is that I need to do this test again but on my production code in order to examine what sort of optimisations may be taking place there too. However, I am expecting that InitInterp may be the way to go.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Cannot call getSupportFragmentManager() from activity

Instead of

extends Fragment

use

extends android.support.v4.app.Fragment 

This works for me. for *API14 and above

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

Best way to get value from Collection by index

I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):

List list = new ArrayList(theCollection);
list.get(5);

Or

Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);

If you know what generics is I can provide samples for that too.

Edit: It's another question what the intent and semantics of the original collection is.

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

Most efficient T-SQL way to pad a varchar on the left to a certain length?

Several people gave versions of this:

right('XXXXXXXXXXXX'+ @str, @n)

be careful with that because it will truncate your actual data if it is longer than n.

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

Design Android EditText to show error message as described by google

If anybody still facing the error with using google's design library as mentioned in the answer then, please use this as commented by @h_k which is -

Instead of calling setError on TextInputLayout, You might be using setError on EditText itself.

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

What is the difference between Task.Run() and Task.Factory.StartNew()

In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

This definitely works most of the time:

Go to your target Build Settings -> Other linker flags -> double click . Add $(inherited) to a new line.

If you have problem with "...target overrides the GCC_PREPROCESSOR_DEFINITIONS build setting defined in..." then you must add $(inherited) to your target Build Settings -> Preprocessor Macros

Configure WAMP server to send email

Install Fake Sendmail (download sendmail.zip). Then configure C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

The above will work against a Gmail account. And then configure php.ini:

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

Now, restart Apache, and that is basically all you need to do.

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

And you call it like so ...

<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" })  %>

Simples :-)

edit

bit more of a write up here

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

Can "git pull --all" update all my local branches?

The following one-liner fast-forwards all branches that have an upstream branch if possible, and prints an error otherwise:

git branch \
  --format "%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)" |
  sh

How does it work?

It uses a custom format with the git branch command. For each branch that has an upstream branch, it prints a line with the following pattern:

git push . <remote-ref>:<branch>

This can be piped directly into sh (assuming that the branch names are well-formed). Omit the | sh to see what it's doing.

Caveats

The one-liner will not contact your remotes. Issue a git fetch or git fetch --all before running it.

The currently checked-out branch will not be updated with a message like

! [remote rejected] origin/master -> master (branch is currently checked out)

For this, you can resort to regular git pull --ff-only .

Alias

Add the following to your .gitconfig so that git fft performs this command:

[alias]
        fft = !sh -c 'git branch --format \"%(if)%(upstream:short)%(then)git push . %(upstream:short):%(refname:short)%(end)\" | sh' -

See also my .gitconfig. The alias is a shorthand to "fast-forward tracking (branches)".

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

get current date from [NSDate date] but set the time to 10:00 am

I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.

let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!

Displaying the Indian currency symbol on a website

There are two html entity code : &#x20b9; &#8377;

How can I sort a std::map first by value, then by key?

As explained in Nawaz's answer, you cannot sort your map by itself as you need it, because std::map sorts its elements based on the keys only. So, you need a different container, but if you have to stick to your map, then you can still copy its content (temporarily) into another data structure.

I think, the best solution is to use a std::set storing flipped key-value pairs as presented in ks1322's answer. The std::set is sorted by default and the order of the pairs is exactly as you need it:

3) If lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first, returns false. Otherwise, if lhs.second<rhs.second, returns true. Otherwise, returns false.

This way you don't need an additional sorting step and the resulting code is quite short:

std::map<std::string, int> m;  // Your original map.
m["realistically"] = 1;
m["really"]        = 8;
m["reason"]        = 4;
m["reasonable"]    = 3;
m["reasonably"]    = 1;
m["reassemble"]    = 1;
m["reassembled"]   = 1;
m["recognize"]     = 2;
m["record"]        = 92;
m["records"]       = 48;
m["recs"]          = 7;

std::set<std::pair<int, std::string>> s;  // The new (temporary) container.

for (auto const &kv : m)
    s.emplace(kv.second, kv.first);  // Flip the pairs.

for (auto const &vk : s)
    std::cout << std::setw(3) << vk.first << std::setw(15) << vk.second << std::endl;

Output:

  1  realistically
  1     reasonably
  1     reassemble
  1    reassembled
  2      recognize
  3     reasonable
  4         reason
  7           recs
  8         really
 48        records
 92         record

Code on Ideone

Note: Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. As a result, the code for copying your map becomes even shorter and more readable:

for (auto const &[k, v] : m)
    s.emplace(v, k);  // Flip the pairs.

How to do a logical OR operation for integer comparison in shell scripting?

From Bash Reference Manual ? 3.4.2 Special Parameters

#
($#) Expands to the number of positional parameters in decimal.

Therefore, $# will always be either 0 or a bigger integer.

So if you want to do something whenever $# is either 0 or bigger than 1, you just have to check if $# is or is not 1:

[ $# -eq 1 ] && echo "1 positional param" || echo "0 or more than 1"

This uses the syntax:

[ condition ] && {things if true} || {things if false}

Difference between Method and Function?

There is no functions in c#. There is methods (typical method:public void UpdateLeaveStatus(EmployeeLeave objUpdateLeaveStatus)) link to msdn and functors - variable of type Func<>

Is there a stopwatch in Java?

Use System.currentTimeMillis() to get the start time and the end time and calculate the difference.

class TimeTest1 {
  public static void main(String[] args) {

    long startTime = System.currentTimeMillis();

    long total = 0;
    for (int i = 0; i < 10000000; i++) {
      total += i;
    }

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    System.out.println(elapsedTime);
  }
} 

More info at this tutorial

Clip/Crop background-image with CSS

You can put the graphic in a pseudo-element with its own dimensional context:

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}

_x000D_
_x000D_
#graphic {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
    content: '';_x000D_
    _x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    z-index: -1;_x000D_
    _x000D_
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
_x000D_
_x000D_

Browser support is good, but if you need to support IE8, use a single colon :before. IE has no support for either syntax in versions prior to that.

How to Correctly Check if a Process is running and Stop it

Thanks @Joey. It's what I am looking for.

I just bring some improvements:

  • to take into account multiple processes
  • to avoid reaching the timeout when all processes have terminated
  • to package the whole in a function

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    $processList = Get-Process $processName -ErrorAction SilentlyContinue
    if ($processList) {
        # Try gracefully first
        $processList.CloseMainWindow() | Out-Null

        # Wait until all processes have terminated or until timeout
        for ($i = 0 ; $i -le $timeout; $i ++){
            $AllHaveExited = $True
            $processList | % {
                $process = $_
                If (!$process.HasExited){
                    $AllHaveExited = $False
                }                    
            }
            If ($AllHaveExited){
                Return
            }
            sleep 1
        }
        # Else: kill
        $processList | Stop-Process -Force        
    }
}

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

How to put spacing between floating divs?

You can do the following:

Assuming your container div has a class "yellow".

.yellow div {
    // Apply margin to every child in this container
    margin: 10px;
}

.yellow div:first-child, .yellow div:nth-child(3n+1) {
    // Remove the margin on the left side on the very first and then every fourth element (for example)
    margin-left: 0;
}

.yellow div:last-child {
    // Remove the right side margin on the last element
    margin-right: 0;
}

The number 3n+1 equals every fourth element outputted and will clearly only work if you know how many will be displayed in a row, but it should illustrate the example. More details regarding nth-child here.

Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.

Note2: The :nth-child() selector is supported in all major browsers, except IE8 and earlier.

Sublime Text 2 - Show file navigation in sidebar

You have to add a folder to the Sublime Text window in order to navigate via the sidebar. Go to File -> Open Folder... and select the highest directory you want to be able to navigate.

Also, 'View -> Sidebar -> Show Sidebar' if it still doesn't show. In the new version, there is only an 'open' menu and no separate option for opening a folder.

How to read/write from/to file using Go?

Just looking at the documentation it seems you should just declare a buffer of type []byte and pass it to read which will then read up to that many characters and return the number of characters actually read (and an error).

The docs say

Read reads up to len(b) bytes from the File. It returns the number of bytes read and an Error, if any. EOF is signaled by a zero count with err set to EOF.

Does that not work?

EDIT: Also, I think you should perhaps use the Reader/Writer interfaces declared in the bufio package instead of using os package.

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

What is this Javascript "require"?

Necromancing.
IMHO, the existing answers leave much to be desired.

It's very simple:
Require is simply a (non-standard) function defined at global scope.
(window in browser, global in NodeJS).

Now, as such, to answer the question "what is require", we "simply" need to know what this function does.
This is perhaps best explained with code.

Here's a simple implementation by Michele Nasti, the code you can find on his github page.

Basically, let's call our minimalisc require function myRequire:

function myRequire(name) 
{
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequire.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = fs.readFileSync(name, 'utf8');
        let module = { exports: {} };
        myRequire.cache[name] = module;
        let wrapper = Function("require, exports, module", code);
        wrapper(myRequire, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequire.cache[name].exports;
}
myRequire.cache = Object.create(null);
window.require = myRequire;
const stuff = window.require('./main.js');
console.log(stuff);

Now you notice, the object "fs" is used here.
For simplicity's sake, Michele just imported the NodeJS fs module:

const fs = require('fs');

Which wouldn't be necessary.
So in the browser, you could make a simple implementation of require with a SYNCHRONOUS XmlHttpRequest:

const fs = {
    file: `
    // module.exports = \"Hello World\";
        
    module.exports = function(){ return 5*3;};
    
    `
    , getFile(fileName: string, encoding: string): string
    {
        // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
        let client = new XMLHttpRequest();
        // client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

        // open(method, url, async)
        client.open("GET", fileName, false);
        client.send();
        if (client.status === 200)
            return client.responseText;

        return null;
    }


    , readFileSync: function (fileName: string, encoding: string): string
    {
        // this.getFile(fileName, encoding);
        return this.file; // Example, getFile would fetch this file 
    }
};

Basically, what require thus does, is download a JavaScript-file, eval it in an anonymous namespace (aka Function), with the global parameters "require", "exports" and "module", and return the exports, meaning an object's public functions and properties.

Note that this evaluation is recursive: you require files, which themselfs can require files.

This way, all "global" variables used in your module are variables in the require-wrapper-function namespace, and don't pollute the global scope with unwanted variables.

Also, this way, you can reuse code without depending on namespaces, so you get "modularity" in JavaScript. "modularity" in quotes, because this is not exactly true, though, because you can still write window.bla, and hence still pollute the global scope... Also, this establishes a separation between private and public functions, the public functions being the exports.

Now instead of saying

module.exports = function(){ return 5*3;};

You can also say:

function privateSomething()
{
    return 42:
}


function privateSomething2()
{
    return 21:
}


module.exports = {
      getRandomNumber: privateSomething
     ,getHalfRandomNumber: privateSomething2
};

and return an object.

Also, because your modules get evaluated in a function with parameters "require", "exports" and "module", your modules can use the undeclared variables "require", "exports" and "module", which might be startling at first. The require parameter there is of course a ByVal pointer to the require function saved into a variable.
Cool, right ?
Seen this way, require looses its magic, and becomes simple.
Now, the real require-function will do a few more checks and quirks, of course, but this is the essence of what that boils down to.

Also, in 2020, you should use the ECMA implementations instead of require:

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";

And if you need a dynamic non-static import (e.g. load a polyfill based on browser-type), there is the ECMA-import function/keyword:

var promise = import("module-name");

note that import is not synchronous like require.
Instead, import is a promise, so

var something = require("something");

becomes

var something = await import("something");

because import returns a promise (asynchronous).

So basically, unlike require, import replaces fs.readFileSync with fs.readFileAsync.

async readFileAsync(fileName, encoding) 
{
    const textDecoder = new TextDecoder(encoding);
    // textDecoder.ignoreBOM = true;
    const response = await fetch(fileName);
    console.log(response.ok);
    console.log(response.status);
    console.log(response.statusText);
    // let json = await response.json();
    // let txt = await response.text();
    // let blo:Blob = response.blob();
    // let ab:ArrayBuffer = await response.arrayBuffer();
    // let fd = await response.formData()
    // Read file almost by line
    // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read#Example_2_-_handling_text_line_by_line
    let buffer = await response.arrayBuffer();
    let file = textDecoder.decode(buffer);
    return file;
} // End Function readFileAsync

This of course requires the import-function to be async as well.

"use strict";
async function myRequireAsync(name) {
    console.log(`Evaluating file ${name}`);
    if (!(name in myRequireAsync.cache)) {
        console.log(`${name} is not in cache; reading from disk`);
        let code = await fs.readFileAsync(name, 'utf8');
        let module = { exports: {} };
        myRequireAsync.cache[name] = module;
        let wrapper = Function("asyncRequire, exports, module", code);
        await wrapper(myRequireAsync, module.exports, module);
    }
    console.log(`${name} is in cache. Returning it...`);
    return myRequireAsync.cache[name].exports;
}
myRequireAsync.cache = Object.create(null);
window.asyncRequire = myRequireAsync;
async () => {
    const asyncStuff = await window.asyncRequire('./main.js');
    console.log(asyncStuff);
};

Even better, right ?
Well yea, except that there is no ECMA-way to dynamically import synchronously (without promise).

Now, to understand the repercussions, you absolutely might want to read up on promises/async-await here, if you don't know what that is.

But very simply put, if a function returns a promise, it can be "awaited":

function sleep (fn, par) 
{
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}


var fileList = await sleep(listFiles, nextPageToken)

Which is nice way to make asynchronous code look synchronous.
Note that if you want to use async await in a function, that function must be declared async.

async function doSomethingAsync()
{
    var fileList = await sleep(listFiles, nextPageToken)
}

And also please note that in JavaScript, there is no way to call an async function (blockingly) from a synchronous one (the ones you know). So if you want to use await (aka ECMA-import), all your code needs to be async, which most likely is a problem, if everything isn't already async...

An example of where this simplified implementation of require fails, is when you require a file that is not valid JavaScript, e.g. when you require css, html, txt, svg and images or other binary files.
And it's easy to see why:
If you e.g. put HTML into a JavaScript function body, you of course rightfully get

SyntaxError: Unexpected token '<'

because of Function("bla", "<doctype...")

Now, if you wanted to extend this to for example include non-modules, you could just check the downloaded file-contents with for code.indexOf("module.exports") == -1, and then e.g. eval("jquery content") instead of Func (which works fine as long as you're in the browser). Since downloads with Fetch/XmlHttpRequests are subject to the same-origin-policy, and integrity is ensured by SSL/TLS, the use of eval here is rather harmless, provided you checked the JS files before you added them to your site, but that much should be standard-operating-procedure.

Note that there are several implementations of require-like functionality:

Best Practices for securing a REST API / web service

For Web Application Security, you should take a look at OWASP (https://www.owasp.org/index.php/Main_Page) which provides cheatsheets for various security attacks. You can incorporate as many measures as possible to secure your Application. With respect to API security (authorization, authentication, identity management), there are multiple ways as already mentioned (Basic,Digest and OAuth). There are loop holes in OAuth1.0, so you can use OAuth1.0a (OAuth2.0 is not widely adopted due to concerns with the specification)

Accessing constructor of an anonymous class

Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

How can I get a favicon to show up in my django app?

if you have permission then

Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico

add alias to your virtual host. (in apache config file ) similarly for robots.txt

Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt

How to delete history of last 10 commands in shell?

Combining answers from above:

history -w vi ~/.bash_history history -r

How to run eclipse in clean mode? what happens if we do so?

Two ways to run eclipse in clean mode.

1 ) In Eclipse.ini file

  • Open the eclipse.ini file located in the Eclipse installation directory.
  • Add -clean first line in the file.
  • Save the file.
  • Restart Eclipse.

enter image description here

2 ) From Command prompt (cmd/command)

  • Go to folder where Eclipse installed.
  • Take the path of Eclipse
  • C:..\eclipse\eclipse.exe -clean
  • press enter button

enter image description here

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

Decompile an APK, modify it and then recompile it

I know this question is answered still and I am not trying to be smart here. I'll just want to share another method on this topic.

Download applications with apk grail

APK Grail providing the free zip file of the application.

Initializing a two dimensional std::vector

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value

If a value other than zero, say 4 for example, was required to be the default then:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT, 4));

I should also mention uniform initialization was introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };
                           

Using PowerShell credentials without being prompted for a password

read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password

Be very careful with storing passwords this way... it's not as secure as ...

How do I dynamically set HTML5 data- attributes using react?

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

While code confirms it, Apple itself has said that Swift will be compatible on iOS 7 and Mavericks in their technical keynote (State of the platforms, session 102, around the 34 min 00 sec mark) at WWDC 2014.

How to get 2 digit year w/ Javascript?

another version:

var yy = (new Date().getFullYear()+'').slice(-2);

To get specific part of a string in c#

You can use Substring:

string b = a.Substring(0,3);

__FILE__ macro shows full path

Here is a portable function that works for both Linux (path '/') and Windows (mix of '\' and '/').
Compiles with gcc, clang and vs.

#include <string.h>
#include <stdio.h>

const char* GetFileName(const char *path)
{
    const char *name = NULL, *tmp = NULL;
    if (path && *path) {
        name = strrchr(path, '/');
        tmp = strrchr(path, '\\');
        if (tmp) {
             return name && name > tmp ? name + 1 : tmp + 1;
        }
    }
    return name ? name + 1 : path;
}

int main() {
    const char *name = NULL, *path = NULL;

    path = __FILE__;
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path ="/tmp/device.log";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:\\Downloads\\crisis.avi";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:\\Downloads/nda.pdf";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = "C:/Downloads\\word.doc";
    name = GetFileName(path);
    printf("path: %s, filename: %s\n", path, name);

    path = NULL;
    name = GetFileName(NULL);
    printf("path: %s, filename: %s\n", path, name);

    path = "";
    name = GetFileName("");
    printf("path: %s, filename: %s\n", path, name);

    return 0;
}

Standard output:

path: test.c, filename: test.c
path: /tmp/device.log, filename: device.log
path: C:\Downloads\crisis.avi, filename: crisis.avi
path: C:\Downloads/nda.pdf, filename: nda.pdf
path: C:/Downloads\word.doc, filename: word.doc
path: (null), filename: (null)
path: , filename: 

PHP Pass variable to next page

Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.

How do I run a single test using Jest?

Here is my take:

./node_modules/.bin/jest --config test/jest-unit-config.json --runInBand src/components/OpenForm/OpenForm.spec.js -t 'show expanded'

Notes:

  • ./node_modules/.bin/... is a wonderful way, to access the locally installed Jest (or Mocha or...) binary that came with the locally installed package. (Yes, in your npm scripts you can jest with nothing before, but this is handy on command line... (that's also a good start for your debugging config, whichever IDE you are using...)
  • Your project might not have a set of configuration options. But if it does (peek into the scripts in package.json), this is, what you need.
  • --runInBand – as said, don't know about your configuration, but if you concentrate on developing/fixing a single test, you rather do not want to deal with web workers...
  • Yes, you can give the whole, explicit path to your file
  • Optionally, you can use -t to not run all tests in that file, but only a single one (here: the one, that has something with ‘show expanded’ in its name). Same effect can be achieved by glueing .only() into that file.

Listing available com ports with Python

Please, try this code:

import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
    print(port.device)

first of all, you need to import package for serial port communication, so:

import serial

then you create the list of all the serial ports currently available:

ports = serial.tools.list_ports.comports(include_links=False)

and then, walking along whole list, you can for example print port names:

for port in ports :
    print(port.device)

This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after

port.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

Digital Certificate: How to import .cer file in to .truststore file using?

Instead of using sed to filter out the certificate, you can also pipe the openssl s_client output through openssl x509 -out certfile.txt, for example:

echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt

Difference between \w and \b regular expression meta characters

@Mahender, you probably meant the difference between \W (instead of \w) and \b. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.

\W would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b can be thought of as (\W|^|$). [Edit: as @?mega mentions below, \b is a zero-length match so (\W|^|$) is not strictly correct, but hopefully helps explain the diff]

Quick example: For the string Hello World, .+\W would match Hello_ (with the space) but will not match World. .+\b would match both Hello and World.

Does Python have a string 'contains' substring method?

You can use y.count().

It will return the integer value of the number of times a sub string appears in a string.

For example:

string.count("bah") >> 0
string.count("Hello") >> 1

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

create a libs folder in the inside WEB-INF directory and add jstl, standard jars as below.enter image description here

What is the instanceof operator in JavaScript?

And you can use it for error handling and debugging, like this:

try{
    somefunction();
} 
catch(error){
    if (error instanceof TypeError) {
        // Handle type Error
    } else if (error instanceof ReferenceError) {
        // Handle ReferenceError
    } else {
        // Handle all other error types
    }
}

Invalid argument supplied for foreach()

What about defining an empty array as fallback if get_value() is empty?
I can't think of a shortest way.

$values = get_values() ?: [];

foreach ($values as $value){
  ...
}

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

Give a Format String value of C2 for the value's properties as shown in figure below.

enter image description here

How can I check if a user is logged-in in php?

In file Login.html:

<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Login Form</title>
</head>
<body>
  <section class="container">
    <div class="login">
      <h1>Login</h1>
      <form method="post" action="login.php">
        <p><input type="text" name="username" value="" placeholder="Username"></p>
        <p><input type="password" name="password" value="" placeholder="Password"></p>

        <p class="submit"><input type="submit" name="commit" value="Login"></p>
      </form>
    </div>
</body>
</html>

In file Login.php:

<?php
    $host="localhost"; // Host name
    $username=""; // MySQL username
    $password=""; // MySQL password
    $db_name=""; // Database name
    $tbl_name="members"; // Table name

    // Connect to the server and select a database.
    mysql_connect("$host", "$username", "$password") or die("cannot connect");
    mysql_select_db("$db_name") or die("cannot select DB");

    // Username and password sent from the form
    $username = $_POST['username'];
    $password = $_POST['password'];

    // To protect MySQL injection (more detail about MySQL injection)
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    $sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
    $result = mysql_query($sql);

    // Mysql_num_row is counting the table rows
    $count=mysql_num_rows($result);

    // If the result matched $username and $password, the table row must be one row
    if($count == 1){
        session_start();
        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username;
    }

In file Member.php:

session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
}
else {
    echo "Please log in first to see this page.";
}

In MySQL:

CREATE TABLE `members` (
    `id` int(4) NOT NULL auto_increment,
    `username` varchar(65) NOT NULL default '',
    `password` varchar(65) NOT NULL default '',
    PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

In file Register.html:

<html>
    <head>
        <title>Sign-Up</title>
    </head>

    <body id="body-color">
        <div id="Sign-Up">
            <fieldset style="width:30%"><legend>Registration Form</legend>
                <table border="0">
                    <form method="POST" action="register.php">
                        <tr>
                            <td>UserName</td><td> <input type="text" name="username"></td>
                        </tr>

                        <tr>
                            <td>Password</td><td> <input type="password" name="password"></td>
                        </tr>

                        <tr>
                            <td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
                        </tr>
                    </form>
                </table>
            </fieldset>
        </div>
    </body>
</html>

In file Register.php:

<?php
    define('DB_HOST', '');
    define('DB_NAME', '');
    define('DB_USER','');
    define('DB_PASSWORD', '');

    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
    $db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());

    $userName = $_POST['username'];
    $password = $_POST['password'];
    $query = "INSERT INTO members (username,password) VALUES ('$userName', '$password')";
    $data = mysql_query ($query) or die(mysql_error());
    if($data)
    {
        echo "Your registration is completed...";
    }
    else
    {
        echo "Unknown Error!"
    }

Spring MVC Missing URI template variable

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

For example

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

How do you render primitives as wireframes in OpenGL?

From http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5

// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box
DrawBox();

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);

How do I debug Windows services in Visual Studio?

You can also try this.

  1. Create your Windows service and install and start…. That is, Windows services must be running in your system.
  2. While your service is running, go to the Debug menu, click on Attach Process (or process in old Visual Studio)
  3. Find your running service, and then make sure the Show process from all users and Show processes in all sessions is selected, if not then select it.

enter image description here

  1. Click the Attach button
  2. Click OK
  3. Click Close
  4. Set a break point to your desirable location and wait for execute. It will debug automatic whenever your code reaches to that point.
  5. Remember, put your breakpoint at reachable place, if it is onStart(), then stop and start the service again

(After a lot of googling, I found this in "How to debug the Windows Services in Visual Studio".)

Sending arrays with Intent.putExtra

This code sends array of integer values

Initialize array List

List<Integer> test = new ArrayList<Integer>();

Add values to array List

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

Send the array list values to target activity

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

here you get values on targetActivty

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

How to obtain the start time and end time of a day?

Java 8


public static Date atStartOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
    return localDateTimeToDate(startOfDay);
}

public static Date atEndOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
    return localDateTimeToDate(endOfDay);
}

private static LocalDateTime dateToLocalDateTime(Date date) {
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}

private static Date localDateTimeToDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

Update: I've added these 2 methods to my Java Utility Classes here

It is in the Maven Central Repository at:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

Java 7 and Earlier


With Apache Commons

public static Date atEndOfDay(Date date) {
    return DateUtils.addMilliseconds(DateUtils.ceiling(date, Calendar.DATE), -1);
}

public static Date atStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}

Without Apache Commons

public Date atEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

public Date atStartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

android.widget.Switch - on/off event listener?

The layout for Switch widget is something like this.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:gravity="right"
        android:text="All"
        android:textStyle="bold"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:id="@+id/list_toggle" />
</LinearLayout>

In the Activity class, you can code by two ways. Depends on the use you can code.

First Way

public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.return_vehicle);

    list_toggle=(Switch)findViewById(R.id.list_toggle);
    list_toggle.setOnCheckedChangeListener(this);
    }
}

public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
    if(isChecked) {
        list_toggle.setText("Only Today's");  //To change the text near to switch
        Log.d("You are :", "Checked");
    }
    else {
        list_toggle.setText("All List");   //To change the text near to switch
        Log.d("You are :", " Not Checked");
    }
}

Second way

public class ActivityClass extends Activity {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.return_vehicle);

    list_toggle=(Switch)findViewById(R.id.list_toggle);
    list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          if(isChecked) {
             list_toggle.setText("Only Today's");  //To change the text near to switch
             Log.d("You are :", "Checked");
          }
          else {
             list_toggle.setText("All List");  //To change the text near to switch
             Log.d("You are :", " Not Checked");
          }
       }       
     });
   }
}

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

How to search a specific value in all tables (PostgreSQL)?

Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.

DO $$
DECLARE
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
BEGIN
  DROP TABLE IF EXISTS _x;
  CREATE TEMPORARY TABLE _x (
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  );
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
        LOOP
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
    BEGIN
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
    EXCEPTION WHEN OTHERS THEN
    END;
  END LOOP;
  END; $$;

SELECT * FROM _x;

How do I do a case-insensitive string comparison?

def insenStringCompare(s1, s2):
    """ Method that takes two strings and returns True or False, based
        on if they are equal, regardless of case."""
    try:
        return s1.lower() == s2.lower()
    except AttributeError:
        print "Please only pass strings into this method."
        print "You passed a %s and %s" % (s1.__class__, s2.__class__)

Python not working in the command line of git bash

2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:

% python

So I just use:

% winpty python

As some people have noted above, you can also use:

% python -i

2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line: enter image description here

See attached session.enter image description here

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

Setting width/height as percentage minus pixels

Another way to achieve the same goal: flex boxes. Make the container a column flex box, and then you have all freedom to allow some elements to have fixed-size (default behavior) or to fill-up/shrink-down to the container space (with flex-grow:1 and flex-shrink:1).

#wrap {        
  display:flex;
  flex-direction:column;
}
.extendOrShrink {
  flex-shrink:1;
  flex-grow:1;
  overflow:auto;
}

See https://jsfiddle.net/2Lmodwxk/ (try to extend or reduce the window to notice the effect)

Note: you may also use the shorthand property:

   flex:1 1 auto;

sql server invalid object name - but tables are listed in SSMS tables list

The solution is:

  • Click menu Query,
  • then click 'Change Database'.
  • Select your appropriate database name.

That's it.

Turn off auto formatting in Visual Studio

You can tweak the settings of the code formatting. I always turn off all extra line breaks, and then it works fine for how I format the code.

If you tweak the settings as close as you can to your preference, that should leave you minimal work whenever you use refactoring.

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Get string between two strings in a string

var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

This returns only the value(s) between "key :" and the following occurance of "-"

Why is super.super.method(); not allowed in Java?

IMO, it's a clean way to achieve super.super.sayYourName() behavior in Java.

public class GrandMa {  
    public void sayYourName(){  
        System.out.println("Grandma Fedora");  
    }  
}  

public class Mama extends GrandMa {  
    public void sayYourName(boolean lie){  
        if(lie){   
            super.sayYourName();  
        }else {  
            System.out.println("Mama Stephanida");  
        }  
    }  
}  

public class Daughter extends Mama {  
    public void sayYourName(boolean lie){  
        if(lie){   
            super.sayYourName(lie);  
        }else {  
            System.out.println("Little girl Masha");  
        }  
    }  
}  

public class TestDaughter {
    public static void main(String[] args){
        Daughter d = new Daughter();

        System.out.print("Request to lie: d.sayYourName(true) returns ");
        d.sayYourName(true);
        System.out.print("Request not to lie: d.sayYourName(false) returns ");
        d.sayYourName(false);
    }
}

Output:

Request to lie: d.sayYourName(true) returns Grandma Fedora
Request not to lie: d.sayYourName(false) returns Little girl Masha

Escaping regex string

Use the re.escape() function for this:

4.2.3 re Module Contents

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

You can do this easily with ReSharper 8 or later. The ctorf, ctorp, and ctorfp snippets generate constructors that populate all the fields, properties, or fields and properties of a class.

What does "./" (dot slash) refer to in terms of an HTML file path location?

.  = This location
.. = Up a directory

So, ./foo.html is just foo.html. And it is optional, but may have relevance if a script generated the path (relevance to the script that is, not how the reference works).

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

This was provided after installation of Sql Express 2019

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

So just use 'localhost\SQLEXPRESS' in server name and windows authentication worked for me.

enter image description here

Android: show/hide status bar/power bar

For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,

Here is the solution that worked for me, (Documentation) (Flag Reference)

Hide Status Bar

// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
   View decorView = getWindow().getDecorView();
  // Hide Status Bar.
   int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
   decorView.setSystemUiVisibility(uiOptions);
}

Show Status Bar

   if (Build.VERSION.SDK_INT < 16) {
              getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    else {
       View decorView = getWindow().getDecorView();
      // Show Status Bar.
       int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
       decorView.setSystemUiVisibility(uiOptions);
    }

Regex to match URL end-of-line or "/" character

You've got a couple regexes now which will do what you want, so that's adequately covered.

What hasn't been mentioned is why your attempt won't work: Inside a character class, $ (as well as ^, ., and /) has no special meaning, so [/$] matches either a literal / or a literal $ rather than terminating the regex (/) or matching end-of-line ($).

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

Callback functions in C++

Callback functions are part of the C standard, an therefore also part of C++. But if you are working with C++, I would suggest you use the observer pattern instead: http://en.wikipedia.org/wiki/Observer_pattern

Vertical Tabs with JQuery?

I've created a vertical menu and tabs changing in the middle of the page. I changed two words on the code source and I set apart two different divs

menu:

<div class="arrowgreen">
  <ul class="tabNavigation"> 
    <li> <a href="#first" title="Home">Tab 1</a></li>
    <li> <a href="#secund" title="Home">Tab 2</a></li>
  </ul>
</div> 

content:

<div class="pages">
  <div id="first">
    CONTENT 1
  </div>
  <div id="secund">
    CONTENT 2
  </div>
</div>

the code works with the div apart

$(function () {
    var tabContainers = $('div.pages > div');

    $('div.arrowgreen ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.arrowgreen ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');

        return false;
    }).filter(':first').click();
});

How to debug in Django, the good way?

An additional suggestion.

You can leverage nosetests and pdb together, rather injecting pdb.set_trace() in your views manually. The advantage is that you can observe error conditions when they first start, potentially in 3rd party code.

Here's an error for me today.

TypeError at /db/hcm91dmo/catalog/records/

render_option() argument after * must be a sequence, not int

....


Error during template rendering

In template /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28
render_option() argument after * must be a sequence, not int
18  
19          {% if field|is_checkboxselectmultiple %}
20              {% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
21          {% endif %}
22  
23          {% if field|is_radioselect %}
24              {% include 'bootstrap3/layout/radioselect.html' %}
25          {% endif %}
26  
27          {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28  

      {% if field|is_checkbox and form_show_labels %}

Now, I know this means that I goofed the constructor for the form, and I even have good idea of which field is a problem. But, can I use pdb to see what crispy forms is complaining about, within a template?

Yes, I can. Using the --pdb option on nosetests:

tests$ nosetests test_urls_catalog.py --pdb

As soon as I hit any exception (including ones handled gracefully), pdb stops where it happens and I can look around.

  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 537, in __str__
    return self.as_widget()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 593, in as_widget
    return force_text(widget.render(name, self.value(), attrs=attrs))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 513, in render
    options = self.render_options(choices, [value])
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 543, in render_options
    output.append(self.render_option(selected_choices, *option))
TypeError: render_option() argument after * must be a sequence, not int
INFO lib.capture_middleware log write_to_index(http://localhost:8082/db/hcm91dmo/catalog/records.html)
INFO lib.capture_middleware log write_to_index:end
> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py(543)render_options()
-> output.append(self.render_option(selected_choices, *option))
(Pdb) import pprint
(Pdb) pprint.PrettyPrinter(indent=4).pprint(self)
<django.forms.widgets.Select object at 0x115fe7d10>
(Pdb) pprint.PrettyPrinter(indent=4).pprint(vars(self))
{   'attrs': {   'class': 'select form-control'},
    'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]],
    'is_required': False}
(Pdb)         

Now, it's clear that my choices argument to the crispy field constructor was as it was a list within a list, rather than a list/tuple of tuples.

 'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]]

The neat thing is that this pdb is taking place within crispy's code, not mine and I didn't need to insert it manually.

Class has no member named

Did you remember to include the closing brace in main?

#include <iostream>
#include "Attack.h"

using namespace std;

int main()
{
  Attack attackObj;
  attackObj.printShiz();
}

Python: How do I make a subclass from a superclass?

In the answers above, the super is initialized without any (keyword) arguments. Often, however, you would like to do that, as well as pass on some 'custom' arguments of your own. Here is an example which illustrates this use case:

class SortedList(list):
    def __init__(self, *args, reverse=False, **kwargs):
        super().__init__(*args, **kwargs)       # Initialize the super class
        self.reverse = reverse
        self.sort(reverse=self.reverse)         # Do additional things with the custom keyword arguments

This is a subclass of list which, when initialized, immediately sorts itself in the direction specified by the reverse keyword argument, as the following tests illustrate:

import pytest

def test_1():
    assert SortedList([5, 2, 3]) == [2, 3, 5]

def test_2():
    SortedList([5, 2, 3], reverse=True) == [5, 3, 2]

def test_3():
    with pytest.raises(TypeError):
        sorted_list = SortedList([5, 2, 3], True)   # This doesn't work because 'reverse' must be passed as a keyword argument

if __name__ == "__main__":
    pytest.main([__file__])

Thanks to the passing on of *args to super, the list can be initialized and populated with items instead of only being empty. (Note that reverse is a keyword-only argument in accordance with PEP 3102).

Plot a legend outside of the plotting area in base graphics?

Sorry for resurrecting an old thread, but I was with the same problem today. The simplest way that I have found is the following:

# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(0,0,0,6))

# Plot graph normally
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

# Plot legend where you want
legend(3.2,1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)

Found here: http://www.harding.edu/fmccown/R/

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

How to find the Number of CPU Cores via .NET/C#?

There are many answers here already, but some have heavy upvotes and are incorrect.

The .NET Environment.ProcessorCount WILL return incorrect values and can fail critically if your system WMI is configured incorrectly.

If you want a RELIABLE way to count the cores, the only way is Win32 API.

Here is a C++ snippet:

#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}

And since this is a .NET C# Question, here's the ported version:

[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();

Writing a dict to txt file and reading it back?

To store Python objects in files, use the pickle module:

import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True

Notice that I never set b = a, but instead pickled a to a file and then unpickled it into b.

As for your error:

self.whip = open('deed.txt', 'r').read()

self.whip was a dictionary object. deed.txt contains text, so when you load the contents of deed.txt into self.whip, self.whip becomes the string representation of itself.

You'd probably want to evaluate the string back into a Python object:

self.whip = eval(open('deed.txt', 'r').read())

Notice how eval sounds like evil. That's intentional. Use the pickle module instead.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

When I catch an exception, how do I get the type, file, and line number?

You could achieve this without having to import traceback:

try:
    func1()
except Exception as ex:
    trace = []
    tb = ex.__traceback__
    while tb is not None:
        trace.append({
            "filename": tb.tb_frame.f_code.co_filename,
            "name": tb.tb_frame.f_code.co_name,
            "lineno": tb.tb_lineno
        })
        tb = tb.tb_next
    print(str({
        'type': type(ex).__name__,
        'message': str(ex),
        'trace': trace
    }))

Output:

{

  'type': 'ZeroDivisionError',
  'message': 'division by zero',
  'trace': [
    {
      'filename': '/var/playground/main.py',
      'name': '<module>',
      'lineno': 16
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func1',
      'lineno': 11
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func2',
      'lineno': 7
    },
    {
      'filename': '/var/playground/my.py',
      'name': 'test',
      'lineno': 2
    }
  ]
}

Polymorphism vs Overriding vs Overloading

The clearest way to express polymorphism is via an abstract base class (or interface)

public abstract class Human{
   ...
   public abstract void goPee();
}

This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.

So we defer the implementation by using the abstract class.

public class Male extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Stand Up");
    }
}

and

public class Female extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Sit Down");
    }
}

Now we can tell an entire room full of Humans to go pee.

public static void main(String[] args){
    ArrayList<Human> group = new ArrayList<Human>();
    group.add(new Male());
    group.add(new Female());
    // ... add more...

    // tell the class to take a pee break
    for (Human person : group) person.goPee();
}

Running this would yield:

Stand Up
Sit Down
...

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Difference between binary semaphore and mutex

Their synchronization semantics are very different:

  • mutexes allow serialization of access to a given resource i.e. multiple threads wait for a lock, one at a time and as previously said, the thread owns the lock until it is done: only this particular thread can unlock it.
  • a binary semaphore is a counter with value 0 and 1: a task blocking on it until any task does a sem_post. The semaphore advertises that a resource is available, and it provides the mechanism to wait until it is signaled as being available.

As such one can see a mutex as a token passed from task to tasks and a semaphore as traffic red-light (it signals someone that it can proceed).

In Angular, how to add Validator to FormControl after control is created?

To add onto what @Delosdos has posted.

Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

This is an amazing way to programmatically set your form validation.

MySQL Database won't start in XAMPP Manager-osx

Try running these two commands in the terminal:

  1. sudo killall mysqld sudo
  2. /Applications/XAMPP/xamppfiles/bin/mysql.server start

How to change spinner text size and text color?

Make a custom XML file for your spinner item.

spinner_item.xml:

Give your customized color and size to text in this file.

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

<TextView  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:gravity="left"  
    android:textColor="#FF0000"         
    android:padding="5dip"
    />

Now use this file to show your spinner items like:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item,list);

You don't need to set the drop down resource. It will take spinner_item.xml only to show your items in spinner.

How to find the largest file in a directory and its subdirectories?

Quote from this link-

If you want to find and print the top 10 largest files names (not directories) in a particular directory and its sub directories

$ find . -printf '%s %p\n'|sort -nr|head

To restrict the search to the present directory use "-maxdepth 1" with find.

$ find . -maxdepth 1 -printf '%s %p\n'|sort -nr|head

And to print the top 10 largest "files and directories":

$ du -a . | sort -nr | head

** Use "head -n X" instead of the only "head" above to print the top X largest files (in all the above examples)

Javascript Uncaught Reference error Function is not defined

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

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

Error in plot.new() : figure margins too large in R

I found the same error today. I have tried the "Clear all Plots" button, but it was giving me the same error. Then this trick worked for me, Try to increase the plot area by dragging. It will help you for sure.

"Thinking in AngularJS" if I have a jQuery background?

Imperative ? declarative

In jQuery, selectors are used to find DOM elements and then bind/register event handlers to them. When an event triggers, that (imperative) code executes to update/change the DOM.

In AngularJS, you want to think about views rather than DOM elements. Views are (declarative) HTML that contain AngularJS directives. Directives set up the event handlers behind the scenes for us and give us dynamic databinding. Selectors are rarely used, so the need for IDs (and some types of classes) is greatly diminished. Views are tied to models (via scopes). Views are a projection of the model. Events change models (that is, data, scope properties), and the views that project those models update "automatically."

In AngularJS, think about models, rather than jQuery-selected DOM elements that hold your data. Think about views as projections of those models, rather than registering callbacks to manipulate what the user sees.

Separation of concerns

jQuery employs unobtrusive JavaScript - behavior (JavaScript) is separated from the structure (HTML).

AngularJS uses controllers and directives (each of which can have their own controller, and/or compile and linking functions) to remove behavior from the view/structure (HTML). Angular also has services and filters to help separate/organize your application.

See also https://stackoverflow.com/a/14346528/215945

Application design

One approach to designing an AngularJS application:

  1. Think about your models. Create services or your own JavaScript objects for those models.
  2. Think about how you want to present your models -- your views. Create HTML templates for each view, using the necessary directives to get dynamic databinding.
  3. Attach a controller to each view (using ng-view and routing, or ng-controller). Have the controller find/get only whatever model data the view needs to do its job. Make controllers as thin as possible.

Prototypal inheritance

You can do a lot with jQuery without knowing about how JavaScript prototypal inheritance works. When developing AngularJS applications, you will avoid some common pitfalls if you have a good understanding of JavaScript inheritance. Recommended reading: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

How can I pass an Integer class correctly by reference?

If you change your inc() function to this

 public static Integer inc(Integer i) {
      Integer iParam = i;
      i = i+1;    // I think that this must be **sneakally** creating a new integer...  
      System.out.println(i == iParam);
      return i;
  }

then you will see that it always prints "false". That means that the addition creates a new instance of Integer and stores it in the local variable i ("local", because i is actually a copy of the reference that was passed), leaving the variable of the calling method untouched.

Integer is an immutable class, meaning that you cannot change it's value but must obtain a new instance. In this case you don't have to do it manually like this:

i = new Integer(i+1); //actually, you would use Integer.valueOf(i.intValue()+1);

instead, it is done by autoboxing.

Batch Renaming of Files in a Directory

This code will work

The function exactly takes two arguments f_patth as your path to rename file and new_name as your new name to the file.

import glob2
import os


def rename(f_path, new_name):
    filelist = glob2.glob(f_path + "*.ma")
    count = 0
    for file in filelist:
        print("File Count : ", count)
        filename = os.path.split(file)
        print(filename)
        new_filename = f_path + new_name + str(count + 1) + ".ma"
        os.rename(f_path+filename[1], new_filename)
        print(new_filename)
        count = count + 1

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Mockito: InvalidUseOfMatchersException

Inspite of using all the matchers, I was getting the same issue:

"org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 3 recorded:"

It took me little while to figure this out that the method I was trying to mock was a static method of a class(say Xyz.class) which contains only static method and I forgot to write following line:

PowerMockito.mockStatic(Xyz.class);

May be it will help others as it may also be the cause of the issue.

Count the number of occurrences of a string in a VARCHAR field?

In SQL SERVER, this is the answer

Declare @t table(TITLE VARCHAR(100), DESCRIPTION VARCHAR(100))

INSERT INTO @t SELECT 'test1', 'value blah blah value' 
INSERT INTO @t SELECT 'test2','value test' 
INSERT INTO @t SELECT 'test3','test test test' 
INSERT INTO @t SELECT 'test4','valuevaluevaluevaluevalue' 


SELECT TITLE,DESCRIPTION,Count = (LEN(DESCRIPTION) - LEN(REPLACE(DESCRIPTION, 'value', '')))/LEN('value') 

FROM @t

Result

TITLE   DESCRIPTION               Count
test1   value blah blah value        2
test2   value test                   1
test3   test test test               0
test4   valuevaluevaluevaluevalue    5

I don't have MySQL install, but goggled to find the Equivalent of LEN is LENGTH while REPLACE is same.

So the equivalent query in MySql should be

SELECT TITLE,DESCRIPTION, (LENGTH(DESCRIPTION) - LENGTH(REPLACE(DESCRIPTION, 'value', '')))/LENGTH('value') AS Count
FROM <yourTable>

Please let me know if it worked for you in MySql also.

TestNG ERROR Cannot find class in classpath

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION

java -cp "path_copied" org.testng.TestNG testng.xml

If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

How to Detect Browser Window /Tab Close Event?

Solution Posted Here

After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser. Hence, i observed that there will be very little time delay between closing the tabs. So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.

//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});

JSFiddle Link

Can I change the fill color of an svg path with CSS?

Put in all your svg:

fill="var(--svgcolor)"

In Css:

:root {
  --svgcolor: tomato;
}

To use pseudo-classes:

span.github:hover {
  --svgcolor:aquamarine;
}

Explanation

root = html page.
--svgcolor = a variable.
span.github = selecting a span element with a class github, a svg icon inside and assigning pseudo-class hover.

How to specify an element after which to wrap in css flexbox?

The only thing that appears to work is to set flex-wrap: wrap; on the container and them somehow make the child you want to break out after to fill the full width, so width: 100%; should work.

If, however, you can't stretch the element to 100% (for example, if it's an <img>), you can apply a margin to it, like width: 50px; margin-right: calc(100% - 50px).

How to get current local date and time in Kotlin

Another solution is changing the api level of your project in build.gradle and this will work.

Force browser to download image files on click

In 2020 I use Blob to make local copy of image, which browser will download as a file. You can test it on this site.

enter image description here

(function(global) {
  const next = () => document.querySelector('.search-pagination__button-text').click();
  const uuid = () => Math.random().toString(36).substring(7);
  const toBlob = (src) => new Promise((res) => {
    const img = document.createElement('img');
    const c = document.createElement("canvas");
    const ctx = c.getContext("2d");
    img.onload = ({target}) => {
      c.width = target.naturalWidth;
      c.height = target.naturalHeight;
      ctx.drawImage(target, 0, 0);
      c.toBlob((b) => res(b), "image/jpeg", 0.75);
    };
    img.crossOrigin = "";
    img.src = src;
  });
  const save = (blob, name = 'image.png') => {
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.target = '_blank';
    a.download = name;
    a.click();
  };
  global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
  global.next = () => next();
})(window);

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

If you have multiple projects in your solution, then right-click on the solution icon in Visual Studio and select 'Manage NuGet Packages for Solution', then click on the fourth tab 'Consolidate' to consolidate all your projects to the same version of the DLLs. This will give you a list of referenced assemblies to consolidate. Click on each item in the list, then click install in the tab that appears to the right.

How to get method parameter names?

What about dir() and vars() now?

Seems doing exactly what is being asked super simply…

Must be called from within the function scope.

But be wary that it will return all local variables so be sure to do it at the very beginning of the function if needed.

Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.

How to correctly save instance state of Fragments in back stack?

This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.

public final class MyFragment extends Fragment {
    private TextView vstup;
    private Bundle savedState = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.whatever, null);
        vstup = (TextView)v.findViewById(R.id.whatever);

        /* (...) */

        /* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
        /* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle(App.STAV);
        }
        if(savedState != null) {
            vstup.setText(savedState.getCharSequence(App.VSTUP));
        }
        savedState = null;

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState(); /* vstup defined here for sure */
        vstup = null;
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence(App.VSTUP, vstup.getText());
        return state;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
        /* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
        /* => (?:) operator inevitable! */
        outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
    }

    /* (...) */

}

Alternatively, it is always a possibility to keep the data displayed in passive Views in variables and using the Views only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

Displaying the build date

Regarding the technique of pulling build date/version info from the bytes of an assembly PE header, Microsoft has changed the default build parameters beginning with Visual Studio 15.4. The new default includes deterministic compilation, which makes a valid timestamp and automatically incremented version numbers a thing of the past. The timestamp field is still present but it gets filled with a permanent value that is a hash of something or other, but not any indication of the build time.

Some detailed background here

For those who prioritize a useful timestamp over deterministic compilation, there is a way to override the new default. You can include a tag in the .csproj file of the assembly of interest as follows:

  <PropertyGroup>
      ...
      <Deterministic>false</Deterministic>
  </PropertyGroup>

Update: I endorse the T4 text template solution described in another answer here. I used it to solve my issue cleanly without losing the benefit of deterministic compilation. One caution about it is that Visual Studio only runs the T4 compiler when the .tt file is saved, not at build time. This can be awkward if you exclude the .cs result from source control (since you expect it to be generated) and another developer checks out the code. Without resaving, they won't have the .cs file. There is a package on nuget (I think called AutoT4) that makes T4 compilation part of every build. I have not yet confronted the solution to this during production deployment, but I expect something similar to make it right.

How do I programmatically force an onchange event on an input?

Taken from the bottom of QUnit

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
        elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

To use this function:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

How to finish Activity when starting other activity in Android?

You need to intent your current context to another activity first with startActivity. After that you can finish your current activity from where you redirect.

 Intent intent = new Intent(this, FirstActivity.class);// New activity
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 finish(); // Call once you redirect to another activity

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.

Method has the same erasure as another method in type

This is because Java Generics are implemented with Type Erasure.

Your methods would be translated, at compile time, to something like:

Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)

void add(Set ii);
void add(Set ss);

Both methods have the same signature without the type parameters, hence the error.

How to exit from ForEach-Object in PowerShell

There are differences between foreach and foreach-object.

A very good description you can find here: MS-ScriptingGuy

For testing in PS, here you have scripts to show the difference.

ForEach-Object:

# Omit 5.
1..10 | ForEach-Object {
if ($_ -eq 5) {return}
# if ($_ -ge 5) {return} # Omit from 5.
Write-Host $_
}
write-host "after1"
# Cancels whole script at 15, "after2" not printed.
11..20 | ForEach-Object {
if ($_ -eq 15) {continue}
Write-Host $_
}
write-host "after2"
# Cancels whole script at 25, "after3" not printed.
21..30 | ForEach-Object {
if ($_ -eq 25) {break}
Write-Host $_
}
write-host "after3"

foreach

# Ends foreach at 5.
foreach ($number1 in (1..10)) {
if ($number1 -eq 5) {break}
Write-Host "$number1"
}
write-host "after1"
# Omit 15. 
foreach ($number2 in (11..20)) {
if ($number2 -eq 15) {continue}
Write-Host "$number2"
}
write-host "after2"
# Cancels whole script at 25, "after3" not printed.
foreach ($number3 in (21..30)) {
if ($number3 -eq 25) {return}
Write-Host "$number3"
}
write-host "after3"

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

This fixed node.js not running on port 80 under Windows 10 as well, I was getting a listen eacces error. Start > Services, find "World Wide Web Publish Service" and disable it, exactly as paaacman described.

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Just set the JDK path from the below steps:

  1. Go to 'Run' ->External Tools -> External Tools Configuration

  2. -> Select 'JRE' Then from the DropDown list select the available JDK . ex. jdk1.8.0_25

PHP - Indirect modification of overloaded property

This is occurring due to how PHP treats overloaded properties in that they are not modifiable or passed by reference.

See the manual for more information regarding overloading.

To work around this problem you can either use a __set function or create a createObject method.

Below is a __get and __set that provides a workaround to a similar situation to yours, you can simply modify the __set to suite your needs.

Note the __get never actually returns a variable. and rather once you have set a variable in your object it no longer is overloaded.

/**
 * Get a variable in the event.
 *
 * @param  mixed  $key  Variable name.
 *
 * @return  mixed|null
 */
public function __get($key)
{
    throw new \LogicException(sprintf(
        "Call to undefined event property %s",
        $key
    ));
}

/**
 * Set a variable in the event.
 *
 * @param  string  $key  Name of variable
 *
 * @param  mixed  $value  Value to variable
 *
 * @return  boolean  True
 */
public function __set($key, $value)
{
    if (stripos($key, '_') === 0 && isset($this->$key)) {
        throw new \LogicException(sprintf(
            "%s is a read-only event property", 
            $key
        ));
    }
    $this->$key = $value;
    return true;
}

Which will allow for:

$object = new obj();
$object->a = array();
$object->a[] = "b";
$object->v = new obj();
$object->v->a = "b";

CSS Flex Box Layout: full-width row and columns

Just use another container to wrap last two divs. Don't forget to use CSS prefixes.

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
   display: flex;_x000D_
   flex-direction: column;_x000D_
   height: 600px;_x000D_
   width: 580px;_x000D_
   background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
   height: 100px;_x000D_
   background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
   display: flex;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
   background-color: red;_x000D_
   flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
   background-color: blue;_x000D_
   flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
   <div id="productShowcaseTitle">1</div>_x000D_
   <div id="anotherContainer">_x000D_
      <div id="productShowcaseDetail">2</div>_x000D_
      <div id="productShowcaseThumbnailContainer">3</div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

npm global path prefix

Extending your PATH with:

export PATH=/usr/local/share/npm/bin:$PATH

isn't a terrible idea. Having said that, you shouldn't have to do it.

Run this:

npm config get prefix

The default on OS X is /usr/local, which means that npm will symlink binaries into /usr/local/bin, which should already be on your PATH (especially if you're using Homebrew).

So:

  1. npm config set prefix /usr/local if it's something else, and
  2. Don't use sudo with npm! According to the jslint docs, you should just be able to npm install it.

If you installed npm as sudo (sudo brew install), try reinstalling it with plain ol' brew install. Homebrew is supposed to help keep you sudo-free.

Gitignore not working

@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests

step 1

add filename to .gitignore file

step 2

[remove filename (file path) from git cache

git rm --cached filename

setp 3

commit changes git add filename

git commit -m "add filename to .gitignore"

it will keep your git history clean because if you do git rm -r --cached . and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the point

HTML: How to make a submit button with text + image in it?

You can do this:

HTML code:

    <form action="submit.php" method="get" id="form">        
    <a href="javascript: submitForm()">        
    <img src="save.gif" alt="Save icon"/>        
    <br/>        
    save        
    </a>        
    </form>        

note: you can use and action and method of your choice and Id and any text starting from href="javascript: and ending to ()" but make sure that when I type the same things such as id and some text you type in your replacement in the same places(java script and HTML code).

java script code:

    var form=document.getElementById("form");        
    function submitForm()        
    {        
    form.submit();       
    }         

Can I set subject/content of email using mailto:?

I split it into separate lines to make it a little more readable.

<a href="

    mailto:[email protected]

    ?subject=My+great+email+to+you

    &body=This+is+an+awesome+email

    &[email protected]

    &[email protected]

">Click here to send email!</a>

How to prevent column break within an element?

set following to the style of the element that you don't want to break:

overflow: hidden; /* fix for Firefox */
break-inside: avoid-column;
-webkit-column-break-inside: avoid;

SQL - Query to get server's IP address

SELECT  
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address 

The code here Will give you the IP Address;

This will work for a remote client request to SQL 2008 and newer.

If you have Shared Memory connections allowed, then running above on the server itself will give you

  • "Shared Memory" as the value for 'net_transport', and
  • NULL for 'local_net_address', and
  • '<local machine>' will be shown in 'client_net_address'.

'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.

I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.

AngularJS Error: $injector:unpr Unknown Provider

I was getting this problem and it turned out I had included my controller both in ui.router and in the html template as in

.config(['$stateProvider',
  function($stateProvider) {
    $stateProvider.state('dashboard', {
      url: '/dashboard',
      templateUrl: 'dashboard/views/index.html',
      controller: 'DashboardController'
    });
  }
]);

and

<section data-ng-controller="DashboardController">

How to send POST in angularjs with multiple params?

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).

Reverting single file in SVN to a particular revision

You want to do

svn merge -r [revision to revert from]:[revision to revert to] [path/filename]

Once you do that, you will have that revision of the file in a committable state. Commit the file.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

Open Bootstrap Modal from code-behind

By default Bootstrap javascript files are included just before the closing body tag

        <script src="vendors/jquery-1.9.1.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
        <script src="assets/scripts.js"></script>
 </body>

I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:

    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
    <script src="assets/scripts.js"></script>

 <script type="text/javascript">
    function openModal() {
        $('#myModal').modal('show');
    }
</script>
</head>
<body>

then I could call the modal popup from code-behind with the following:

protected void lbEdit_Click(object sender, EventArgs e) {   
      ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}

Convert hex color value ( #ffffff ) to integer value

Get Shared Preferences Color Code in String then Convert to integer and add layout-background color:

    sharedPreferences = getSharedPreferences(mypref, Context.MODE_PRIVATE);
    String sw=sharedPreferences.getString(name, "");
    relativeLayout.setBackgroundColor(Color.parseColor(sw));

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

Since you are setting the layout explicitly you might want to try and put it in the default /layout folder not in the /layout-land since that is if you want Android to automatically handle rotation for you.

Why can't DateTime.Parse parse UTC date

Assuming you use the format "o" for your datetime so you have "2016-07-24T18:47:36Z", there is a very simple way to handle this.

Call DateTime.Parse("2016-07-24T18:47:36Z").ToUniversalTime().

What happens when you call DateTime.Parse("2016-07-24T18:47:36Z") is you get a DateTime set to the local timezone. So it converts it to the local time.

The ToUniversalTime() changes it to a UTC DateTime and converts it back to UTC time.

Amazon AWS Filezilla transfer permission denied

for me below worked:

chown -R ftpusername /var/app/current

How to call another components function in angular2

  1. Add injectable decorator to component2(or any component which have the method)
@Injectable({
    providedIn: 'root'
})
  1. Inject into component1 (the component from where component2 method will be called)
constructor(public comp2 : component2) { }
  1. Define method in component1 from where component2 method is called
method1()
{
    this.comp2.method2();
}

component 1 and component 2 code below.

import {Component2} from './Component2';

@Component({
  selector: 'sel-comp1',
  templateUrl: './comp1.html',
  styleUrls: ['./comp1.scss']
})
export class Component1 implements OnInit {
  show = false;
  constructor(public comp2: Component2) { }
method1()
 {
   this.comp2.method2(); 
  }
}


@Component({
  selector: 'sel-comp2',
  templateUrl: './comp2.html',
  styleUrls: ['./comp2.scss']
})
export class Component2 implements OnInit {
  method2()
{
  alert('called comp2 method from comp1');
}

How to generate an MD5 file hash in JavaScript?

You can use a lightweight library pure-md5. Just a 4.7kb.

_x000D_
_x000D_
$("#file-dialog").change(function() {_x000D_
  handleFiles(this.files);_x000D_
});_x000D_
_x000D_
function handleFiles(files) {_x000D_
  for (var index = 0; index < files.length; index++) {_x000D_
    var file = files[index];_x000D_
    var fileReader = new FileReader();_x000D_
    fileReader.onload = function(e) {_x000D_
      $('body').append(`_x000D_
        <div style="margin-top: 2rem;">_x000D_
          <span>${file.name}: </span>_x000D_
          <span>${(md5(e.target.result))}</span>_x000D_
        </div>_x000D_
      `);_x000D_
    }_x000D_
_x000D_
    fileReader.readAsText(file, 'utf-8');_x000D_
  }_x000D_
_x000D_
}
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/lib/index.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="file" id="file-dialog" multiple="true" accept="image/*">
_x000D_
_x000D_
_x000D_

What does "implements" do on a class?

An interface can be thought of as just a list of method definitions (without any body). If a class wants to implement and interface, it is entering into a contract, saying that it will provide an implementation for all of the methods listed in the interface. For more information, see http://download.oracle.com/javase/tutorial/java/concepts/

Bulk Insert Correctly Quoted CSV File in SQL Server

Been stung by the same :)

I wrapped this logic into a function to clean up data that had been was already imported

DECLARE @str NVARCHAR(MAX);
DECLARE @quote_identifier NVARCHAR(MAX);

SET @quote_identifier = N'"';

SET @str = N'"quoted stuff"';

SELECT IIF(
           LEFT(@str, 1) = @quote_identifier
           AND RIGHT(@str, 1) = @quote_identifier,
           SUBSTRING(@str, DATALENGTH(@quote_identifier), LEN(@str) - DATALENGTH(@quote_identifier)),
           @str);

PHP Checking if the current date is before or after a set date

if (strtotime($date) > mktime(0,0,0)) should do the job.

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

UPDATE 2014-11-14: The solution below is too old, I recommend using flex box layout method. Here is a overview: http://learnlayout.com/flexbox.html


My solution

html

<li class="grid-list-header row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

<li class="grid-list-item row-cw row-cw-msg-list ...">
  <div class="col-md-1 col-cw col-cw-name">
  <div class="col-md-1 col-cw col-cw-keyword">
  <div class="col-md-1 col-cw col-cw-reply">
  <div class="col-md-1 col-cw col-cw-action">
</li>

scss

.row-cw {
  position: relative;
}

.col-cw {
  position: absolute;
  top: 0;
}


.ir-msg-list {

  $col-reply-width: 140px;
  $col-action-width: 130px;

  .row-cw-msg-list {
    padding-right: $col-reply-width + $col-action-width;
  }

  .col-cw-name {
    width: 50%;
  }

  .col-cw-keyword {
    width: 50%;
  }

  .col-cw-reply {
    width: $col-reply-width;
    right: $col-action-width;
  }

  .col-cw-action {
    width: $col-action-width;
    right: 0;
  }
}

Without modify too much bootstrap layout code.


Update (not from OP): adding code snippet below to facilitate understanding of this answer. But it doesn't seem to work as expected.

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
.row-cw {_x000D_
  position: relative;_x000D_
  height: 20px;_x000D_
}_x000D_
.col-cw {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  background-color: rgba(150, 150, 150, .5);_x000D_
}_x000D_
.row-cw-msg-list {_x000D_
  padding-right: 270px;_x000D_
}_x000D_
.col-cw-name {_x000D_
  width: 50%;_x000D_
  background-color: rgba(150, 0, 0, .5);_x000D_
}_x000D_
.col-cw-keyword {_x000D_
  width: 50%;_x000D_
  background-color: rgba(0, 150, 0, .5);_x000D_
}_x000D_
.col-cw-reply {_x000D_
  width: 140px;_x000D_
  right: 130px;_x000D_
  background-color: rgba(0, 0, 150, .5);_x000D_
}_x000D_
.col-cw-action {_x000D_
  width: 130px;_x000D_
  right: 0;_x000D_
  background-color: rgba(150, 150, 0, .5);_x000D_
}
_x000D_
<ul class="ir-msg-list">_x000D_
  <li class="grid-list-header row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
_x000D_
  <li class="grid-list-item row-cw row-cw-msg-list">_x000D_
    <div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
    <div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
    <div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
    <div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to get the containing form of an input?

Every input has a form property which points to the form the input belongs to, so simply:

function doSomething(element) {
  var form = element.form;
}

How do I POST an array of objects with $.ajax (jQuery or Zepto)

I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.

First I stringify the data as

var myData = [];
   allData.forEach((x, index) => {
         // console.log(index);
         myData.push(JSON.stringify({
         "product_id" : x.product_id,
         "product" : x.product,
         "url" : x.url,
         "image_url" : x.image_url,
         "price" : x.price,
         "source": x.source
      }))
   })

Then I sent it like

$.ajax({
        url: '{% url "url_name" %}',
        method: "POST",
        data: {
           'csrfmiddlewaretoken': '{{ csrf_token }}',
           'queryset[]': myData
        },
        success: (res) => {
        // success post work here.
    }
})

And received as :

list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]

Using unset vs. setting a variable to empty

As has been said, using unset is different with arrays as well

$ foo=(4 5 6)

$ foo[2]=

$ echo ${#foo[*]}
3

$ unset foo[2]

$ echo ${#foo[*]}
2

Create a basic matrix in C (input by user !)

You need to dynamically allocate your matrix. For instance:

int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));

This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Log4net does not write the log in the log file

Make sure the process (account) that the site is running under has privileges to write to the output directory.

In IIS 7 and above this is configured on the application pool and is normally the AppPool Identity, which will not normally have permission to write to all directories.

Check your event logs (application and security) to see if any exceptions were thrown.

mysql update column with value from another table

you need to join the two tables:

for instance you want to copy the value of name from tableA into tableB where they have the same ID

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.id = t2.id
SET t1.name = t2.name 
WHERE t2.name = 'Joe'

UPDATE 1

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.id = t2.id
SET t1.name = t2.name 

UPDATE 2

UPDATE tableB t1 
        INNER JOIN tableA t2 
             ON t1.name = t2.name
SET t1.value = t2.value

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Using Ionic with Cordova via command line...

ionic cordova run android --prod

I ran into this and found that I had deleted the release version from a previous test install, but had an old debug version that was hanging out in apps drawer that I missed. I unplugged my device from the computer, opened the app drawer and used "Search apps.." to find all instances of the app to uninstall them. Then I re-plugged in the device to the computer and viola, it worked!

Thanks for the help everyone!

What's the difference between `raw_input()` and `input()` in Python 3?

The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). (Remember that eval() is evil. Try to use safer ways of parsing your input if possible.)

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I had this problem but didn't have a version conflict in my package.json.

My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.