# Programs & Examples On #C89

This tag is for questions regarding the international standard ISO 9899:1990, also known as "C89", "C90" or "ANSI C", with amendments and technical corrigenda (as opposed to K&R C, C99, C11 or later C standard revisions).

### What is the behavior of integer division?

Will result always be the floor of the division?

No. The result varies, but variation happens only for negative values.

What is the defined behavior?

To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)

For positive values they are the same

int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0


For negative value this is different

int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0


### C: convert double to float, preserving decimal point precision

float and double don't store decimal places. They store binary places: float is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).

Converting from double to float will give you the closest possible float, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.

#include <stdio.h>

int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}


To get a double approximation to the nice decimal value you intended, you can write something like:

double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}


### Why should you use strncpy instead of strcpy?

While I know the intent behind strncpy, it is not really a good function. Avoid both. Raymond Chen explains.

Personally, my conclusion is simply to avoid strncpy and all its friends if you are dealing with null-terminated strings. Despite the "str" in the name, these functions do not produce null-terminated strings. They convert a null-terminated string into a raw character buffer. Using them where a null-terminated string is expected as the second buffer is plain wrong. Not only do you fail to get proper null termination if the source is too long, but if the source is short you get unnecessary null padding.

### How do I remove all .pyc files from a project?

if you don't want .pyc anymore you can use this single line in a terminal:

export PYTHONDONTWRITEBYTECODE=1


unset PYTHONDONTWRITEBYTECODE


### Can I set text box to readonly when using Html.TextBoxFor?

This work for me...

@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = "readonly" })


### cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;


value is now 9.

I suggest you read more about pointers, this is their base functionality.

### Clearing <input type='file' /> using jQuery

I tried with the most of the techniques the users mentioned, but none of they worked in all browsers. i.e: clone() doesn't work in FF for file inputs. I ended up copying manually the file input, and then replacing the original with the copied one. It works in all browsers.

<input type="file" id="fileID" class="aClass" name="aName"/>

var $fileInput=$("#fileID");
var $fileCopy=$("<input type='file' class='"+$fileInput.attr("class")+" id='fileID' name='"+$fileInput.attr("name")+"'/>");
$fileInput.replaceWith($fileCopy);


### 'pip install' fails for every package ("Could not find a version that satisfies the requirement")

curl https://bootstrap.pypa.io/get-pip.py | python


Note: You may need to use sudo python above if not in a virtual environment.

#### What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python


and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools


### What is the difference between smoke testing and sanity testing?

#### Sanity testing

Sanity testing is the subset of regression testing and it is performed when we do not have enough time for doing testing.

Sanity testing is the surface level testing where QA engineer verifies that all the menus, functions, commands available in the product and project are working fine.

#### Example

Suppose we have a bug in the login page: the login page's username field accepts usernames which are shorter than 6 alphanumeric characters, and this is against the requirements, as in the requirements it is specified that the username should be at least 6 alphanumeric characters.

Now the bug is reported by the testing team to the developer team to fix it. After the developing team fixes the bug and passes the app to the testing team, the testing team also checks the other modules of the application in order to verify that the bug fix does not affect the functionality of the other modules. But keep one point always in mind: the testing team only checks the extreme functionality of the modules, it does not go deep to test the details because of the short time.

Sanity testing is performed after the build has cleared the smoke tests and has been accepted by QA team for further testing. Sanity testing checks the major functionality with finer details.

Sanity testing is performed when the development team needs to know quickly the state of the product after they have done changes in the code, or there is some controlled code changed in a feature to fix any critical issue, and stringent release time-frame does not allow complete regression testing.

#### Smoke testing

Smoke Testing is performed after a software build to ascertain that the critical functionalities of the program are working fine. It is executed "before" any detailed functional or regression tests are executed on the software build.

The purpose is to reject a badly broken application, so that the QA team does not waste time installing and testing the software application.

In smoke testing, the test cases chosen cover the most important functionalities or components of the system. The objective is not to perform exhaustive testing, but to verify that the critical functionalities of the system are working fine. For example, typical smoke tests would be:

• verify that the application launches successfully,
• Check that the GUI is responsive

### How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

• keydown
• keypress
• keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

• textInput

See for more details .. http://unixpapa.com/js/key.html

### What is the best open source help ticket system?

I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).

### Convert double to Int, rounded down

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

### Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'


Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

### How to scanf only integer?

If you're set on using scanf, you can do something like the following:

int val;
char follow;

if ( read == 2 )
{
if ( isspace( follow ) )
{
// input is an integer followed by whitespace, accept
}
else
{
// input is an integer followed by non-whitespace, reject
}
}
else if ( read == 1 )
{
// input is an integer followed by EOF, accept
}
else
{
// input is not an integer, reject
}


### How to concatenate two numbers in javascript?

var value = "" + 5 + 6;


### How to stop a JavaScript for loop?

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
if (ele > 3) break;
console.log(ele);
}


### How to use global variables in React Native?

If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate method like this:

<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />

and in 'NextScreen' you can access them with the navigation.getParam() method:

let foo=this.props.navigation.getParam(foo);

But it can get really "messy" if you have more than a couple of variables to pass..

### Two column div layout with fluid left and fixed right column

The following examples are source ordered i.e. column 1 appears before column 2 in the HTML source. Whether a column appears on left or right is controlled by CSS:

Fixed Right

_x000D_
_x000D_
#wrapper {_x000D_
margin-right: 200px;_x000D_
}_x000D_
#content {_x000D_
float: left;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: right;_x000D_
width: 200px;_x000D_
margin-right: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fixed Left

_x000D_
_x000D_
#wrapper {_x000D_
margin-left: 200px;_x000D_
}_x000D_
#content {_x000D_
float: right;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: left;_x000D_
width: 200px;_x000D_
margin-left: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternate solution is to use display: table-cell; which results in equal height columns.

### jQuery function after .append

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root') .append(html) .ready(function () { // enter code here });  ### The R %in% operator You can use all > all(1:6 %in% 0:36) [1] TRUE > all(1:60 %in% 0:36) [1] FALSE  On a similar note, if you want to check whether any of the elements is TRUE you can use any > any(1:6 %in% 0:36) [1] TRUE > any(1:60 %in% 0:36) [1] TRUE > any(50:60 %in% 0:36) [1] FALSE  ### MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client Check privileges and username/password for your MySQL user. For catching errors it is always useful to use overrided _delegateError method. In your case this has to look like: var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "password", insecureAuth : true }); var _delegateError = con._protocol._delegateError; con._protocol._delegateError = function(err, sequence) { if (err.fatal) console.trace('MySQL fatal error: ' + err.message); return _delegateError.call(this, err, sequence); }; con.connect(function(err) { if (err) throw err; console.log("Connected!"); });  This construction will help you to trace fatal errors. ### Unpivot with column name You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps: 1. create multiple copies for each row using cross join (also creating subject column in this case) 2. create column "marks" and fill in relevant values using case expression ( ex: if subject is science then pick value from science column) 3. remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)  select * from ( select name, subject, case subject when 'Maths' then maths when 'Science' then science when 'English' then english end as Marks from studentmarks Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject) )as D where marks is not null;  ### C++: what regex library should I use? Boost has regex in it. That should fill the bill ### TypeScript function overloading #### Function overloading in typescript: According to Wikipedia, (and many programming books) the definition of method/function overloading is the following: In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context. In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics: • JavaScript function definitions do not specify data types for their parameters • JavaScript functions do not check the number of arguments when called Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading. Here is an example: function add(a: number, b: number, c: number): number; function add(a: number, b: number): any; function add(a: string, b: string): any; function add(a: any, b: any, c?: any): any { if (c) { return a + c; } if (typeof a === 'string') { return a is${a}, b is ${b}; } else { return a + b; } }  The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly. ### Where to find 64 bit version of chromedriver.exe for Selenium WebDriver? There is no separate 64-bit version of Chromedriver. The version available at https://sites.google.com/a/chromium.org/chromedriver/downloads works on both 32 and 64-bit Windows, against either 32-or 64-bit Chrome. This was confirmed in the Chromedriver issue tracker: https://bugs.chromium.org/p/chromedriver/issues/detail?id=1797#c1 Yes, Chromedriver works on 64-bit Windows and against 64-bit Chrome successfully. I came here while searching for the answer to if it works on 64-bit Chrome following the announcement that from version 58 Chrome will default to 64-bit on Windows provided certain conditions are met: https://chromereleases.googleblog.com/2017/05/stable-channel-update-for-desktop.html In order to improve stability, performance, and security, users who are currently on 32-bit version of Chrome, and 64-bit Windows with 4GB or more of memory and auto-update enabled will be automatically migrated to 64-bit Chrome during this update. 32-bit Chrome will still be available via the Chrome download page. ### Align image in center and middle within div A simple way would be creating separate styles for both the div and the image and then position them independently. Say if I want to set my image position to 50%, then I would have code which looks like the following.... _x000D_ _x000D_ #over{_x000D_ position:absolute;_x000D_ width:100%;_x000D_ height:100%;_x000D_ }_x000D_ #img{_x000D_ position:absolute;_x000D_ left:50%;_x000D_ right:50%;_x000D_ } _x000D_ <div id="over">_x000D_ <img src="img.png" id="img">_x000D_ </div> _x000D_ _x000D_ _x000D_ ### Easy way to use variables of enum types as string in C? Because I prefer not to use macros for all the usual reasons, I used a more limited macro solution that has the advantage of keeping the enum declaration macro free. Disadvantages include having to copy paste the macro defintion for each enum, and having to explicitly add a macro invocation when adding values to the enum. std::ostream& operator<<(std::ostream& os, provenance_wrapper::CaptureState cs) { #define HANDLE(x) case x: os << #x; break; switch (cs) { HANDLE(CaptureState::UNUSED) HANDLE(CaptureState::ACTIVE) HANDLE(CaptureState::CLOSED) } return os; #undef HANDLE }  ### Animated GIF in IE stopping I realize that this is an old question and that by now the original posters have each found a solution that works for them, but I ran across this issue and found that VML tags do not fall victim to this IE bug. Animated GIFs still move during page unload when placed on the IE browser using VML tags. Notice I detected VML first before making the decision to use VML tags so this is working in FireFox and other browsers using normal animated GIF behavior. Here's how I solved this. <input class="myExitButton" type="button" value="Click me" /> <div class="loadingNextPage" style="display:none" > <span style="left:-24px; POSITION: relative; WIDTH: 48px; DISPLAY: inline-block; HEIGHT: 48px" class="spinnerImageVml"><?xml:namespace prefix="rvml" ns = "urn:schemas-microsoft-com:vml" /><rvml:group style="POSITION: absolute; WIDTH: 48px; HEIGHT: 48px; rotation: 1deg" class="rvml" coordsize = "47,47"><rvml:image style="POSITION: absolute; WIDTH: 48px; HEIGHT: 48px; TOP: 0px; LEFT: 0px" class="rvml" src="/images/loading_gray.gif" coordsize="21600,21600"></rvml:image></rvml:group></span> <img class="spinnerImage" src="/images/loading_gray.gif" alt="loading..." /> <div>Just one moment while we access this information...</div> </div> <script language="javascript" type="text/javascript"> window.LoadProgress = (function (progress,$) {

var getdialogHeight = function (height) {
var isIE = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
if (isIE) {
return height + 'px';
}
return height;
};

var isVmlSupported = function () {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
var supported = b ? typeof b.adj == "object" : true;
a.parentNode.removeChild(a);
return supported;
};

var showAnimationDuringPageUnload = function () {
if (isVmlSupported()) {
$(".loadingNextPage > .spinnerImage").hide(); } else {$(".loadingNextPage > .spinnerImageVml").hide();
}
};

$(".loadingNextPage").dialog({ modal: true, closeOnEscape: true, title: 'Please wait...', closeText: 'x', height: getdialogHeight(200), buttons: { "Close": function () {$(this).dialog("close");
}
}
});
};

$('.myExitButton').click(function () { openLoadingMessage(); showAnimationDuringPageUnload(); window.location.href = 'http://www.stackoverflow.com'; }); return progress; })(window.LoadProgress || {}, window.jQuery); </script>  Naturally, this relies on jQuery, jQueryUI and requires an animated GIF of some type ("/images/loading_gray.gif"). ### In PHP with PDO, how to check the final SQL parametrized query? I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9): Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges: SET GLOBAL general_log = 'ON';  In a terminal, tail your log file. Mine was here: >sudo tail -f /usr/local/mysql/data/myMacComputerName.log  You can search for your mysql files with this terminal command: >ps auxww|grep [m]ysqld  I found that PDO escapes everything, so you can't write $dynamicField = 'userName';
$sql = "SELECT * FROM example WHERE :field = :value";$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field',$dynamicField);
$this->statement->bindValue(':value', 'mick');$this->statement->execute();


Because it creates:

SELECT * FROM example WHERE 'userName' = 'mick' ;


Which did not create an error, just an empty result. Instead I needed to use

$sql = "SELECT * FROM example WHERE $dynamicField = :value";


to get

SELECT * FROM example WHERE userName = 'mick' ;


When you are done execute:

SET GLOBAL general_log = 'OFF';


or else your logs will get huge.

### What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics. ### Android : change button text and background color Here is an example of a drawable that will be white by default, black when pressed: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape> <solid android:color="#1E669B"/> <stroke android:width="2dp" android:color="#1B5E91"/> <corners android:radius="6dp"/> <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/> </shape> </item> <item> <shape> <gradient android:angle="270" android:endColor="#1E669B" android:startColor="#1E669B"/> <stroke android:width="4dp" android:color="#1B5E91"/> <corners android:radius="7dp"/> <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/> </shape> </item> </selector>  ### How to set breakpoints in inline Javascript in Google Chrome? This is an extension of Rian Schmits' answer above. In my case, I had HTML code embedded in my JavaScript code and I couldn't see anything other than the HTML code. Maybe Chrome Debugging has changed over the years but right-clicking the Sources/Sources tab presented me with Add folder to workspace. I was able to add my entire project, which gave me access to all of my JavaScripts. You can find more detail in this link. I hope this helps somebody. ### Automatic date update in a cell when another cell's value changes (as calculated by a formula) You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput. Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook). EDIT: Here is some code: For the UDF:  Public Function UDF_Date(ByVal data) As Date UDF_Date = Now() End Function  As Formula in D2: =UDF_Date(C2)  You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value. And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative. Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called. Addendum: Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that: • The usage of the UDF is the same as described above. • The UDF works only for single cell input ranges. • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point. • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost. • The code might brake for cell-values for which conversion to string is non-deterministic. • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk. Public Function UDF_Date(ByVal inData As Range) As Date Dim wb As Workbook Dim dProps As DocumentProperties Dim pValue As DocumentProperty Dim pDate As DocumentProperty Dim sName As String Dim sNameDate As String Dim bDate As Boolean Dim bValue As Boolean Dim bChanged As Boolean bDate = True bValue = True bChanged = False Dim sVal As String Dim dDate As Date sName = inData.Address & "_" & inData.Worksheet.Name sNameDate = sName & "_dat" sVal = CStr(inData.Value) dDate = Now() Set wb = inData.Worksheet.Parent Set dProps = wb.CustomDocumentProperties On Error Resume Next Set pValue = dProps.Item(sName) If Err.Number <> 0 Then bValue = False Err.Clear End If On Error GoTo 0 If Not bValue Then bChanged = True Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal) Else bChanged = pValue.Value <> sVal If bChanged Then pValue.Value = sVal End If End If On Error Resume Next Set pDate = dProps.Item(sNameDate) If Err.Number <> 0 Then bDate = False Err.Clear End If On Error GoTo 0 If Not bDate Then Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate) End If If bChanged Then pDate.Value = dDate Else dDate = pDate.Value End If UDF_Date = dDate End Function  Make the insertion of the date conditional upon the range. This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes. Adapted from this tip and @Paul S answer Private Sub Worksheet_Change(ByVal Target As Range) Dim R1 As Range Dim R2 As Range Dim InRange As Boolean Set R1 = Range(Target.Address) Set R2 = Range("C2:C20") Set InterSectRange = Application.Intersect(R1, R2) InRange = Not InterSectRange Is Nothing Set InterSectRange = Nothing If InRange = True Then R1.Offset(0, 1).Value = Now() End If Set R1 = Nothing Set R2 = Nothing End Sub  ### How do I find the width & height of a terminal window? In bash, the $LINES and $COLUMNS environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the SIGWINCH signal) ### Angular 2 Sibling Component Communication Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service. Here would be the service: import {Injectable} from '@angular/core'; @Injectable() export class SharedService { dataArray: string[] = []; insertData(data: string){ this.dataArray.unshift(data); } }  Now, here would be the PARENT component import {Component} from '@angular/core'; import {SharedService} from './shared.service'; import {ChildComponent} from './child.component'; import {ChildSiblingComponent} from './child-sibling.component'; @Component({ selector: 'parent-component', template:  <h1>Parent</h1> <div> <child-component></child-component> <child-sibling-component></child-sibling-component> </div> , providers: [SharedService], directives: [ChildComponent, ChildSiblingComponent] }) export class parentComponent{ }  and its two children child 1 import {Component, OnInit} from '@angular/core'; import {SharedService} from './shared.service' @Component({ selector: 'child-component', template:  <h1>I am a child</h1> <div> <ul *ngFor="#data in data"> <li>{{data}}</li> </ul> </div>  }) export class ChildComponent implements OnInit{ data: string[] = []; constructor( private _sharedService: SharedService) { } ngOnInit():any { this.data = this._sharedService.dataArray; } }  child 2 (It's sibling) import {Component} from 'angular2/core'; import {SharedService} from './shared.service' @Component({ selector: 'child-sibling-component', template:  <h1>I am a child</h1> <input type="text" [(ngModel)]="data"/> <button (click)="addData()"></button>  }) export class ChildSiblingComponent{ data: string = 'Testing data'; constructor( private _sharedService: SharedService){} addData(){ this._sharedService.insertData(this.data); this.data = ''; } }  NOW: Things to take note of when using this method. 1. Only include the service provider for the shared service in the PARENT component and NOT the children. 2. You still have to include constructors and import the service in the children 3. This answer was originally answered for an early angular 2 beta version. All that has changed though are the import statements, so that is all you need to update if you used the original version by chance. ### How to add 10 days to current time in Rails Some other options, just for reference -10.days.ago # Available in Rails 4 DateTime.now.days_ago(-10)  Just list out all options I know: [1] Time.now + 10.days [2] 10.days.from_now [3] -10.days.ago [4] DateTime.now.days_ago(-10) [5] Date.today + 10  So now, what is the difference between them if we care about the timezone: • [1, 4] With system timezone • [2, 3] With config timezone of your Rails app • [5] Date only no time included in result ### Git pull till a particular commit I've found the updated answer from this video, the accepted answer didn't work for me. First clone the latest repo from git (if haven't) using git clone <HTTPs link of the project> (or using SSH) then go to the desire branch using git checkout <branch name> . Use the command git log  to check the latest commits. Copy the shal of the particular commit. Then use the command git fetch origin <Copy paste the shal here>  After pressing enter key. Now use the command git checkout FETCH_HEAD  Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name> . That's all. Check the video for reference. ### Changing website favicon dynamically The favicon is declared in the head tag with something like: <link rel="shortcut icon" type="image/ico" href="favicon.ico">  You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag. ### How to plot a function curve in R You mean like this? > eq = function(x){x*x} > plot(eq(1:1000), type='l')  (Or whatever range of values is relevant to your function) ### Regular expression - starting and ending with a letter, accepting only letters, numbers and _ ^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$


### Batch not-equal (inequality) operator

Try:

if not "asdf" == "fdas" echo asdf


That works for me on Windows XP (I get the same error as you for the code you posted).

### Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;

class MyStack {

// Push element x onto stack.
public void push(int x) {
if(isEmpty()){
queue1.offer(x);
}else{
if(queue1.size()>0){
queue2.offer(x);
int size = queue1.size();
while(size>0){
queue2.offer(queue1.poll());
size--;
}
}else if(queue2.size()>0){
queue1.offer(x);
int size = queue2.size();
while(size>0){
queue1.offer(queue2.poll());
size--;
}
}
}
}

// Removes the element on top of the stack.
public void pop() {
if(queue1.size()>0){
queue1.poll();
}else if(queue2.size()>0){
queue2.poll();
}
}

// Get the top element. You can make it more perfect just example
public int top() {
if(queue1.size()>0){
return queue1.peek();
}else if(queue2.size()>0){
return queue2.peek();
}
return 0;
}

// Return whether the stack is empty.
public boolean isEmpty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}


### Java8: sum values from specific field of the objects in a list

You can do this method: "IntSummaryStatistics"

IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();


### Java 8 Streams FlatMap method example

A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

fullNames.stream()
.flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
.forEach(System.out::println);


This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent


### Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.

In perl:

if($testString =~ /\d/) { print "This string contains at least one digit" }  where \d matches to a digit. ### Mean filter for smoothing images in Matlab h = fspecial('average', n); filter2(h, img);  See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h. ### Convert Mat to Array/Vector in OpenCV byte * matToBytes(Mat image) { int size = image.total() * image.elemSize(); byte * bytes = new byte[size]; //delete[] later std::memcpy(bytes,image.data,size * sizeof(byte)); }  ### Downloading jQuery UI CSS from Google's CDN I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files This link suggests that they are: We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN. ### What’s the best way to load a JSONObject from a json text file? Another way of doing the same could be using the Gson Class String filename = "path/to/file/abc.json"; Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(filename)); SampleClass data = gson.fromJson(reader, SampleClass.class);  This will give an object obtained after parsing the json string to work with. ### Remove/ truncate leading zeros by javascript/jquery Simply try to multiply by one as following: "00123" * 1; // Get as number "00123" * 1 + ""; // Get as string ### Replace negative values in an numpy array You are halfway there. Try: In [4]: a[a < 0] = 0 In [5]: a Out[5]: array([1, 2, 3, 0, 5])  ### Delaying a jquery script until everything else has loaded This code block solve my problem, _x000D_ _x000D_ <script type="text/javascript">_x000D_$(window).bind("load", function () {_x000D_
// Code here_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

### How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

### How can I split a text file using PowerShell?

I often need to do the same thing. The trick is getting the header repeated into each of the split chunks. I wrote the following cmdlet (PowerShell v2 CTP 3) and it does the trick.

##############################################################################
#.SYNOPSIS
# Breaks a text file into multiple text files in a destination, where each
# file contains a maximum number of lines.
#
#.DESCRIPTION
# When working with files that have a header, it is often desirable to have
# the header information repeated in all of the split files. Split-File
# supports this functionality with the -rc (RepeatCount) parameter.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Destination
# (Or -d) The location in which to place the chunked output files.
#
#.PARAMETER Count
# (Or -c) The maximum number of lines in each file.
#
#.PARAMETER RepeatCount
# (Or -rc) Specifies the number of "header" lines from the input file that will
# be repeated in each output file. Typically this is 0 or 1 but it can be any
# number of lines.
#
#.EXAMPLE
# Split-File bigfile.csv 3000 -rc 1
#
# Out-TempFile
##############################################################################
function Split-File {

[CmdletBinding(DefaultParameterSetName='Path')]
param(

[Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$Path,

[Alias("PSPath")]
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$LiteralPath, [Alias('c')] [Parameter(Position=2,Mandatory=$true)]
[Int32]$Count, [Alias('d')] [Parameter(Position=3)] [String]$Destination='.',

[Alias('rc')]
[Parameter()]
[Int32]$RepeatCount ) process { # yeah! the cmdlet supports wildcards if ($LiteralPath) { $ResolveArgs = @{LiteralPath=$LiteralPath} }
elseif ($Path) {$ResolveArgs = @{Path=$Path} } Resolve-Path @ResolveArgs | %{$InputName = [IO.Path]::GetFileNameWithoutExtension($_)$InputExt  = [IO.Path]::GetExtension($_) if ($RepeatCount) { $Header = Get-Content$_ -TotalCount:$RepeatCount } # get the input file in manageable chunks$Part = 1
Get-Content $_ -ReadCount:$Count | %{

# make an output filename with a suffix
$OutputFile = Join-Path$Destination ('{0}-{1:0000}{2}' -f ($InputName,$Part,$InputExt)) # In the first iteration the header will be # copied to the output file as usual # on subsequent iterations we have to do it if ($RepeatCount -and $Part -gt 1) { Set-Content$OutputFile $Header } # write this chunk to the output file Write-Host "Writing$OutputFile"
Add-Content $OutputFile$_

Part += 1 } } } }  ### How to keep indent for second line in ordered lists via CSS? CSS provides only two values for its "list-style-position" - inside and outside. With "inside" second lines are flush with the list points not with the superior line: In ordered lists, without intervention, if you give "list-style-position" the value "inside", the second line of a long list item will have no indent, but will go back to the left edge of the list (i.e. it will left-align with the number of the item). This is peculiar to ordered lists and doesn't happen in unordered lists. If you instead give "list-style-position" the value "outside", the second line will have the same indent as the first line. I had a list with a border and had this problem. With "list-style-position" set to "inside", my list didn't look like I wanted it to. But with "list-style-position" set to "outside", the numbers of the list items fell outside the box. I solved this by simply setting a wider left margin for the whole list, which pushed the whole list toward the right, back into the position it was in before. CSS: ol.classname {margin:0;padding:0;} ol.classname li {margin:0.5em 0 0 0;padding-left:0;list-style-position:outside;} HTML: <ol class="classname" style="margin:0 0 0 1.5em;">  ### Composer - the requested PHP extension mbstring is missing from your system 1. find your php.ini 2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir) 3. make sure the directive extension=php_mbstring.dll is set (uncommented) If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken. ### Looping through the content of a file in Bash #!/bin/bash # # Change the file name from "test" to desired input file # (The comments in bash are prefixed with #'s) for x in(cat test.txt)
do
echo $x done  ### ASP.NET MVC: Custom Validation by DataAnnotation #### Self validated model Your model should implement an interface IValidatableObject. Put your validation code in Validate method: public class MyModel : IValidatableObject { public string Title { get; set; } public string Description { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Title == null) yield return new ValidationResult("*", new [] { nameof(Title) }); if (Description == null) yield return new ValidationResult("*", new [] { nameof(Description) }); } }  Please notice: this is a server-side validation. It doesn't work on client-side. You validation will be performed only after form submission. ### Sending emails through SMTP with PHPMailer Simple smtp client with php stream socket with tls/ssl smtp STARTTLS command: https://github.com/breakermind/PhpMimeParser/blob/master/PhpSmtpSslSocketClient.php works with gmail.com with authenticate: <?php // Login email and password$login = "[email protected]";
$pass = "123456"; ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'verify_peer', false); stream_context_set_option($ctx, 'ssl', 'verify_peer_name', false);
try{
// echo $socket = stream_socket_client('ssl://smtp.gmail.com:587',$err, $errstr, 60, STREAM_CLIENT_CONNECT,$ctx);
echo $socket = stream_socket_client('tcp://smtp.gmail.com:587',$err, $errstr, 60, STREAM_CLIENT_CONNECT,$ctx);
if (!$socket) { print "Failed to connect$err $errstr\n"; return; }else{ // Http // fwrite($socket, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
// Smtp
echo fread($socket,8192); echo fwrite($socket, "EHLO cool.xx\r\n");
echo fread($socket,8192); // Start tls connection echo fwrite($socket, "STARTTLS\r\n");
echo fread($socket,8192); echo stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);

// Send ehlo
echo fwrite($socket, "EHLO cool.xx\r\n"); echo fread($socket,8192);

// echo fwrite($socket, "MAIL FROM: <[email protected]>\r\n"); // echo fread($socket,8192);

echo fwrite($socket, "AUTH LOGIN\r\n"); echo fread($socket,8192);

echo fwrite($socket, base64_encode($login)."\r\n");
echo fread($socket,8192); echo fwrite($socket, base64_encode($pass)."\r\n"); echo fread($socket,8192);

echo fwrite($socket, "rcpt to: <[email protected]>\r\n"); echo fread($socket,8192);

echo fwrite($socket, "DATA\n"); echo fread($socket,8192);

echo fwrite($socket, "Date: ".time()."\r\nTo: <[email protected]>\r\nFrom:<[email protected]\r\nSubject:Hello from php socket tls\r\n.\r\n"); echo fread($socket,8192);

echo fwrite($socket, "QUIT \n"); echo fread($socket,8192);

/* Turn off encryption for the rest */
// stream_socket_enable_crypto($fp, false); fclose($socket);
}
}catch(Exception $e){ echo$e;
}


### How to use goto statement correctly

goto doesn't do anything in Java.

### Overflow:hidden dots at the end

Yes, via the text-overflow property in CSS 3. Caveat: it is not universally supported yet in browsers.

### List attributes of an object

>>> ', '.join(i for i in dir(a) if not i.startswith('__'))
'multi, str'


This of course will print any methods or attributes in the class definition. You can exclude "private" methods by changing i.startwith('__') to i.startwith('_')

### How to write a simple Html.DropDownListFor()?

@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
.Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
new { @class = "myselect" })


Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;

Thanks Master Programmer && Joel Wahlund && JaredPar ;

Good luck friends.

### Convert Dictionary<string,string> to semicolon separated string in c#

using System.Linq;

string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());


(And if you're using .NET 4, or newer, then you can omit the final ToArray call.)

### What is the best Java library to use for HTTP POST, GET etc.?

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

private static String url = "http://www.apache.org/";

public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();

// Create a method instance.
GetMethod method = new GetMethod(url);

// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));

try {
// Execute the method.
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}

byte[] responseBody = method.getResponseBody();

// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));

} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}


some highlight features:

• Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
• Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
• Supports encryption with HTTPS (HTTP over SSL) protocol.
• Granular non-standards configuration and tracking.
• Transparent connections through HTTP proxies.
• Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
• Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
• Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
• Plug-in mechanism for custom authentication methods.
• Pluggable secure sockets implementations, making it easier to use third party solutions
• Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
• Plug-in mechanism for custom cookie policies.
• Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
• Response input streams to efficiently read the response body by streaming directly from the socket to the server.
• Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
• The ability to set connection timeouts.
• HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
• Source code is freely available under the Apache Software License.

### How do you make a LinearLayout scrollable?

Whenever you wanted to make a layout scrollable, you can use <ScrollView> With a layout or component in it.

### Find everything between two XML tags with RegEx

You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/

The content between the tags will be in the matched group.

### changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>


If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
color:#069;
}
</style>


### Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']


However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

### Copy the entire contents of a directory in C#

One variant with only one loop for copying of all folders and files:

foreach (var f in Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories))
{
var output = Regex.Replace(f, @"^" + path, newPath);
if (File.Exists(f)) File.Copy(f, output, true);
else Directory.CreateDirectory(output);
}


### How to create JSON object Node.js

The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.

  1 {
2     'Orientation Sensor':
3     [
4         {
5             sampleTime: '1450632410296',
6             data: '76.36731:3.4651554:0.5665419'
7         },
8         {
9             sampleTime: '1450632410296',
10             data: '78.15431:0.5247617:-0.20050584'
11         }
12     ],
13     'Screen Orientation Sensor':
14     [
15         {
16             sampleTime: '1450632410296',
17             data: '255.0:-1.0:0.0'
18         }
19     ],
20     'MPU6500 Gyroscope sensor UnCalibrated':
21     [
22         {
23             sampleTime: '1450632410296',
24             data: '-0.05006743:-0.013848438:-0.0063915867
25         },
26         {
27             sampleTime: '1450632410296',
28             data: '-0.051132694:-0.0127831735:-0.003325345'
29         }
30     ]
31 }


There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

### HTML5 Canvas vs. SVG vs. div

I agree with Simon Sarris's conclusions:

I have compared some visualization in Protovis (SVG) to Processingjs (Canvas) which display > 2000 points and processingjs is much faster than protovis.

Handling events with SVG is of course much easer because you can attach them to the objects. In Canvas you have to do it manually (check mouse position, etc) but for simple interaction it shouldn't be hard.

There is also the dojo.gfx library of the dojo toolkit. It provides an abstraction layer and you can specify the renderer (SVG, Canvas, Silverlight). That might be also an viable choice although I don't know how much overhead the additional abstraction layer adds but it makes it easy to code interactions and animations and is renderer-agnostic.

Here are some interesting benchmarks:

### Adding elements to a collection during iteration

Actually it is rather easy. Just think for the optimal way. I beleive the optimal way is:

for (int i=0; i<list.size(); i++) {
Level obj = list.get(i);

//Here execute yr code that may add / or may not add new element(s)
//...

i=list.indexOf(obj);
}


The following example works perfectly in the most logical case - when you dont need to iterate the added new elements before the iteration element. About the added elements after the iteration element - there you might want not to iterate them either. In this case you should simply add/or extend yr object with a flag that will mark them not to iterate them.

### Using ping in c#

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation namespace contains a class called PingReply that has properties designed to translate the ICMP response and deliver useful information about the pinged server such as:

• IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
• IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
• RoundtripTime (System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
• PingOptions (System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.

The following is a simple example using WinForms to demonstrate how ping works in c#. By providing a valid IP address in textBox1 and clicking button1, we are creating an instance of the Ping class, a local variable PingReply, and a string to store the IP or URL address. We assign PingReply to the ping Send method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success status. Finally, we extract from PingReply the information we need to display for the user, which is described above.

    using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace PingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Ping p = new Ping();
string s;
s = textBox1.Text;
r = p.Send(s);

if (r.Status == IPStatus.Success)
{
lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
}
}

private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
{
}
}
}
}


### Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");  mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli. ### How to get file path in iPhone app Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file. Here is an example: NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" ofType:@"the_file_extension"];  ### Choose File Dialog You just need to override onCreateDialog in an Activity. //In an Activity private String[] mFileList; private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//"); private String mChosenFile; private static final String FTYPE = ".txt"; private static final int DIALOG_LOAD_FILE = 1000; private void loadFileList() { try { mPath.mkdirs(); } catch(SecurityException e) { Log.e(TAG, "unable to write on the sd card " + e.toString()); } if(mPath.exists()) { FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { File sel = new File(dir, filename); return filename.contains(FTYPE) || sel.isDirectory(); } }; mFileList = mPath.list(filter); } else { mFileList= new String[0]; } } protected Dialog onCreateDialog(int id) { Dialog dialog = null; AlertDialog.Builder builder = new Builder(this); switch(id) { case DIALOG_LOAD_FILE: builder.setTitle("Choose your file"); if(mFileList == null) { Log.e(TAG, "Showing file picker before loading the file list"); dialog = builder.create(); return dialog; } builder.setItems(mFileList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mChosenFile = mFileList[which]; //you can do stuff with the file here too } }); break; } dialog = builder.show(); return dialog; }  ### Permission denied at hdfs I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml <property> <name>dfs.permissions</name> <value>false</value> </property>  ### How to determine a user's IP address in node In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this: proxy_set_header X-Real-IP$remote_addr;


app.set('trust proxy', true);


After that, wherever you want it to appear:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;


### H2 database error: Database may be already in use: "Locked by another process"

H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as ->

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>


OR

DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password");


It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.

Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.

### PHP string concatenation

I think this code should work fine

while ($personCount < 10) {$result = $personCount . "people ';$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;  ### Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces Hello sorry for the delay! Here is the best and the most efficiency answer that you are looking for: import java.util.regex.Matcher; import java.util.regex.Pattern; public class MyPatternReplace { public String replaceWithPattern(String str,String replace){ Pattern ptn = Pattern.compile("\\s+"); Matcher mtch = ptn.matcher(str); return mtch.replaceAll(replace); } public static void main(String a[]){ String str = "My name is kingkon. "; MyPatternReplace mpr = new MyPatternReplace(); System.out.println(mpr.replaceWithPattern(str, " ")); }  So your output of this example will be: My name is kingkon. However this method will remove also the "\n" that your string may has. So if you do not want that just use this simple method: while (str.contains(" ")){ //2 spaces str = str.replace(" ", " "); //(2 spaces, 1 space) }  And if you want to strip the leading and trailing spaces too just add: str = str.trim();  ### Sending email through Gmail SMTP server with C# This code works for me, and also allows in gmail access from unsecure apps, and removing authentication in 2 steps: Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(MailAddress, Password)  ### jQuery load more data on scroll You question specifically is about loading data when a div falls into view, and not when the user reaches the end of the page. Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226 ### An unhandled exception occurred during the execution of the current web request. ASP.NET Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies. Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever. Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null) Good luck. ### Hamcrest compare collections If you want to assert that the two lists are identical, don't complicate things with Hamcrest: assertEquals(expectedList, actual.getList());  If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder varargs method and provide values directly: assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));  (Assuming that your list is of String, rather than Agent, for this example.) If you really want to call that same method with the contents of a List: assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));  Without this, you're calling the method with a single argument and creating a Matcher that expects to match an Iterable where each element is a List. This can't be used to match a List. That is, you can't match a List<Agent> with a Matcher<Iterable<List<Agent>>, which is what your code is attempting. ### JFrame.dispose() vs System.exit() • If you have multiple windows open and only want to close the one that was closed use JFrame.dispose(). • If you want to close all windows and terminate the application use System.exit() ### Import error: No module name urllib2 That worked for me in python3: import urllib.request htmlfile = urllib.request.urlopen("http://google.com") htmltext = htmlfile.read() print(htmltext)  ### POST JSON fails with 415 Unsupported media type, Spring 3 mvc I've had this happen before with Spring @ResponseBody and it was because there was no accept header sent with the request. Accept header can be a pain to set with jQuery, but this worked for me source $.postJSON = function(url, data, callback) {
return jQuery.ajax({
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': url,
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};


The Content-Type header is used by @RequestBody to determine what format the data being sent from the client in the request is. The accept header is used by @ResponseBody to determine what format to sent the data back to the client in the response. That's why you need both headers.

### Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
return trim($value, ','); },$filters));

$query->whereIn('products.value', explode(','$values));


### Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Based on the current user's latitude, longitude and the distance you wants to find,the sql query is given below.

SELECT * FROM(
SELECT *,(((acos(sin((@latitude*pi()/180)) * sin((Latitude*pi()/180))+cos((@latitude*pi()/180)) * cos((Latitude*pi()/180)) * cos(((@longitude - Longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM Distances) t
WHERE distance <= @distance


@latitude and @longitude are the latitude and longitude of the point. Latitude and longitude are the columns of distances table. Value of pi is 22/7

### How do I get the last four characters from a string in C#?

mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;


### Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>


The complete markup should be along these lines:

<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>


You can take a look at this fiddle, and here's the result:

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>


Check the fiddle here and the screenshot below.

Here is the solution:

<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>


### Insert if not exists Oracle

This only inserts if the item to be inserted is not already present.

Works the same as:

if not exists (...) insert ...


in T-SQL

insert into destination (DESTINATIONABBREV)
select 'xyz' from dual
left outer join destination d on d.destinationabbrev = 'xyz'
where d.destinationid is null;


may not be pretty, but it's handy :)

### android.content.res.Resources$NotFoundException: String resource ID #0x0 The evaluated value for settext was integer so it went to see a resource attached to it but it was not found, you wanted to set text so it should be string so convert integer into string by attaching .toStringe or String.valueOf(int) will solve your problem! ### Get the size of the screen, current web page and browser window Here is a cross browser solution with pure JavaScript (Source): var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;  ### How to print the data in byte array as characters? byte[] buff = {1, -2, 5, 66}; for(byte c : buff) { System.out.format("%d ", c); } System.out.println();  gets you 1 -2 5 66  ### How to check if a file exists from inside a batch file if exist <insert file name here> ( rem file exists ) else ( rem file doesn't exist )  Or on a single line (if only a single action needs to occur): if exist <insert file name here> <action>  for example, this opens notepad on autoexec.bat, if the file exists: if exist c:\autoexec.bat notepad c:\autoexec.bat  ### C# string reference type? Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type: MyClass c = new MyClass(); c.MyProperty = "foo"; CNull(c); // only a copy of the reference is sent Console.WriteLine(c.MyProperty); // still foo, we only made the copy null CPropertyChange(c); Console.WriteLine(c.MyProperty); // bar private void CNull(MyClass c2) { c2 = null; } private void CPropertyChange(MyClass c2) { c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well. }  ### How to do Select All(*) in linq to sql Why don't you use DbTestDataContext obj = new DbTestDataContext(); var q =from a in obj.GetTable<TableName>() select a;  This is simple. ### How can I get a list of locally installed Python modules? Very simple searching using pkgutil.iter_modules from pkgutil import iter_modules a=iter_modules() while True: try: x=a.next() except: break if 'searchstr' in x[1]: print x[1]  ### Force "git push" to overwrite remote files Another option (to avoid any forced push which can be problematic for other contributors) is to: • put your new commits in a dedicated branch • reset your master on origin/master • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch). See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs. That way, you can push master to remote without having to force anything. ### ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate I ran into this issue because in the dependency injection setup I was missing a dependency of a repository that is a dependency of a controller: services.AddScoped<IDependencyOne, DependencyOne>(); <-- I was missing this line! services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();  ### Setting focus on an HTML input box on page load This line: <input type="password" name="PasswordInput"/>  should have an id attribute, like so: <input type="password" name="PasswordInput" id="PasswordInput"/>  ### How to resolve symbolic links in a shell script readlink -f "$path"


Editor's note: The above works with GNU readlink and FreeBSD/PC-BSD/OpenBSD readlink, but not on OS X as of 10.11.
GNU readlink offers additional, related options, such as -m for resolving a symlink whether or not the ultimate target exists.

Note since GNU coreutils 8.15 (2012-01-06), there is a realpath program available that is less obtuse and more flexible than the above. It's also compatible with the FreeBSD util of the same name. It also includes functionality to generate a relative path between two files.

realpath $path  [Admin addition below from comment by halloleodanorton] For Mac OS X (through at least 10.11.x), use readlink without the -f option: readlink$path


Editor's note: This will not resolve symlinks recursively and thus won't report the ultimate target; e.g., given symlink a that points to b, which in turn points to c, this will only report b (and won't ensure that it is output as an absolute path).
Use the following perl command on OS X to fill the gap of the missing readlink -f functionality:
perl -MCwd -le 'print Cwd::abs_path(shift)' "$path" ### Allow multiple roles to access controller action Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out: public static class RolesConvention { public const string Administrator = "Administrator"; public const string Guest = "Guest"; }  Then in the controller: [Authorize(Roles = RolesConvention.Administrator )] [Authorize(Roles = RolesConvention.Guest)] [Produces("application/json")] [Route("api/[controller]")] public class MyController : Controller  ### Simplest way to download and unzip files in Node.js cross-platform? Checkout adm-zip. ADM-ZIP is a pure JavaScript implementation for zip data compression for NodeJS. The library allows you to: • decompress zip files directly to disk or in-memory buffers • compress files and store them to disk in .zip format or in compressed buffers • update content of/add new/delete files from an existing .zip ### When adding a Javascript library, Chrome complains about a missing source map, why? I had similar problem when i was trying to work with coco-ssd. I think this problem is caused because of the version. I changed version of tfjs to 0.9.0 and coco-ssd version to 1.1.0 and it worked for me. (you can search for posenet versions on : https://www.jsdelivr.com/package/npm/@tensorflow-models/posenet) <!-- Load TensorFlow.js--> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"></script> <!-- Load the coco-ssd model. --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"</script>  ### How can I put strings in an array, split by new line? You can use the explode function, using "\n" as separator: $your_array = explode("\n", $your_string_from_db);  For instance, if you have this piece of code: $str = "My text1\nMy text2\nMy text3";
$arr = explode("\n",$str);
var_dump($arr);  You'd get this output: array 0 => string 'My text1' (length=8) 1 => string 'My text2' (length=8) 2 => string 'My text3' (length=8)  Note that you have to use a double-quoted string, so \n is actually interpreted as a line-break. (See that manual page for more details.) ### Delete all documents from index/type without deleting type Just to add couple cents to this. The "delete_by_query" mentioned at the top is still available as a plugin in elasticsearch 2.x. Although in the latest upcoming version 5.x it will be replaced by "delete by query api" ### Replace and overwrite instead of appending Using truncate(), the solution could be import re #open the xml file for reading: with open('path/test.xml','r+') as f: #convert to string: data = f.read() f.seek(0) f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data)) f.truncate()  ### How can I turn a string into a list in Python? The list() function [docs] will convert a string into a list of single-character strings. >>> list('hello') ['h', 'e', 'l', 'l', 'o']  Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets: >>> s = "hello" >>> s[1] 'e' >>> s[4] 'o'  You can also loop over the characters in the string as you can loop over the elements of a list: >>> for c in 'hello': ... print c + c, ... hh ee ll ll oo  ### android.view.InflateException: Binary XML file: Error inflating class fragment In my case . The layout i was trying to inflate had <include layout = "...." />  tag, removing it fixed it. I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter. ### How can I read and parse CSV files in C++? Solution using Boost Tokenizer: std::vector<std::string> vec; using namespace boost; tokenizer<escaped_list_separator<char> > tk( line, escaped_list_separator<char>('\\', ',', '\"')); for (tokenizer<escaped_list_separator<char> >::iterator i(tk.begin()); i!=tk.end();++i) { vec.push_back(*i); }  ### How to create a QR code reader in a HTML5 website? The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub. I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub. ### Remove elements from collection while iterating I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time. ### How to loop through a dataset in powershell? The parser is having trouble concatenating your string. Try this: write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])  Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string: write-host "value is :$i $($ds.Tables[1].Rows[$i][0])"  ### Can iterators be reset in Python? One possible option is to use itertools.cycle(), which will allow you to iterate indefinitely without any trick like .seek(0). iterDic = itertools.cycle(csv.DictReader(open('file.csv')))  ### Javascript reduce on array of objects I used to encounter this is my development, what I do is wrap my solution in a function to make it reusable in my environment, like this: const sumArrayOfObject =(array, prop)=>array.reduce((sum, n)=>{return sum + n[prop]}, 0)  ### Load image from resources You can do this using the ResourceManager: public bool info(string channel) { object o = Properties.Resources.ResourceManager.GetObject(channel); if (o is Image) { channelPic.Image = o as Image; return true; } return false; }  ### How to write into a file in PHP? fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead. Article file_put_contents(file,data,mode,context): The file_put_contents writes a string to a file. This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure. fwrite(file,string,length): The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length, whichever comes first.This function returns the number of bytes written or FALSE on failure. ### Setting up FTP on Amazon Cloud Server FileZila is good FTP tool to setup with Amazon Cloud. 1. Download FileZila client from https://filezilla-project.org/ 2. Click on File -> Site Manager - > 3. New Site 4. Provide Host Name IP address of your amazon cloud location (Port if any) 5. Protocol - SFTP (May change based on your requirement) 6. Login Type - Normal (So system will not ask for password each time) 7. Provide user name and password. 8. Connect. You need to do these step only 1 time, later it will upload content to the same IP address and same site. ### Calling a Sub and returning a value Private Sub Main() Dim value = getValue() 'do something with value End Sub Private Function getValue() As Integer Return 3 End Function  ### AttributeError: 'module' object has no attribute All the above answers are great, but I'd like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me. ### How to check list A contains any value from list B? You can check if a list is inside of another list with this var list1 = new List<int> { 1, 2, 3, 4, 6 }; var list2 = new List<int> { 2, 3 }; bool a = list1.Any(c => list2.Contains(c));  ### Fastest Way to Find Distance Between Two Lat/Long Points I needed to solve similar problem (filtering rows by distance from single point) and by combining original question with answers and comments, I came up with solution which perfectly works for me on both MySQL 5.6 and 5.7. SELECT *, (6371 * ACOS(COS(RADIANS(56.946285)) * COS(RADIANS(Y(coordinates))) * COS(RADIANS(X(coordinates)) - RADIANS(24.105078)) + SIN(RADIANS(56.946285)) * SIN(RADIANS(Y(coordinates))))) AS distance FROM places WHERE MBRContains ( LineString ( Point ( 24.105078 + 15 / (111.320 * COS(RADIANS(56.946285))), 56.946285 + 15 / 111.133 ), Point ( 24.105078 - 15 / (111.320 * COS(RADIANS(56.946285))), 56.946285 - 15 / 111.133 ) ), coordinates ) HAVING distance < 15 ORDER By distance  coordinates is field with type POINT and has SPATIAL index 6371 is for calculating distance in kilometres 56.946285 is latitude for central point 24.105078 is longitude for central point 15 is maximum distance in kilometers In my tests, MySQL uses SPATIAL index on coordinates field to quickly select all rows which are within rectangle and then calculates actual distance for all filtered places to exclude places from rectangles corners and leave only places inside circle. This is visualisation of my result: Gray stars visualise all points on map, yellow stars are ones returned by MySQL query. Gray stars inside corners of rectangle (but outside circle) were selected by MBRContains() and then deselected by HAVING clause. ### Xcode swift am/pm time to 24 hour format Swift 3 * Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes- Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds func timeConversion24(time12: String) -> String { let dateAsString = time12 let df = DateFormatter() df.dateFormat = "hh:mm:ssa" let date = df.date(from: dateAsString) df.dateFormat = "HH:mm:ss" let time24 = df.string(from: date!) print(time24) return time24 }  Input 07:05:45PM Output 19:05:45 Similarly Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes- Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM func timeConversion12(time24: String) -> String { let dateAsString = time24 let df = DateFormatter() df.dateFormat = "HH:mm:ss" let date = df.date(from: dateAsString) df.dateFormat = "hh:mm:ssa" let time12 = df.string(from: date!) print(time12) return time12 }  Input 19:05:45 Output 07:05:45PM ### jquery simple image slideshow tutorial Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin. _x000D_ _x000D_ $(function() {_x000D_
var theImage = $('ul#ss li img');_x000D_ var theWidth = theImage.width();_x000D_ //wrap into mother div_x000D_$('ul#ss').wrap('<div id="mother" />');_x000D_
//assign height width and overflow hidden to mother_x000D_
$('#mother').css({_x000D_ width: function() {_x000D_ return theWidth;_x000D_ },_x000D_ height: function() {_x000D_ return theImage.height();_x000D_ },_x000D_ position: 'relative',_x000D_ overflow: 'hidden'_x000D_ });_x000D_ //get total of image sizes and set as width for ul _x000D_ var totalWidth = theImage.length * theWidth;_x000D_$('ul').css({_x000D_
width: function() {_x000D_
}_x000D_
});_x000D_
_x000D_
var ss_timer = setInterval(function() {_x000D_
ss_next();_x000D_
}, 3000);_x000D_
_x000D_
function ss_next() {_x000D_
var a = $(".active");_x000D_ a.removeClass('active');_x000D_ _x000D_ if (a.hasClass('last')) {_x000D_ //last element -- loop_x000D_ a.parent('ul').animate({_x000D_ "margin-left": (0)_x000D_ }, 1000);_x000D_ a.siblings(":first").addClass('active');_x000D_ } else {_x000D_ a.parent('ul').animate({_x000D_ "margin-left": (-(a.index() + 1) * theWidth)_x000D_ }, 1000);_x000D_ a.next().addClass('active');_x000D_ }_x000D_ }_x000D_ _x000D_ // Cancel slideshow and move next manually on click_x000D_$('ul#ss li img').on('click', function() {_x000D_
clearInterval(ss_timer);_x000D_
ss_next();_x000D_
});_x000D_
_x000D_
});
_x000D_
* {_x000D_
margin: 0;_x000D_
}_x000D_
#ss {_x000D_
list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
float: left;_x000D_
}_x000D_
#ss img {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
<li class="active">_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
</li>_x000D_
<li class="last">_x000D_
</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

### Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

1. Install dplyr package.
2. Run the below code
library(dplyr)

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))



Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.

    <directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>


### How Best to Compare Two Collections in Java and Act on Them?

public static boolean doCollectionsContainSameElements(
Collection<Integer> c1, Collection<Integer> c2){

if (c1 == null || c2 == null) {
return false;
}
else if (c1.size() != c2.size()) {
return false;
} else {
return c1.containsAll(c2) && c2.containsAll(c1);
}
}


### NVIDIA NVML Driver/library version mismatch

These answers not worked for me:

https://stackoverflow.com/a/43023000/1179925

https://stackoverflow.com/a/45319156/1179925

https://stackoverflow.com/a/54349675/1179925

dmesg

NVRM: API mismatch: the client has the version 418.67, but
NVRM: this kernel module has the version 430.26.  Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.


Uninstall old driver 418.67 and install new driver 430.26 (download NVIDIA-Linux-x86_64-430.26.run):

sudo apt-get --purge remove "*nvidia*"
sudo /usr/bin/nvidia-uninstall
chmod +x NVIDIA-Linux-x86_64-430.26.run
sudo ./NVIDIA-Linux-x86_64-430.26.run
[ignore abort]


cat /proc/driver/nvidia/version

NVRM version: NVIDIA UNIX x86_64 Kernel Module  430.26  Tue Jun  4 17:40:52 CDT 2019
GCC version:  gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)


### Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")


worked for me, see the picture

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

### Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>


get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn


and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn


### How can I insert multiple rows into oracle with a sequence value?

insert into TABLE_NAME
(COL1,COL2)
WITH
data AS
(
select 'some value'    x from dual
union all
select 'another value' x from dual
)
SELECT my_seq.NEXTVAL, x
FROM data
;


I think that is what you want, but i don't have access to oracle to test it right now.

### Early exit from function?

This:

function myfunction()
{
if (a == 'stop')  // How can I stop working of function here?
{
return;
}
}


### What's the difference between a POST and a PUT HTTP REQUEST?

As far as i know, PUT is mostly used for update the records.

1. POST - To create document or any other resource

2. PUT - To update the created document or any other resource.

But to be clear on that PUT usually 'Replaces' the existing record if it is there and creates if it not there..

### Entity Framework Timeouts

If you are using a DbContext, use the following constructor to set the command timeout:

public class MyContext : DbContext
{
public MyContext ()
{
objectContext.CommandTimeout = 1 * 60; // value in seconds
}
}


### How to iterate through LinkedHashMap with lists as values

I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.

This should work:

// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());

// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}


or you can use

// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}


You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.

### Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol


Instead of what are you using currently:

git diff -w (--ignore-all-space)


For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

### FormData.append("key", "value") is not working

New in Chrome 50+ and Firefox 39+ (resp. 44+):

• formdata.entries() (combine with Array.from() for debugability)
• formdata.get(key)
• and more very useful methods

What I usually do to 'debug' a FormData object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

You don't need a/the same Ajax framework. You don't need any details. Just send it:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);


Easy.

### Select subset of columns in data.table R

Option using dplyr

require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)


### Get startup type of Windows service using PowerShell

WMI is the way to do this.

Get-WmiObject -Query "Select StartMode From Win32_Service Where Name='winmgmt'"


Or

Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='Winmgmt'"


### Best way to check for null values in Java?

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && foo.bar()) {
//do something
}


### global variable for all controller and views

In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:

$request->attributes->add(['myVar' =>$myVar]);


Then you can access it from any of your controllers using:

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


{{ Request::get('myVar') }}


### Java Inheritance - calling superclass method

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
if (something) {
super.alphaMethod1();
return;
}
// Rest of the code for other situations
}


Like this it will only call A's method when needed and will remain invisible for the class user.

### Get all column names of a DataTable into string array using (LINQ/Predicate)

List<String> lsColumns = new List<string>();

if(dt.Rows.Count>0)
{
var count = dt.Rows[0].Table.Columns.Count;

for (int i = 0; i < count;i++ )
{
}
}


### writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
with open('path_to_file','a') as file:
file.write(f'{i}\n')

file.close()


### How to remove text from a string?

This little function I made has always worked for me :)

String.prototype.deleteWord = function (searchTerm) {
var str = this;
var n = str.search(searchTerm);
while (str.search(searchTerm) > -1) {
n = str.search(searchTerm);
str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
}
return str;
}

// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!


I know it is not the best, but It has always worked for me :)

### Android: How to bind spinner to custom object list?

If you don't need a separated class, i mean just a simple adapter mapped on your object. Here is my code based on ArrayAdapter functions provided.

Simple but efficient.

editCategorySpinner = view.findViewById(R.id.discovery_edit_category_spinner);

// Drop down layout style - list view with radio button

// attaching data adapter to spinner, as you can see i have no data at this moment

(getActivity(), android.R.layout.simple_spinner_item, new ArrayList<Category>(0)) {

// And the "magic" goes here
// This is for the "passive" state of the spinner
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// I created a dynamic TextView here, but you can reference your own  custom layout for each spinner item
TextView label = (TextView) super.getView(position, convertView, parent);
label.setTextColor(Color.BLACK);
// Then you can get the current item using the values array (Users array) and the current position
// You can NOW reference each method you has created in your bean object (User class)
Category item = getItem(position);
label.setText(item.getName());

// And finally return your dynamic (or custom) view for each spinner item
return label;
}

// And here is when the "chooser" is popped up
// Normally is the same view, but you can customize it if you want
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
TextView label = (TextView) super.getDropDownView(position, convertView, parent);
label.setTextColor(Color.BLACK);
Category item = getItem(position);
label.setText(item.getName());

return label;
}
};


And then you can use this code (i couldn't put Category[] in adapter constructor because data are loaded separatly).

categoryRepository.getAll().observe(this, new Observer<List<Category>>() {

@Override
public void onChanged(@Nullable final List<Category> items) {
}
});


### What HTTP status response code should I use if the request is missing a required parameter?

I often use a 403 Forbidden error. The reasoning is that the request was understood, but I'm not going to do as asked (because things are wrong). The response entity explains what is wrong, so if the response is an HTML page, the error messages are in the page. If it's a JSON or XML response, the error information is in there.

From rfc2616:

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404

### Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

@NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false) is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.

### PHP expects T_PAAMAYIM_NEKUDOTAYIM?

This can happen on foreachs when using:

foreach( $array as$key = $value )  instead of foreach($array as $key =>$value )


### curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

### PHP Regex to get youtube video ID?

I know that the title of the thread refers to the use of a regex, but just as the Zawinski quote says, I really think that avoiding regexes is best here. I'd recommend this function instead:

function get_youtube_id($url) { if (strpos($url,"v=") !== false)
{
return substr($url, strpos($url, "v=") + 2, 11);
}
elseif(strpos( $url,"embed/") !== false) { return substr($url, strpos($url, "embed/") + 6, 11); } }  I recommend this because the ID of YouTube videos is always the same, independent from the style of the URL, e.g. • http://www.youtube.com/watch?v=t_uW44Bsezg • http://www.youtube.com/watch?feature=endscreen&v=Id3xG4xnOfA&NR=1 • And Other Ulr Form In Which The Word "embed/" Is Placed Before The Id ... !! and that might be the case for embedded and iframe-ed stuff. ### WorksheetFunction.CountA - not working post upgrade to Office 2010 It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches. ### How to remove a row from JTable? The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns. ### What are -moz- and -webkit-? What are -moz- and -webkit-? CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes. Why do different browsers add different prefixes for the same effect? A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode: Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations. Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages. Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid. The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid. UPDATE AS OF THE YEAR 2016 As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one. As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016, Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well. For example, just a few years ago, to set a rounded corner on a box you had to write: -moz-border-radius: 10px 5px; -webkit-border-top-left-radius: 10px; -webkit-border-top-right-radius: 5px; -webkit-border-bottom-right-radius: 10px; -webkit-border-bottom-left-radius: 5px; border-radius: 10px 5px;  But now that browsers have come to fully support this feature, you really only need the standardized version: border-radius: 10px 5px;  Finding the right rules for all browsers As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers. You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability. Input: a { column-count: 3; column-gap: 10px; column-fill: auto; }  Output: a { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 10px; -moz-column-gap: 10px; column-gap: 10px; -webkit-column-fill: auto; -moz-column-fill: auto; column-fill: auto; }  ### Scp command syntax for copying a folder from local machine to a remote server In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command Please check this ### jQuery limit to 2 decimal places You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value: var amount =$("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));


You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));  ### How to make a background 20% transparent on Android See Popularity below textView using this  android:alpha="0.38"  XML android:color="#3983BE00" // Partially transparent sky blue  Dynamically btn.getBackground().setAlpha(128); // 50% transparent tv_name.getBackground().setAlpha(128); // 50% transparent Where the INT ranges from 0 (fully transparent) to 255 (fully opaque). <TextView style="@style/TextAppearance.AppCompat.Caption" android:layout_width="match_parent" android:layout_height="wrap_content" android:alpha="0.38" android:gravity="start" android:textStyle="bold" tools:text="1994|EN" />  android:alpha="0.38" Text View alpha property set 0.38 to your textView visibility is faid  ### Styling input buttons for iPad and iPhone You may be looking for -webkit-appearance: none;  ### How to exclude particular class name in CSS selector? # Method 1 The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space .reMode_selected.reMode_hover:hover  Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be .reMode_selected.reMode_hover:hover { background-color:inherit; } .reMode_hover:hover { background-color: #f0ac00; }  Fiddle # Method 2 An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected Fiddle However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal. # Method 3 A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support Fiddle ### What are the best use cases for Akka framework We use Akka in several projects at work, the most interesting of which is related to vehicle crash repair. Primarily in the UK but now expanding to the US, Asia, Australasia and Europe. We use actors to ensure that crash repair information is provided realtime to enable the safe and cost effective repair of vehicles. The question with Akka is really more 'what can't you do with Akka'. Its ability to integrate with powerful frameworks, its powerful abstraction and all of the fault tolerance aspects make it a very comprehensive toolkit. ### How to select the first element in the dropdown using jquery?  var arr_select_val=[];$("select").each(function() {
var name=this.name;
arr_select_val[name]=$('select option:first-child').val(); }); // Process the array object$('.orders_status_summary_div').print(arr_select_val);


### Computational complexity of Fibonacci Sequence

Just ask yourself how many statements need to execute for F(n) to complete.

For F(1), the answer is 1 (the first part of the conditional).

For F(n), the answer is F(n-1) + F(n-2).

So what function satisfies these rules? Try an (a > 1):

an == a(n-1) + a(n-2)

Divide through by a(n-2):

a2 == a + 1

Solve for a and you get (1+sqrt(5))/2 = 1.6180339887, otherwise known as the golden ratio.

So it takes exponential time.

### Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();


You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

### How to convert currentTimeMillis to a date in Java?

The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.

I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.

### Convert Long into Integer

You'll need to type cast it.

long i = 100L;
int k = (int) i;


Bear in mind that a long has a bigger range than an int so you might lose data.

If you are talking about the boxed types, then read the documentation.

### Unable to copy file - access to the path is denied

If someone wants an extra simple solution before trying anything else.

Simply restart your PC. Open Visual Studio, try to build again.

### What is VanillaJS?

Using "VanillaJS" means using plain JavaScript without any additional libraries like jQuery.

People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries.

### Code formatting shortcuts in Android Studio for Operation Systems

The best key where you can find all commands in Eclipse is Ctrl + Shift + L.

By pressing this you can get all the commands in Eclipse.

One important is Ctrl + Shift + O to import and un-import useless imports.

### How to find a parent with a known class in jQuery?

Assuming that this is .d, you can write

$(this).closest('.a');  The closest method returns the innermost parent of your element that matches the selector. ### Connecting to MySQL from Android with JDBC try changing in the gradle file the targetSdkVersion to 8 targetSdkVersion 8  ### Use -notlike to filter out multiple strings in PowerShell don't use -notLike, -notMatch with Regular-Expression works in one line: Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}


Use Where-Object and test the $_.CreationTime: Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | Where-Object {$_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }  ### How can I install MacVim on OS X? That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line ### How to use the pass statement? The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code: def foo(x,y): return x+y  means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result", def bar(): pass  means "If I call the function bar(), do absolutely nothing." The other answers are quite correct, but it's also useful for a few things that don't involve place-holding. For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero. c = a / b  will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code: try: c = a / b except ZeroDivisionError: pass  Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So: for t in range(25): do_a_thing(t) if t == 20: pass  with the breakpoint on pass. ### MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine make change in changes in /opt/lampp/phpmyadmin/config.inc.php <?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * phpMyAdmin sample configuration, you can use it as base for * manual configuration. For easier setup you can use setup/ * * All directives are explained in documentation in the doc/ folder * or at <http://docs.phpmyadmin.net/>. * * @package PhpMyAdmin */ /** * This is needed for cookie based authentication to encrypt password in * cookie */$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/**
* Servers configuration
*/
$i = 0; /** * First server */$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
//$cfg['Servers'][$i]['host'] = 'localhost';
//$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/**
*/

/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';

$cfg['Servers'][1]['pmadb'] = 'phpmyadmin';$cfg['Servers'][1]['controluser'] = 'pma';
$cfg['Servers'][1]['controlpass'] = '';$cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][1]['relation'] = 'pma_relation';$cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
$cfg['Servers'][1]['table_info'] = 'pma_table_info';$cfg['Servers'][1]['column_info'] = 'pma_column_info';
$cfg['Servers'][1]['history'] = 'pma_history';$cfg['Servers'][1]['recent'] = 'pma_recent';
$cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';$cfg['Servers'][1]['tracking'] = 'pma_tracking';
$cfg['Servers'][1]['table_coords'] = 'pma_table_coords';$cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords'; //$cfg['Servers'][$i]['favorite'] = 'pma__favorite'; //$cfg['Servers'][$i]['users'] = 'pma__users'; //$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups'; //$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding'; //$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches'; //$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns'; //$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings'; //$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates'; /* Contrib / Swekey authentication */ //$cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf'; /** * End of servers configuration */ /** * Directories for saving/loading files from server */$cfg['UploadDir'] = '';
$cfg['SaveDir'] = ''; /** * Whether to display icons or text or both icons and text in table row * action segment. Value can be either of 'icons', 'text' or 'both'. * default = 'both' */ //$cfg['RowActionType'] = 'icons';

/**
* Defines whether a user should be displayed a "show all (records)"
* button in browse mode or not.
* default = false
*/
//$cfg['ShowAll'] = true; /** * Number of rows displayed when browsing a result set. If the result * set contains more rows, "Previous" and "Next". * Possible values: 25, 50, 100, 250, 500 * default = 25 */ //$cfg['MaxRows'] = 50;

/**
* Disallow editing of binary fields
* valid values are:
*   false    allow editing
*   'blob'   allow editing except for BLOB fields
*   'noblob' disallow editing except for BLOB fields
*   'all'    disallow editing
* default = 'blob'
*/
//$cfg['ProtectBinary'] = false; /** * Default language to use, if not browser-defined or user-defined * (you find all languages in the locale folder) * uncomment the desired line: * default = 'en' */ //$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de'; /** * How many columns should be used for table display of a database? * (a value larger than 1 results in some information being hidden) * default = 1 */ //$cfg['PropertiesNumColumns'] = 2;

/**
* Set to true if you want DB-based query history.If false, this utilizes
* JS-routines to display query history (lost by window close)
*
* This requires configuration storage enabled, see above.
* default = false
*/
//$cfg['QueryHistoryDB'] = true; /** * When using DB-based query history, how many entries should be kept? * default = 25 */ //$cfg['QueryHistoryMax'] = 100;

/**
* Whether or not to query the user before sending the error report to
* the phpMyAdmin team when a JavaScript error occurs
*
* Available options
* ('ask' | 'always' | 'never')
*/
//$cfg['SendErrorReports'] = 'always'; /** * You can find more configuration options in the documentation * in the doc/ folder or at <http://docs.phpmyadmin.net/>. */  ### Adding a JAR to an Eclipse Java library In eclipse Galileo : • Open the project's properties • Select Java Build Path • Select Libraries tab From there you can Add External Jars ### Asp.Net MVC with Drop Down List, and SelectListItem Assistance You have a view model to which your view is strongly typed => use strongly typed helpers: <%= Html.DropDownListFor( x => x.SelectedAccountId, new SelectList(Model.Accounts, "Value", "Text") ) %>  Also notice that I use a SelectList for the second argument. And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit: public ActionResult AccountTransaction() { var accounts = Services.AccountServices.GetAccounts(false); var viewModel = new AccountTransactionView { Accounts = accounts.Select(a => new SelectListItem { Text = a.Description, Value = a.AccountId.ToString() }) }; return View(viewModel); }  ### How can I test a change made to Jenkinsfile locally? A bit late to the party, but that's why I wrote jenny, a small reimplementation of some core Jenkinsfile steps. (https://github.com/bmustiata/jenny) ### \n or \n in php echo not print \n must be in double quotes! echo "hello\nworld";  Output hello world  A nice way around this is to use PHP as a more of a templating language <p> Hello <span><?php echo$world ?></span>
</p>


Output

<p>
Hello <span>Planet Earth</span>
</p>


Notice, all newlines are kept in tact!

### Composer update memory limit

I'm running Laravel 6 with Homestead and also ran into this problem. As suggested here in the other answers you can prefix COMPOSER_MEMORY_LIMIT=-1 to a single command and run the command normally. If you'd like to update your PHP config to always allow unlimited memory follow these steps.

vagrant up
vagrant ssh
php --version # 7.4
php --ini # Shows path to the php.ini file that's loaded
cd /etc/php/7.4/cli # your PHP version. Each PHP version has a folder
sudo vi php.ini


Add memory_limit=-1 to your php.ini file. If you're having trouble using Vim or making edits to the php.ini file check this answer about how to edit the php.ini file with Vim. The file should look something like this:

; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit = -1


Note that this could eat up infinite amount of memory on your machine. Probably not a good idea for production lol. With Laravel Valet had to follow this article and update the memory value here:

sudo vi /usr/local/etc/php/7.4/conf.d/php-memory-limits.ini


Then restart the server with Valet:

valet restart


This answer was also helpful for changing the config with Laravel Valet on Mac so the changes take effect.

### CSS width of a <span> tag

I would use the padding attribute. This will allow you add a set number of pixels to either side of the element without the element loosing its span qualities:

• It won't become a block
• It will float as you expect

This method will only add to the padding however, so if you change the length of the content (from Categories to Tags, for example) the size of the content will change and the overall size of the element will change as well. But if you really want to set a rigid size, you should do as mentioned above and use a div.

See the box model for more details about the box model, content, padding, margin, etc.

### Save matplotlib file to a directory

You should be able to specify the whole path to the destination of your choice. E.g.:

plt.savefig('E:\New Folder\Name of the graph.jpg')


### Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

### Does :before not work on img elements?

Just give the Image "position: relative" and it will work

### SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

### How to get current user, and how to use User class in MVC5?

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();


Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();


In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:

### What does auto do in margin:0 auto?

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;


0 is for top-bottom and auto for left-right. The browser sets the margin.

### Jenkins Host key verification failed

As for the workaround (e.g. Windows slave), define the following environment variable in global properties:

GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"


Note: If you don't see the option, you probably need EnvInject plugin for it.

### Detect application heap size in Android

Some operations are quicker than java heap space manager. Delaying operations for some time can free memory space. You can use this method to escape heap size error:

waitForGarbageCollector(new Runnable() {
@Override
public void run() {
}
});

/**
* Measure used memory and give garbage collector time to free up some
* of the space.
*
* @param callback Callback operations to be done when memory is free.
*/
public static void waitForGarbageCollector(final Runnable callback) {

Runtime runtime;
long maxMemory;
long usedMemory;
double availableMemoryPercentage = 1.0;
final double MIN_AVAILABLE_MEMORY_PERCENTAGE = 0.1;
final int DELAY_TIME = 5 * 1000;

runtime =
Runtime.getRuntime();

maxMemory =
runtime.maxMemory();

usedMemory =
runtime.totalMemory() -
runtime.freeMemory();

availableMemoryPercentage =
1 -
(double) usedMemory /
maxMemory;

if (availableMemoryPercentage < MIN_AVAILABLE_MEMORY_PERCENTAGE) {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
waitForGarbageCollector(
callback);
} else {
// Memory resources are available, go to next operation:
callback.run();
}
}


### Create table with jQuery - append

this is most better

html

<div id="here_table"> </div>


jQuery

$('#here_table').append( '<table>' ); for(i=0;i<3;i++) {$('#here_table').append( '<tr>' + 'result' +  i + '</tr>' );

for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' ); } }$('#here_table').append(  '</table>' );


### How to process SIGTERM signal gracefully?

Here is a simple example without threads or classes.

import signal

run = True

def handler_stop_signals(signum, frame):
global run
run = False

signal.signal(signal.SIGINT, handler_stop_signals)
signal.signal(signal.SIGTERM, handler_stop_signals)

while run:
pass # do stuff including other IO stuff


### How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie


Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

### Jquery If radio button is checked

$("input").bind('click', function(e){ if ($(this).val() == 'Yes') {
\$("body").append('whatever');
}
});


### Equivalent of String.format in jQuery

If you're using the validation plugin you can use:

jQuery.validator.format("{0} {1}", "cool", "formatting") = 'cool formatting'

### ng-if check if array is empty

To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">

• Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

<p *ngIf="post?.capabilities?.items?.length > 0">
`