Programs & Examples On #Inheritdoc

Spring boot - Not a managed type

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

UILabel with text of two different colors

SwiftRichString works perfect! You can use + to concatenate two attributed string

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

You have to name your struct like that:

typedef struct car_t {

   char

   wheel_t

} car_t;

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I style even and odd elements?

Below is the example of even and odd css color apply

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

Compare two date formats in javascript/jquery

It's quite simple:

if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
    //your code here
}

Comparing 2 Date instances will work just fine. It'll just call valueOf implicitly, coercing the Date instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date instances will be coerced to the Number type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

Trim characters in Java

This does what you want:

public static void main (String[] args) {
    String a = "\\joe\\jill\\";
    String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
    System.out.println(b);
}

The $ is used to remove the sequence in the end of string. The ^ is used to remove in the beggining.

As an alternative, you can use the syntax:

String b = a.replaceAll("\\\\$|^\\\\", "");

The | means "or".

In case you want to trim other chars, just adapt the regex:

String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining

How to read data from a file in Lua

Try this:

-- http://lua-users.org/wiki/FileInputOutput

-- see if the file exists
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end

-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)

-- print all line numbers and their contents
for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end

How to load my app from Eclipse to my Android phone instead of AVD

Some people may have the issue where your phone might not immediately get recognized by the computer as an emulator, especially if you're given the option to choose why your phone is connected to the computer on your phone. These options are:

  • charge only
  • Media device (MTP)
  • Camera file transfer (PTP)
  • Share mobile network
  • Install driver

Of these options, choose MTP and follow the instructions found in the quotes of other answers.

  • Hope this helps!

goto run menu -> run configuration. right click on android application on the right side and click new. fill the corresponding details like project name under the android tab. then under the target tab. select 'launch on all compatible devices and then select active devices from the drop down list'. save the configuration and run it by either clicking run on the 'run' button on the bottom right side of the window or close the window and run again

Possible reasons for timeout when trying to access EC2 instance

If SSH access doesn't work for your EC2 instance, you need to check:

  • Security Group for your instance is allowing Inbound SSH access (check: view rules).

If you're using VPC instance (you've VPC ID and Subnet ID attached to your instance), check:

  1. In VPC Dashboard, find used Subnet ID which is attached to your VPC.
  2. Check its attached Route table which should have 0.0.0.0/0 as Destination and your Internet Gateway as Target.

On Linux, you may also check route info in System Log in Networking of the instance, e.g.:

++++++++++++++++++++++++++++++++++++++Net device info+++++++++++++++++++++++++++++++++++++++
+--------+------+------------------------------+---------------+-------+-------------------+
| Device |  Up  |           Address            |      Mask     | Scope |     Hw-Address    |
+--------+------+------------------------------+---------------+-------+-------------------+
|   lo   | True |          127.0.0.1           |   255.0.0.0   |   .   |         .         |
|  eth0  | True |         172.30.2.226         | 255.255.255.0 |   .   | 0a:70:f3:2f:82:23 |
+--------+------+------------------------------+---------------+-------+-------------------+
++++++++++++++++++++++++++++Route IPv4 info+++++++++++++++++++++++++++++
+-------+-------------+------------+---------------+-----------+-------+
| Route | Destination |  Gateway   |    Genmask    | Interface | Flags |
+-------+-------------+------------+---------------+-----------+-------+
|   0   |   0.0.0.0   | 172.30.2.1 |    0.0.0.0    |    eth0   |   UG  |
|   1   |   10.0.3.0  |  0.0.0.0   | 255.255.255.0 |   lxcbr0  |   U   |
|   2   |  172.30.2.0 |  0.0.0.0   | 255.255.255.0 |    eth0   |   U   |
+-------+-------------+------------+---------------+-----------+-------+

where UG flags showing you your internet gateway.

For more details, check: Troubleshooting Connecting to Your Instance at Amazon docs.

Android - how to replace part of a string by another string?

You're doing only one mistake.

use replaceAll() function over there.

e.g.

String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

How do I determine if a checkbox is checked?

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<label><input class="lifecheck" id="lifecheck" type="checkbox" checked >Lives</label>_x000D_
_x000D_
<script type="application/javascript" >_x000D_
    lfckv = document.getElementsByClassName("lifecheck");_x000D_
    if (true === lfckv[0].checked) {_x000D_
      alert('the checkbox is checked');_x000D_
    }_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

so after you can add event in javascript to have dynamical event affected with the checkbox .

thanks

How to test an Oracle Stored Procedure with RefCursor return type?

I think this link will be enough for you. I found it when I was searching for the way to execute oracle procedures.

The link to the page

Short Description:

--cursor variable declaration 
variable Out_Ref_Cursor refcursor;
--execute procedure 
execute get_employees_name(IN_Variable,:Out_Ref_Cursor);
--display result referenced by ref cursor.
print Out_Ref_Cursor;

Determining 32 vs 64 bit in C++

I'd place 32-bit and 64-bit sources in different files and then select appropriate source files using the build system.

"Warning: iPhone apps should include an armv6 architecture" even with build config set

I tried all the answers above ,none resolved my question. So I create a new project and diff the build settings one by one. Only "Alternate Permissions Files" is different. The project build failed has a value armv7. Delete it then clean->build->archive . Succeed! Hope can solve you question

Java Spring - How to use classpath to specify a file location?

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.

/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:

InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");

If the result is not null (resource not found), feel free to wrap it in a reader:

Reader reader = new InputStreamReader(is);

How to convert a HTMLElement to a string

The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.

var imported = document.createElement('script');
imported.src = 'http://code.jquery.com/jquery-1.7.1.js';
var tmpHead = document.head.innerHTML;
document.head.innerHTML = "";
document.head.append(imported);
document.head.innerHTML += tmpHead;

That simple :)

How can I keep Bootstrap popovers alive while being hovered?

This is my code for show dynamics tooltips with delay and loaded by ajax.

_x000D_
_x000D_
$(window).on('load', function () {_x000D_
    generatePopovers();_x000D_
    _x000D_
    $.fn.dataTable.tables({ visible: true, api: true }).on('draw.dt', function () {_x000D_
        generatePopovers();_x000D_
    });_x000D_
});_x000D_
_x000D_
$(document).ajaxStop(function () {_x000D_
    generatePopovers();_x000D_
});
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
function generatePopovers() {_x000D_
var popover = $('a[href*="../Something.aspx"]'); //locate the elements to popover_x000D_
_x000D_
popover.each(function (index) {_x000D_
    var poplink = $(this);_x000D_
    if (poplink.attr("data-toggle") == null) {_x000D_
        console.log("RENDER POPOVER: " + poplink.attr('href'));_x000D_
        poplink.attr("data-toggle", "popover");_x000D_
        poplink.attr("data-html", "true");_x000D_
        poplink.attr("data-placement", "top");_x000D_
        poplink.attr("data-content", "Loading...");_x000D_
        poplink.popover({_x000D_
            animation: false,_x000D_
            html: true,_x000D_
            trigger: 'manual',_x000D_
            container: 'body',_x000D_
            placement: 'top'_x000D_
        }).on("mouseenter", function () {_x000D_
            var thispoplink = poplink;_x000D_
            setTimeout(function () {_x000D_
                if (thispoplink.is(":hover")) {_x000D_
                    thispoplink.popover("show");_x000D_
                    loadDynamicData(thispoplink); //load data by ajax if you want_x000D_
                    $('body .popover').on("mouseleave", function () {_x000D_
                        thispoplink.popover('hide');_x000D_
                    });_x000D_
                }_x000D_
            }, 1000);_x000D_
        }).on("mouseleave", function () {_x000D_
            var thispoplink = poplink;_x000D_
            setTimeout(function () {_x000D_
                if (!$("body").find(".popover:hover").length) {_x000D_
                    thispoplink.popover("hide");_x000D_
                }_x000D_
            }, 100);_x000D_
        });_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
function loadDynamicData(popover) {_x000D_
    var params = new Object();_x000D_
    params.somedata = popover.attr("href").split("somedata=")[1]; //obtain a parameter to send_x000D_
    params = JSON.stringify(params);_x000D_
    //check if the content is not seted_x000D_
    if (popover.attr("data-content") == "Loading...") {_x000D_
        $.ajax({_x000D_
            type: "POST",_x000D_
            url: "../Default.aspx/ObtainData",_x000D_
            data: params,_x000D_
            contentType: "application/json; charset=utf-8",_x000D_
            dataType: 'json',_x000D_
            success: function (data) {_x000D_
                console.log(JSON.parse(data.d));_x000D_
                var dato = JSON.parse(data.d);_x000D_
                if (dato != null) {_x000D_
                    popover.attr("data-content",dato.something); // here you can set the data returned_x000D_
                    if (popover.is(":hover")) {_x000D_
                        popover.popover("show"); //use this for reload the view_x000D_
                    }_x000D_
                }_x000D_
            },_x000D_
_x000D_
            failure: function (data) {_x000D_
                itShowError("- Error AJAX.<br>");_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How do I pull my project from github?

Git clone is the command you're looking for:

git clone [email protected]:username/repo.git

Update: And this is the official guide: https://help.github.com/articles/fork-a-repo

Take a look at: https://help.github.com/

It has really useful content

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
var keys = [];

for (var k in obj) keys.push(k);

console.log("total " + keys.length + " keys: " + keys);
_x000D_
_x000D_
_x000D_

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

How to extend / inherit components?

update

Component inheritance is supported since 2.3.0-rc.0

original

So far, the most convenient for me is to keep template & styles into separate *html & *.css files and specify those through templateUrl and styleUrls, so it's easy reusable.

@Component {
    selector: 'my-panel',
    templateUrl: 'app/components/panel.html', 
    styleUrls: ['app/components/panel.css']
}
export class MyPanelComponent extends BasePanelComponent

How to check a string against null in java?

Of course user351809, stringname.equalsignorecase(null) will throw NullPointerException.
See, you have a string object stringname, which follows 2 possible conditions:-

  1. stringname has a some non-null string value (say "computer"):
    Your code will work fine as it takes the form
    "computer".equalsignorecase(null)
    and you get the expected response as false.
  2. stringname has a null value:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, null is not an object that can execute the equalsignorecase() method.

Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null

UML diagram shapes missing on Visio 2013

If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.

  • Search for UML Sequence in the search box -> Select all shapes and add to My shapes (user defined name).

You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.

How do I capture response of form.submit

First of all we will need serializeObject();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

then you make a basic post and get response

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

Finalize vs Dispose

To answer on the first part you should provide examples where people use different approach for the exact same class-object. Otherwise it is difficult (or even strange) to answer.

As for the second question better read first this Proper use of the IDisposable interface which claims that

It's your choice! But choose Dispose.

In other words: The GC only knows about finalizer (if any. Also known as destructor to Microsoft). A good code will attempt to cleanup from both (finalizer and Dispose).

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

How to put a div in center of browser using CSS?

You can also set your div with the following:

#something {width: 400px; margin: auto;}

With that setting, the div will have a set width, and the margin and either side will automatically set depending on the with of the browser.

ActionBarActivity: cannot be resolved to a type

For Eclipse, modify project.properties like this: (your path please)

android.library.reference.1=../../../../workspace/appcompat_v7_22

And remove android-support-v4.jar file in your project's libs folder.

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

How to query for Xml values and attributes from table in SQL Server?

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

Git on Windows: How do you set up a mergetool?

To setup p4merge, installed using chocolatey on windows for both merge and diff, take a look here: https://gist.github.com/CamW/88e95ea8d9f0786d746a

How to copy directory recursively in python and overwrite all?

My simple answer.

def get_files_tree(src="src_path"):
    req_files = []
    for r, d, files in os.walk(src):
        for file in files:
            src_file = os.path.join(r, file)
            src_file = src_file.replace('\\', '/')
            if src_file.endswith('.db'):
                continue
            req_files.append(src_file)

    return req_files
def copy_tree_force(src_path="",dest_path=""):
    """
    make sure that all the paths has correct slash characters.
    """
    for cf in get_files_tree(src=src_path):
        df= cf.replace(src_path, dest_path)
        if not os.path.exists(os.path.dirname(df)):
            os.makedirs(os.path.dirname(df))
        shutil.copy2(cf, df)

How to import image (.svg, .png ) in a React Component

You can use require as well to render images like

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}

How to align td elements in center

margin:auto; text-align, if this won't work - try adding display:block; and set there width:200px; (in case your TD is too small).

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Remove trailing newline from the elements of a string list

All other answers, and mainly about list comprehension, are great. But just to explain your error:

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

a is a member of your list, not an index. What you could write is this:

[...]
for a in lines:
    strip_list.append(a.strip())

Another important comment: you can create an empty list this way:

strip_list = [0] * 20

But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

So your code should be like:

strip_list = []
for a in lines:
    strip_list.append(a.strip())

But, for sure, the best one is this one, as this is exactly the same thing:

stripped = [line.strip() for line in lines]

In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Deleting/commenting

- (void)viewWillAppear:(BOOL)animated {[super viewWillAppear:YES];}

function solved the problem for me.

XCode (11.3.1)

How to manage exceptions thrown in filters in Spring?

If you want a generic way, you can define an error page in web.xml:

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/500</location>
</error-page>

And add mapping in Spring MVC:

@Controller
public class ErrorController {

    @RequestMapping(value="/500")
    public @ResponseBody String handleException(HttpServletRequest req) {
        // you can get the exception thrown
        Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");

        // customize response to what you want
        return "Internal server error.";
    }
}

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

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

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

How do I implement a progress bar in C#?

If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

Reading binary file and looping over each byte

This generator yields bytes from a file, reading the file in chunks:

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

# example:
for b in bytes_from_file('filename'):
    do_stuff_with(b)

See the Python documentation for information on iterators and generators.

Android Image View Pinch Zooming

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    ImageView view = (ImageView) v;
    dumpEvent(event);

    // Handle touch events here...
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        savedMatrix.set(matrix);
        start.set(event.getX(), event.getY());
        Log.d(TAG, "mode=DRAG");
        mode = DRAG;
        break;
    case MotionEvent.ACTION_POINTER_DOWN:
        oldDist = spacing(event);
        Log.d(TAG, "oldDist=" + oldDist);
        if (oldDist > 10f) {
            savedMatrix.set(matrix);
            midPoint(mid, event);
            mode = ZOOM;
            Log.d(TAG, "mode=ZOOM");
        }
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
        mode = NONE;
        Log.d(TAG, "mode=NONE");
        break;
    case MotionEvent.ACTION_MOVE:
        if (mode == DRAG) {
            // ...
            matrix.set(savedMatrix);
            matrix.postTranslate(event.getX() - start.x, event.getY()
                    - start.y);
        } else if (mode == ZOOM) {
            float newDist = spacing(event);
            Log.d(TAG, "newDist=" + newDist);
            if (newDist > 10f) {
                matrix.set(savedMatrix);
                float scale = newDist / oldDist;
                matrix.postScale(scale, scale, mid.x, mid.y);
            }
        }
        break;
    }

    view.setImageMatrix(matrix);
    return true;
}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
    Log.d(TAG, sb.toString());
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return FloatMath.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}

and dont forget to set scaleType property to matrix of ImageView tag like:

<ImageView
    android:id="@+id/imageEnhance"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:background="@drawable/enhanceimageframe"
    android:scaleType="matrix" >
</ImageView>

and the variables used are:

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

How to force child div to be 100% of parent div's height without specifying parent's height?

Based on the method described in this article I have created .Less dynamic solution:

Html:

<div id="container3">
    <div id="container2">
        <div id="container1">
            <div id="col1">Column 1</div>
            <div id="col2">Column 2</div>
            <div id="col3">Column 3</div>
        </div>
    </div>
</div>

Less:

/* Changes these variables to adjust your columns */
@col1Width: 60%;
@col2Width: 1%;
@padding: 0%;

/* Misc variable. Do not change */
@col3Width: 100% - @col1Width - @col2Width;

#container3 {
    float: left;
    width: 100%;
    overflow: hidden;
    background-color: red;
    position: relative;

    #container2 {
        float: left;
        width: 100%;
        position: relative;
        background-color: yellow;
        right: @col3Width;

        #container1 {
            float: left;
            width: 100%;
            position: relative;
            right: @col2Width;
            background-color: green;

            #col1 {
                float: left;
                width: @col1Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding;
                overflow: hidden;
            }

            .col2 {
                float: left;
                width: @col2Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding + @padding * 2;
                overflow: hidden;
            }

            #col3 {
                float: left;
                width: @col3Width - @padding * 2;
                position: relative;
                left: 100% - @col1Width + @padding + @padding * 4;
                overflow: hidden;
            }
        }
    }
}

R object identification

If I get 'someObject', say via

someObject <- myMagicFunction(...)

then I usually proceed by

class(someObject)
str(someObject)

which can be followed by head(), summary(), print(), ... depending on the class you have.

Bootstrap modal z-index

ok, so if you are using bootstrap-rtl.css, what you can do is go to the following class .modal-backdrop and remove the z-index attribute. after that all should be fine

Mapping two integers to one, in a unique and deterministic way

The standard mathematical way for positive integers is to use the uniqueness of prime factorization.

f( x, y ) -> 2^x * 3^y

The downside is that the image tends to span quite a large range of integers so when it comes to expressing the mapping in a computer algorithm you may have issues with choosing an appropriate type for the result.

You could modify this to deal with negative x and y by encoding a flags with powers of 5 and 7 terms.

e.g.

f( x, y ) -> 2^|x| * 3^|y| * 5^(x<0) * 7^(y<0)

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

OpenJDK availability for Windows OS

You can find the thoroughly tested OpenJDK releases provided by Oracle at http://jdk.java.net .

For example, ready to use builds of OpenJDK 10.0.2 from Oracle for 64-bit Linux, MacOS and Windows can be found at http://jdk.java.net/10/ .

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It is because of CASCADE TYPE

if you put

@OneToOne(cascade=CascadeType.ALL)

You can just save your object like this

user.setCountry(country);
session.save(user)

but if you put

 @OneToOne(cascade={    
            CascadeType.PERSIST,
            CascadeType.REFRESH,
            ...
})

You need to save your object like this

user.setCountry(country);
session.save(country)
session.save(user)

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

I found that because I was using a network-oriented command in my rc.local, sometimes it would fail. I fixed this by putting sleep 3 at the top of my script. I don't know why but it seems when the script is run the network interfaces aren't properly configured or something, and this just allows some time for the DHCP server or something. I don't fully understand but I suppose you could give it a try.

Fastest way to copy a file in Node.js

All previous solutions that do not check an existence of a source file are dangerous... For example,

fs.stat(source, function(err,stat) { if (err) { reject(err) }

Otherwise there is a risk in a scenario in case the source and target are by a mistake replaced, your data will be permanently lost without noticing any error.

How to analyze a JMeter summary report?

The JMeter docs say the following:

The summary report creates a table row for each differently named request in your test. This is similar to the Aggregate Report , except that it uses less memory. The thoughput is calculated from the point of view of the sampler target (e.g. the remote server in the case of HTTP samples). JMeter takes into account the total time over which the requests have been generated. If other samplers and timers are in the same thread, these will increase the total time, and therefore reduce the throughput value. So two identical samplers with different names will have half the throughput of two samplers with the same name. It is important to choose the sampler labels correctly to get the best results from the Report.

  • Label - The label of the sample. If "Include group name in label?" is selected, then the name of the thread group is added as a prefix. This allows identical labels from different thread groups to be collated separately if required.
  • # Samples - The number of samples with the same label
  • Average - The average elapsed time of a set of results
  • Min - The lowest elapsed time for the samples with the same label
  • Max - The longest elapsed time for the samples with the same label
  • Std. Dev. - the Standard Deviation of the sample elapsed time
  • Error % - Percent of requests with errors
  • Throughput - the Throughput is measured in requests per second/minute/hour. The time unit is chosen so that the displayed rate is at least 1.0. When the throughput is saved to a CSV file, it is expressed in requests/second, i.e. 30.0 requests/minute is saved as 0.5.
  • Kb/sec - The throughput measured in Kilobytes per second
  • Avg. Bytes - average size of the sample response in bytes. (in JMeter 2.2 it wrongly showed the value in kB)

Times are in milliseconds.

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Conversion failed when converting the nvarchar value ... to data type int

I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.

Capture :

enter image description here

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How to convert date format to milliseconds?

You could use

Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();

Disable same origin policy in Chrome

You can simply use this chrome extension Allow-Control-Allow-Origin

just click the icon of the extensnion to turn enable cross-resource sharing ON or OFF as you want

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

How can I remove leading and trailing quotes in SQL Server?

You can use following query which worked for me-

For updating-

UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...

For selecting-

SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName

Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

Create listview in fragment android

you need to give:

public void onActivityCreated(Bundle savedInstanceState)    
{
  super.onActivityCreated(savedInstanceState);
}

inside fragment.

Call jQuery Ajax Request Each X Minutes

You have a couple options, you could setTimeout() or setInterval(). Here's a great article that elaborates on how to use them.

The magic is that they're built in to JavaScript, you can use them with any library.

Turning off eslint rule for a specific line

To disable all rules on a specific line:

alert('foo'); // eslint-disable-line

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

Distribution certificate / private key not installed

If you are being stuck on this problem. After switch the computer and not able to upload your build to App Store. Simply click manage certificate on the error page, the + plus on the bottom left corner and create a new distribution certificate. Then you'll be good to go.

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

Rounding integer division (instead of truncating)

try using math ceil function that makes rounding up. Math Ceil !

How to run a JAR file

Java

class Hello{
   public static void main(String [] args){
    System.out.println("Hello Shahid");
   }
}

manifest.mf

Manifest-version: 1.0
Main-Class: Hello

On command Line:

$ jar cfm HelloMss.jar  manifest.mf Hello.class 
$ java -jar HelloMss.jar

Output:

Hello Shahid

MySQL - Cannot add or update a child row: a foreign key constraint fails

I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field

for example, you want to add foreign key inside (attendance) table to the column (employeeName)

where the parent is (employees) table, (employeeName) column

all the data in attendance.employeeName must be matching employee.employeeName

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I had the same issue here. As Magnus said above, for me it was happening due to an SDK update to version 22.0.5.

After performing a full update in my Android SDK (including Google Play Services) and Android plugins in Eclipse, I was able to use play services lib in my application.

How to stop flask application without using ctrl-c

This is an old question, but googling didn't give me any insight in how to accomplish this.

Because I didn't read the code here properly! (Doh!) What it does is to raise a RuntimeError when there is no werkzeug.server.shutdown in the request.environ...

So what we can do when there is no request is to raise a RuntimeError

def shutdown():
    raise RuntimeError("Server going down")

and catch that when app.run() returns:

...
try:
    app.run(host="0.0.0.0")
except RuntimeError, msg:
    if str(msg) == "Server going down":
        pass # or whatever you want to do when the server goes down
    else:
        # appropriate handling/logging of other runtime errors
# and so on
...

No need to send yourself a request.

adb not finding my device / phone (MacOS X)

Here is another thing to try, if like me you have tried all of the other answers and have had no luck.

In my case (Android 4.3) I went into the USB settings under the notifications and changed from MTP mode (Media device) to PTP (camera) and as soon as it switched, the device showed up in the ADT device list.

MySQL - DATE_ADD month interval

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

JavaScript or jQuery browser back button click detector

Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type

if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
  // back or forward button functionality
}

This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - 
    p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);

    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - 
    p.unloadEventStart));

    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

Interface naming in Java

In C# it is

public class AdminForumUser : UserBase, IUser

Java would say

public class AdminForumUser extends User implements ForumUserInterface

Because of that, I don't think conventions are nearly as important in java for interfaces, since there is an explicit difference between inheritance and interface implementation. I would say just choose any naming convention you would like, as long as you are consistant and use something to show people that these are interfaces. Haven't done java in a few years, but all interfaces would just be in their own directory, and that was the convention. Never really had any issues with it.

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

PHP Multidimensional Array Searching (Find key by specific value)

I would do like below, where $products is the actual array given in the problem at the very beginning.

print_r(
  array_search("breville-variable-temperature-kettle-BKE820XL", 
  array_map(function($product){return $product["slug"];},$products))
);

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

How do you convert a byte array to a hexadecimal string in C?

For completude, you can also easily do it without calling any heavy library function (no snprintf, no strcat, not even memcpy). It can be useful, say if you are programming some microcontroller or OS kernel where libc is not available.

Nothing really fancy you can find similar code around if you google for it. Really it's not much more complicated than calling snprintf and much faster.

#include <stdio.h>

int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    int i = 0;
    for(; i < sizeof(buf)-1; ++i){
        *pout++ = hex[(*pin>>4)&0xF];
        *pout++ = hex[(*pin++)&0xF];
        *pout++ = ':';
    }
    *pout++ = hex[(*pin>>4)&0xF];
    *pout++ = hex[(*pin)&0xF];
    *pout = 0;

    printf("%s\n", str);
}

Here is another slightly shorter version. It merely avoid intermediate index variable i and duplicating laste case code (but the terminating character is written two times).

#include <stdio.h>
int main(){
    unsigned char buf[] = {0, 1, 10, 11};
    /* target buffer should be large enough */
    char str[12];

    unsigned char * pin = buf;
    const char * hex = "0123456789ABCDEF";
    char * pout = str;
    for(; pin < buf+sizeof(buf); pout+=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
    }
    pout[-1] = 0;

    printf("%s\n", str);
}

Below is yet another version to answer to a comment saying I used a "trick" to know the size of the input buffer. Actually it's not a trick but a necessary input knowledge (you need to know the size of the data that you are converting). I made this clearer by extracting the conversion code to a separate function. I also added boundary check code for target buffer, which is not really necessary if we know what we are doing.

#include <stdio.h>

void tohex(unsigned char * in, size_t insz, char * out, size_t outsz)
{
    unsigned char * pin = in;
    const char * hex = "0123456789ABCDEF";
    char * pout = out;
    for(; pin < in+insz; pout +=3, pin++){
        pout[0] = hex[(*pin>>4) & 0xF];
        pout[1] = hex[ *pin     & 0xF];
        pout[2] = ':';
        if (pout + 3 - out > outsz){
            /* Better to truncate output string than overflow buffer */
            /* it would be still better to either return a status */
            /* or ensure the target buffer is large enough and it never happen */
            break;
        }
    }
    pout[-1] = 0;
}

int main(){
    enum {insz = 4, outsz = 3*insz};
    unsigned char buf[] = {0, 1, 10, 11};
    char str[outsz];
    tohex(buf, insz, str, outsz);
    printf("%s\n", str);
}

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

For me, on centOS 7 I had to remove the old pip link from /bin by

rm /bin/pip2.7 
rm /bin/pip

then relink it with

sudo ln -s  /usr/local/bin/pip2.7 /bin/pip2.7

Then if

/usr/local/bin/pip2.7

Works, this should work

How to remove the Flutter debug banner?

You can give simply hide this by giving a boolean parameter-----> debugShowCheckedModeBanner: false,

void main() {
  Bloc.observer = SimpleBlocDelegate();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Prescription Writing Software',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.white,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashScreen(),
    );
  }
}

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Java Desktop application: SWT vs. Swing

I would use Swing for a couple of reasons.

  • It has been around longer and has had more development effort applied to it. Hence it is likely more feature complete and (maybe) has fewer bugs.

  • There is lots of documentation and other guidance on producing performant applications.

  • It seems like changes to Swing propagate to all platforms simultaneously while changes to SWT seem to appear on Windows first, then Linux.

If you want to build a very feature-rich application, you might want to check out the NetBeans RCP (Rich Client Platform). There's a learning curve, but you can put together nice applications quickly with a little practice. I don't have enough experience with the Eclipse platform to make a valid judgment.

If you don't want to use the entire RCP, NetBeans also has many useful components that can be pulled out and used independently.

One other word of advice, look into different layout managers. They tripped me up for a long time when I was learning. Some of the best aren't even in the standard library. The MigLayout (for both Swing and SWT) and JGoodies Forms tools are two of the best in my opinion.

Download and open PDF file using Ajax

I don't really think that any of the past answers spotted out the problem of the original poster. They all presume a GET request while the poster was trying to POST data and get a download in response.

In the course of searching for any better answer we found this jQuery Plugin for Requesting Ajax-like File Downloads.

In its "heart" it creates a "temporary" HTML form containing the given data as input fields. This form is appended to the document and posted to the desired URL. Right after that the form is removed again:

jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
    .appendTo('body').submit().remove()

Update Mayur's answer looks pretty promising and very simple in comparison to the jQuery plug-in I referred to.

Display animated GIF in iOS

FLAnimatedImage is a performant open source animated GIF engine for iOS:

  • Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers
  • Honors variable frame delays
  • Behaves gracefully under memory pressure
  • Eliminates delays or blocking during the first playback loop
  • Interprets the frame delays of fast GIFs the same way modern browsers do

It's a well-tested component that I wrote to power all GIFs in Flipboard.

How to call an element in a numpy array?

If you are using numpy and your array is an np.array of np.array elements like:

A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])

and you want to access the inner elements (like 10,11,12 13,14.......) then use:

A[0][0] instead of A[0,0]

For example:

>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR

(P.S.: Might be useful when using numpy.array_split())

Does Index of Array Exist

// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:

int index = 25;

if (index >= 0 && index < array.Length)
{
    // Array element found
}

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

Should I use encodeURI or encodeURIComponent for encoding URLs?

If you're encoding a string to put in a URL component (a querystring parameter), you should call encodeURIComponent.

If you're encoding an existing URL, call encodeURI.

How to change the default browser to debug with in Visual Studio 2008?

If you use MVC, you don't have this menu (no "Browse With..." menu)

Create first a normal ASP.NET web site.

ReflectionException: Class ClassName does not exist - Laravel

composer dump-autoload
php artisan config:clear
php artisan cache:clear

This will surely work. If not then, you need to do

composer update

and then, the aforementioned commands.

Total number of items defined in an enum

I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:

var namesCount = (int)MyEnum.Length;

Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.

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

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

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

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

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

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

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

Get the POST request body from HttpServletRequest

If all you want is the POST request body, you could use a method like this:

static String extractPostRequestBody(HttpServletRequest request) throws IOException {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

Credit to: https://stackoverflow.com/a/5445161/1389219

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

If (Array.Length == 0)

As other have already suggested it is likely you are getting a NullReferenceException which can be avoided by first checking to see if the reference is null. However, you need to ask yourself whether that check is actually warranted. Would you be doing it because the reference really might be null and it being null has a special meaning in your code? Or would you be doing it to cover up a bug? The nature of the question leads me to believe it would be the latter. In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

SET sql_mode = 'NO_ZERO_DATE';

I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

Javascript checkbox onChange

Javascript

  // on toggle method
  // to check status of checkbox
  function onToggle() {
    // check if checkbox is checked
    if (document.querySelector('#my-checkbox').checked) {
      // if checked
      console.log('checked');
    } else {
      // if unchecked
      console.log('unchecked');
    }
  }

HTML

<input id="my-checkbox" type="checkbox" onclick="onToggle()">

How to redirect user's browser URL to a different page in Nodejs?

For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

How to check if the given string is palindrome?

Scala

def pal(s:String) = Symbol(s) equals Symbol(s.reverse)

How to change Bootstrap's global default font size?

In v4 change the SASS variable:

$font-size-base: 1rem !default;

Best way to remove the last character from a string built with stringbuilder

The simplest and most efficient way is to perform this command:

data.Length--;

by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

data.Length = 0;

again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.

Total memory used by Python process?

Using sh and os to get into python bayer's answer.

float(sh.awk(sh.ps('u','-p',os.getpid()),'{sum=sum+$6}; END {print sum/1024}'))

Answer is in megabytes.

How to scroll up or down the page to an anchor using jQuery?

function scroll_to_anchor(anchor_id){
    var tag = $("#"+anchor_id+"");
    $('html,body').animate({scrollTop: tag.offset().top},'slow');
}

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

C# testing to see if a string is an integer?

Maybe this can be another solution

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

Disable color change of anchor tag when visited

For those who are dynamically applying classes (i.e. active): Simply add a "div" tag inside the "a" tag with an href attribute:

<a href='your-link'>
  <div>
    <span>your link name</span>
  </div>
</a>

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

Windows error 2 occured while loading the Java VM

Launch the installer with the following command line parameters:

LAX_VM

For example: InstallXYZ.exe LAX_VM "C:\Program Files (x86)\Java\jre6\bin\java.exe"

Given a DateTime object, how do I get an ISO 8601 date in string format?

I would just use XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

It will automatically preserve the time zone.

angularjs getting previous route path

modification for the code above:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('prev path: ' + absOldUrl.$$route.originalPath);
});

How to update PATH variable permanently from Windows command line?

This Python-script[*] does exactly that:

"""
Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.

First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and 
if not accessible due to admin-rights missing, fails-back 
to HKEY_CURRENT_USER.
Write and Delete operations do not proceed to user-tree if all-users succeed.

Syntax: 
    {prog}                  : Print all env-vars. 
    {prog}  VARNAME         : Print value for VARNAME. 
    {prog}  VARNAME   VALUE : Set VALUE for VARNAME. 
    {prog}  +VARNAME  VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`). 
    {prog}  -VARNAME        : Delete env-var value. 

Note that the current command-window will not be affected, 
changes would apply only for new command-windows.
"""

import winreg
import os, sys, win32gui, win32con

def reg_key(tree, path, varname):
    return '%s\%s:%s' % (tree, path, varname) 

def reg_entry(tree, path, varname, value):
    return '%s=%s' % (reg_key(tree, path, varname), value)

def query_value(key, varname):
    value, type_id = winreg.QueryValueEx(key, varname)
    return value

def yield_all_entries(tree, path, key):
    i = 0
    while True:
        try:
            n,v,t = winreg.EnumValue(key, i)
            yield reg_entry(tree, path, n, v)
            i += 1
        except OSError:
            break ## Expected, this is how iteration ends.

def notify_windows(action, tree, path, varname, value):
    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
    print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)

def manage_registry_env_vars(varname=None, value=None):
    reg_keys = [
        ('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
        ('HKEY_CURRENT_USER', r'Environment'),
    ]
    for (tree_name, path) in reg_keys:
        tree = eval('winreg.%s'%tree_name)
        try:
            with winreg.ConnectRegistry(None, tree) as reg:
                with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
                    if not varname:
                        for regent in yield_all_entries(tree_name, path, key):
                            print(regent)
                    else:
                        if not value:
                            if varname.startswith('-'):
                                varname = varname[1:]
                                value = query_value(key, varname)
                                winreg.DeleteValue(key, varname)
                                notify_windows("Deleted", tree_name, path, varname, value)
                                break  ## Don't propagate into user-tree.
                            else:
                                value = query_value(key, varname)
                                print(reg_entry(tree_name, path, varname, value))
                        else:
                            if varname.startswith('+'):
                                varname = varname[1:]
                                value = query_value(key, varname) + ';' + value
                            winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
                            notify_windows("Updated", tree_name, path, varname, value)
                            break  ## Don't propagate into user-tree.
        except PermissionError as ex:
            print("!!!Cannot access %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)
        except FileNotFoundError as ex:
            print("!!!Cannot find %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)

if __name__=='__main__':
    args = sys.argv
    argc = len(args)
    if argc > 3:
        print(__doc__.format(prog=args[0]), file=sys.stderr)
        sys.exit()

    manage_registry_env_vars(*args[1:])

Below are some usage examples, assuming it has been saved in a file called setenv.py somewhere in your current path. Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:

> REM ## Print all env-vars
> setenv.py
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
HKEY_CURRENT_USER\Environment:PATH=...
...

> REM ## Query env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified

> REM ## Set env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo

> REM ## Append env-var:
> setenv.py +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar

> REM ## Delete env-var:
> setenv.py -PATH
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH

[*] Adapted from: http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/

Signed to unsigned conversion in C - is it always safe?

As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.

However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:

int iValue, iResult;
unsigned int uValue, uResult;

It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.

Convert string to hex-string in C#

First you'll need to get it into a byte[], so do this:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

NOTE: you could use a different Encoding if you needed to.

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Clear data in MySQL table with PHP?

TRUNCATE TABLE tablename

or

DELETE FROM tablename

The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

Actually, wasn't this already answered in your other question?

Golang append an item to a slice

In order to make your code work without having to return the slice from Test, you can pass a pointer like this:

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice *[]int) {
    *slice = append(*slice, 100)

    fmt.Println(*slice)
}

func main() {

    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(&a)

    fmt.Println(a)
}

Change font-weight of FontAwesome icons?

Another solution I've used to create lighter fontawesome icons, similar to the webkit-text-stroke approach but more portable, is to set the color of the icon to the same as the background (or transparent) and use text-shadow to create an outline:

.fa-outline-dark-gray {
    color: #fff;
    text-shadow: -1px -1px 0 #999,
            1px -1px 0 #999,
           -1px 1px 0 #999,
            1px 1px 0 #999;
}

It doesn't work in ie <10, but at least it's not restricted to webkit browsers.

Why should I prefer to use member initialization lists?

Next to the performance issues, there is another one very important which I'd call code maintainability and extendibility.

If a T is POD and you start preferring initialization list, then if one time T will change to a non-POD type, you won't need to change anything around initialization to avoid unnecessary constructor calls because it is already optimised.

If type T does have default constructor and one or more user-defined constructors and one time you decide to remove or hide the default one, then if initialization list was used, you don't need to update code if your user-defined constructors because they are already correctly implemented.

Same with const members or reference members, let's say initially T is defined as follows:

struct T
{
    T() { a = 5; }
private:
    int a;
};

Next, you decide to qualify a as const, if you would use initialization list from the beginning, then this was a single line change, but having the T defined as above, it also requires to dig the constructor definition to remove assignment:

struct T
{
    T() : a(5) {} // 2. that requires changes here too
private:
    const int a; // 1. one line change
};

It's not a secret that maintenance is far easier and less error-prone if code was written not by a "code monkey" but by an engineer who makes decisions based on deeper consideration about what he is doing.

newline in <td title="">

This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

<img src="'../images/foo.gif'" 
  alt="line 1&#013;line 2" title="line 1&#013;line 2">

Try a JavaScript tooltip library for a better result, something like OverLib.

maven "cannot find symbol" message unhelpful

In my case, I was using a dependency scoped as <scope>test</scope>. This made the class available at development time but, by at compile time, I got this message.

Turn the class scope for <scope>provided</scope> solved the problem.

Convert String array to ArrayList

in most cases the List<String> should be enough. No need to create an ArrayList

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

...

String[] words={"ace","boom","crew","dog","eon"};
List<String> l = Arrays.<String>asList(words);

// if List<String> isnt specific enough:
ArrayList<String> al = new ArrayList<String>(l);

Select random lines from a file

Use shuf with the -n option as shown below, to get N random lines:

shuf -n N input > output

C# Error: Parent does not contain a constructor that takes 0 arguments

You need to change your child's constructor to:

public child(int i) : base(i)
{
    // etc...
}

You were getting the error because your parent class's constructor takes a parameter but you are not passing that parameter from the child to the parent.

Constructors are not inherited in C#, you have to chain them manually.

Sort a Map<Key, Value> by values

I rewrote devinmoore's method that performs sorting a map by it's value without using Iterator :

public static Map<K, V> sortMapByValue(Map<K, V> inputMap) {

    Set<Entry<K, V>> set = inputMap.entrySet();
    List<Entry<K, V>> list = new ArrayList<Entry<K, V>>(set);

    Collections.sort(list, new Comparator<Map.Entry<K, V>>()
    {
        @Override
        public int compare(Entry<K, V> o1, Entry<K, V> o2) {
            return (o1.getValue()).compareTo( o2.getValue() );  //Ascending order
        }
    } );

    Map<K, V> sortedMap = new LinkedHashMap<>();

    for(Map.Entry<K, V> entry : list){
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}

Note: that we used LinkedHashMap as output map, because our list has been sorted by value and now we should store our list into output map with order of inserted key,values. So if you use for example TreeMap as your output map, your map will be sorted by map keys again!

This is the main method:

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("3", "three");
    map.put("1", "one");
    map.put("5", "five");
    System.out.println("Input Map:" + map);
    System.out.println("Sorted Map:" + sortMapByValue(map));
}

Finally, this is the output:

Input Map:{1=one, 3=three, 5=five}
Sorted Map:{5=five, 1=one, 3=three}

How to input a path with a white space?

If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:

1) Java's build.properties file:

build_path='/home/ec2-user/Name\\ of\\ Directory'

Where ~/ is equal to /home/ec2-user

2) Jenkinsfile:

build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"

Inserting a string into a list without getting split into characters

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

C# Linq Where Date Between 2 Dates

If someone interested to know how to work with 2 list and between dates

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

Setting up foreign keys in phpMyAdmin?

In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).

enter image description here

You can assign the forging key from the list box near by the primary key.(See image below). and save

enter image description here

corresponding SQL query automatically generated and executed.

Online PHP syntax checker / validator

I found this for online php validation:-

http://www.icosaedro.it/phplint/phplint-on-line.html

Hope this helps.

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Getting index value on razor foreach

Or you could simply do this:

@foreach(var myItem in Model.Members)
{    
    <span>@Model.Members.IndexOf(myItem)</span>
}

Create Excel file in Java

I've created the API "generator-excel" to create an Excel file, below the dependecy:

<dependency>
  <groupId>com.github.bld-commons.excel</groupId>
  <artifactId>generator-excel</artifactId>
  <version>3.1.0</version>
</dependency>

This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop

  1. I created 2 classes that represents the row of the table.
  2. package bld.generator.report.junit.entity;
        
        import java.util.Date;
        
        import org.apache.poi.ss.usermodel.HorizontalAlignment;
        
        import bld.generator.report.excel.RowSheet;
        import bld.generator.report.excel.annotation.ExcelCellLayout;
        import bld.generator.report.excel.annotation.ExcelColumn;
        import bld.generator.report.excel.annotation.ExcelDate;
        import bld.generator.report.excel.annotation.ExcelImage;
        import bld.generator.report.excel.annotation.ExcelRowHeight;
        
        @ExcelRowHeight(height = 3)
        public class UtenteRow implements RowSheet {
            
            @ExcelColumn(columnName = "Id", indexColumn = 0)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
            private Integer idUtente; 
            @ExcelColumn(columnName = "Nome", indexColumn = 2)
            @ExcelCellLayout
            private String nome; 
            @ExcelColumn(columnName = "Cognome", indexColumn = 1)
            @ExcelCellLayout
            private String cognome;
            @ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
            @ExcelDate
            private Date dataNascita;
            @ExcelColumn(columnName = "Immagine", indexColumn = 4)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private byte[] image;   
            
            @ExcelColumn(columnName = "Path", indexColumn = 5)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private String path;    
            
        
            public UtenteRow() {
            }
        
        
            public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
                super();
                this.idUtente = idUtente;
                this.nome = nome;
                this.cognome = cognome;
                this.dataNascita = dataNascita;
            }
        
        
            public Integer getIdUtente() {
                return idUtente;
            }
        
        
            public void setIdUtente(Integer idUtente) {
                this.idUtente = idUtente;
            }
        
        
            public String getNome() {
                return nome;
            }
        
        
            public void setNome(String nome) {
                this.nome = nome;
            }
        
        
            public String getCognome() {
                return cognome;
            }
        
        
            public void setCognome(String cognome) {
                this.cognome = cognome;
            }
        
        
            public Date getDataNascita() {
                return dataNascita;
            }
        
        
            public void setDataNascita(Date dataNascita) {
                this.dataNascita = dataNascita;
            }
        
        
            public byte[] getImage() {
                return image;
            }
        
        
            public String getPath() {
                return path;
            }
        
        
            public void setImage(byte[] image) {
                this.image = image;
            }
        
        
            public void setPath(String path) {
                this.path = path;
            }
        
        }
    

    package bld.generator.report.junit.entity;
    
    import org.apache.poi.ss.usermodel.DataConsolidateFunction;
    import org.apache.poi.ss.usermodel.HorizontalAlignment;
    
    import bld.generator.report.excel.RowSheet;
    import bld.generator.report.excel.annotation.ExcelCellLayout;
    import bld.generator.report.excel.annotation.ExcelColumn;
    import bld.generator.report.excel.annotation.ExcelFont;
    import bld.generator.report.excel.annotation.ExcelSubtotal;
    import bld.generator.report.excel.annotation.ExcelSubtotals;
    
    @ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
    public class SalaryRow implements RowSheet {
    
        @ExcelColumn(columnName = "Name", indexColumn = 0)
        @ExcelCellLayout
        private String name;
        @ExcelColumn(columnName = "Amount", indexColumn = 1)
        @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
        @ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
        private Double amount;
        
        public SalaryRow() {
            super();
        }
        public SalaryRow(String name, Double amount) {
            super();
            this.name = name;
            this.amount = amount;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Double getAmount() {
            return amount;
        }
        public void setAmount(Double amount) {
            this.amount = amount;
        }
        
    }
    
  3. I created 2 class that represents the sheets.
  4. package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.QuerySheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelQuery;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
    @ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
            + "FROM utente "
            + "WHERE cognome=:cognome "
            + "order by cognome,nome")
    public class UtenteSheet extends QuerySheetData<UtenteRow> {
        
    
        public UtenteSheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
        
    }
    

    package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.SheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
    public class SalarySheet extends SheetData<SalaryRow> {
    
        public SalarySheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
    }
    
  5. Class test, in the test function there are antoher sheets
  6. package bld.generator.report.junit;
    
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import bld.generator.report.excel.BaseSheet;
    import bld.generator.report.excel.GenerateExcel;
    import bld.generator.report.excel.data.ReportExcel;
    import bld.generator.report.junit.entity.AutoreLibriSheet;
    import bld.generator.report.junit.entity.CasaEditrice;
    import bld.generator.report.junit.entity.GenereSheet;
    import bld.generator.report.junit.entity.SalaryRow;
    import bld.generator.report.junit.entity.SalarySheet;
    import bld.generator.report.junit.entity.TotaleAutoreLibriRow;
    import bld.generator.report.junit.entity.TotaleAutoreLibriSheet;
    import bld.generator.report.junit.entity.UtenteSheet;
    import bld.generator.report.utils.ExcelUtils;
    
    /**
     * The Class ReportTest.
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ConfigurationProperties
    @ComponentScan(basePackages = {"bld.generator","bld.read"})
    @EnableTransactionManagement
    public class ReportTestJpa {
    
        /** The Constant PATH_FILE. */
        private static final String PATH_FILE = "/mnt/report/";
    
        /** The generate excel. */
        @Autowired
        private GenerateExcel generateExcel;
    
        /**
         * Sets the up.
         *
         * @throws Exception the exception
         */
        @Before
        public void setUp() throws Exception {
        }
    
        /**
         * Test.
         *
         * @throws Exception the exception
         */
        @Test
        public void test() throws Exception {
            List<BaseSheet> listBaseSheet = new ArrayList<>();
            
            UtenteSheet utenteSheet=new UtenteSheet("Utente");
            utenteSheet.getMapParameters().put("cognome", "Rossi");
            listBaseSheet.add(utenteSheet);
            
            CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
            listBaseSheet.add(casaEditrice);
            
            
            AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
            TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
            totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
            autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet);
            listBaseSheet.add(autoreLibriSheet);
            GenereSheet genereSheet=new GenereSheet("Genere");
            listBaseSheet.add(genereSheet);
            SalarySheet salarySheet=new SalarySheet("salary");
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            listBaseSheet.add(salarySheet);
            ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
    
            byte[] byteReport = this.generateExcel.createFileXlsx(excel);
    
            ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
    
        }
    
        
    
    }
    
  7. Application yaml
  8. logging:
      level:
        root: WARN
        org:
          springframework:
            web: DEBUG
          hibernate: ERROR
    
    
    
    spring:
      datasource:
        url: jdbc:postgresql://localhost:5432/excel_db
        username: ${EXCEL_USER_DB}
        password: ${EXCEL_PASSWORD_DB}
      jpa:
        show-sql: true
        properties:
          hibernate:
            default_schema: public
            jdbc:
              lob:
                non_contextual_creation: true 
            format_sql: true    
            ddl-auto: auto
        database-platform: org.hibernate.dialect.PostgreSQLDialect
        generate-ddl: true
    

below the link of the project on github:

How do I check if the mouse is over an element in jQuery?

You can test with jQuery if any child div has a certain class. Then by applying that class when you mouse over and out out a certain div, you can test whether your mouse is over it, even when you mouse over a different element on the page Much less code this way. I used this because I had spaces between divs in a pop-up, and I only wanted to close the pop up when I moved off of the pop up, not when I was moving my mouse over the spaces in the pop up. So I called a mouseover function on the content div (which the pop up was over), but it would only trigger the close function when I moused-over the content div, AND was outside the pop up!


$(".pop-up").mouseover(function(e)
    {
    $(this).addClass("over");
    });

$(".pop-up").mouseout(function(e)
    {
    $(this).removeClass("over");
    });


$("#mainContent").mouseover(function(e){
            if (!$(".expanded").hasClass("over")) {
            Drupal.dhtmlMenu.toggleMenu($(".expanded"));
        }
    });

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Casting to string in JavaScript

They do behave differently when the value is null.

  • null.toString() throws an error - Cannot call method 'toString' of null
  • String(null) returns - "null"
  • null + "" also returns - "null"

Very similar behaviour happens if value is undefined (see jbabey's answer).

Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

Jackson JSON custom serialization for certain fields

jackson-annotations provides @JsonFormat which can handle a lot of customizations without the need to write the custom serializer.

For example, requesting a STRING shape for a field with numeric type will output the numeric value as string

public class Person {
    public String name;
    public int age;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public int favoriteNumber;
}

will result in the desired output

{"name":"Joe","age":25,"favoriteNumber":"123"}

Disable cross domain web security in Firefox

The Chrome setting you refer to is to disable the same origin policy.

This was covered in this thread also: Disable firefox same origin policy

about:config -> security.fileuri.strict_origin_policy -> false

Internal Error 500 Apache, but nothing in the logs?

Check your php error log which might be a separate file from your apache error log.

Find it by going to phpinfo() and check for error_log attribute. If it is not set. Set it: https://stackoverflow.com/a/12835262/445131

Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.

VB.NET - If string contains "value1" or "value2"

You have to do it like this:

If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
    '[Put Code Here]
End if

Fatal error: Call to undefined function mysqli_connect()

On Raspberry Pi I had to install php5 mysql extension.

apt-get install php5-mysql

After installing the client, the webserver should be restarted. In case you're using apache, the following should work:

sudo service apache2 restart

jQuery Selector: Id Ends With?

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")

How do I get next month date from today's date and insert it in my database?

I know - sort of late. But I was working at the same problem. If a client buys a month of service, he/she expects to end it a month later. Here's how I solved it:

    $now = time(); 
    $day = date('j',$now);
    $year = date('o',$now);
    $month = date('n',$now);
    $hour = date('G');
    $minute = date('i');
    $month += $count;
    if ($month > 12)        {
            $month -= 12;
            $year++; 
            }
    $work = strtotime($year . "-" . $month . "-01");
    $avail = date('t',$work);
    if ($day > $avail)
            $day = $avail;
    $stamp = strtotime($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute);

This will calculate the exact day n*count months from now (where count <= 12). If the service started March 31, 2019 and runs for 11 months, it will end on Feb 29, 2020. If it runs for just one month, the end date is Apr 30, 2019.

How to Compare two Arrays are Equal using Javascript?

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

Java: Multiple class declarations in one file

1.Is there a tidy name for this technique (analogous to inner, nested, anonymous)?

Multi-class single-file demo.

2.The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )

find the array index of an object with a specific key value in underscore

If your target environment supports ES2015 (or you have a transpile step, eg with Babel), you can use the native Array.prototype.findIndex().

Given your example

const array = [ {id:1}, {id:2} ]
const desiredId = 2;
const index = array.findIndex(obj => obj.id === desiredId);

How to query between two dates using Laravel and Eloquent?

I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

You will also need to use Carbon

use Carbon\Carbon;

How do I pass a list as a parameter in a stored procedure?

As far as I can tell, there are three main contenders: Table-Valued Parameters, delimited list string, and JSON string.

Since 2016, you can use the built-in STRING_SPLIT if you want the delimited route: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

That would probably be the easiest/most straightforward/simple approach.

Also since 2016, JSON can be passed as a nvarchar and used with OPENJSON: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

That's probably best if you have a more structured data set to pass that may be significantly variable in its schema.

TVPs, it seems, used to be the canonical way to pass more structured parameters, and they are still good if you need that structure, explicitness, and basic value/type checking. They can be a little more cumbersome on the consumer side, though. If you don't have 2016+, this is probably the default/best option.

I think it's a trade off between any of these concrete considerations as well as your preference for being explicit about the structure of your params, meaning even if you have 2016+, you may prefer to explicitly state the type/schema of the parameter rather than pass a string and parse it somehow.

Parsing JSON from URL

You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:

JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

Powershell script does not run via Scheduled Tasks

If youu are having this problem under WIN 10 this might solve your problem as it did for me. An update messed up the task scheduler.

http://answers.microsoft.com/en-us/windows/forum/windows_10-performance/anniversary-update-version-1607-build14393-breaks/d034ab52-5d49-4b92-976a-a1355b5a6e6d?page=2

This comment solved my problem.

Your tip about "one-time" tasks works great - it will definitely be sufficient as a workaround until MS fixes the issue. The only advantage to "daily" as far as I can see is that lack of the arbitrary date associated with the run time. It might be confusing to others as to why the job is set to start on X date.

Trigger settings "Einmal" means "one-time", "Sofort" means "At once"

Equivalent of varchar(max) in MySQL?

The max length of a varchar is

65535

divided by the max byte length of a character in the character set the column is set to (e.g. utf8=3 bytes, ucs2=2, latin1=1).

minus 2 bytes to store the length

minus the length of all the other columns

minus 1 byte for every 8 columns that are nullable. If your column is null/not null this gets stored as one bit in a byte/bytes called the null mask, 1 bit per column that is nullable.

How to replace a substring of a string

You are probably not assigning it after doing the replacement or replacing the wrong thing. Try :

String haystack = "abcd=0; efgh=1";
String result = haystack.replaceAll("abcd","dddd");

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of 10.1.1.2 is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

How to add comments into a Xaml file in WPF?

For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:

<!--Comments Allowed With Markup Compatibility (mc) In XAML!
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
    mc:Ignorable="ØignoreØ"
    Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->

Then in the code block

<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...

AttributeNotToIgnore="TextNotToIgnore"
...

...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...   
>
</Application>

Comprehensive methods of viewing memory usage on Solaris

Top can be compiled from sources or downloaded from sunfreeware.com. As previously posted, vmstat is available (I believe it's in the core install?).

Specify sudo password for Ansible

A more savvy way to do this is to store your sudo password in a secure vault such as LastPass or KeePass and then pass it to ansible-playbook using the -e@ but instead of hardcoding the contents in an actual file, you can use the construct -e@<(...) to run a command in a sub-shell, and redirect its output (STDOUT) to a anonymous file descriptor, effectively feeding the password to the -e@<(..).

Example

$ ansible-playbook -i /tmp/hosts pb.yml \
   -e@<(echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)")

The above is doing several things, let's break it down.

  • ansible-playbook -i /tmp/hosts pb.yml - obviously running a playbook via ansible-playbook
  • $(lpass show folder1/item1 --password)" - runs the LastPass CLI lpass and retrieves the password to use
  • echo "ansible_sudo_pass: ...password..." - takes the string 'ansible_sudo_pass: ' and combines it with the password supplied by lpass
  • -e@<(..) - puts the above together, and connects the subshell of <(...) as a file descriptor for ansible-playbook to consume.

Further improvements

If you'd rather not type that every time you can simply things like so. First create an alias in your .bashrc like so:

$ cat ~/.bashrc
alias asp='echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)"'

Now you can run your playbook like this:

$ ansible-playbook -i /tmp/hosts pb.yml -e@<(asp)

References

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

How can one change the timestamp of an old commit in Git?

If you want to perform the accepted answer (https://stackoverflow.com/a/454750/72809) in standard Windows command line, you need the following command:

git filter-branch -f --env-filter "if [ $GIT_COMMIT = 578e6a450ff5318981367fe1f6f2390ce60ee045 ]; then export GIT_AUTHOR_DATE='2009-10-16T16:00+03:00'; export GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; fi"

Notes:

  • It may be possible to split the command over multiple lines (Windows supports line splitting with the carret symbol ^), but I didn't succeed.
  • You can write ISO dates, saving a lot of time finding the right day-of-week and general frustration over the order of elements.
  • If you want the Author and Committer date to be the same, you can just reference the previously set variable.

Many thanks go to a blog post by Colin Svingen. Even though his code didn't work for me, it helped me find the correct solution.

How can I make Visual Studio wrap lines at 80 characters?

Adds vertical column guides to the Visual Studio text editor. This version is for Visual Studio 2012, Visual Studio 2013 or Visual Studio 2015.

See the plugin.

Offset a background image from the right using CSS

Ok If I understand what your asking you would do this;

You have your DIV container called #main-container and .my-element that is within it. Use this to get you started;

#main-container { 
  position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
  position:absolute;
  top:0;
  right:10px;
}

/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
  float:right;
  margin-right:10px;
}

By the way, it better practice to use classes if you referencing a lower level element within a page (I assume you are hence my name change above.

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

Bootstrap 4: responsive sidebar menu to top navbar

It could be done in Bootstrap 4 using the responsive grid columns. One column for the sidebar and one for the main content.

Bootstrap 4 Sidebar switch to Top Navbar on mobile

<div class="container-fluid h-100">
    <div class="row h-100">
        <aside class="col-12 col-md-2 p-0 bg-dark">
            <nav class="navbar navbar-expand navbar-dark bg-dark flex-md-column flex-row align-items-start">
                <div class="collapse navbar-collapse">
                    <ul class="flex-md-column flex-row navbar-nav w-100 justify-content-between">
                        <li class="nav-item">
                            <a class="nav-link pl-0" href="#">Link</a>
                        </li>
                        ..
                    </ul>
                </div>
            </nav>
        </aside>
        <main class="col">
            ..
        </main>
    </div>
</div>

Alternate sidebar to top
Fixed sidebar to top

For the reverse (Top Navbar that becomes a Sidebar), can be done like this example

Value cannot be null. Parameter name: source

I got this error when I had an invalid Type for an entity property.

public Type ObjectType {get;set;}

When I removed the property the error stopped occurring.

java: HashMap<String, int> not working

int is a primitive type, you can read what does mean a primitive type in java here, and a Map is an interface that has to objects as input:

public interface Map<K extends Object, V extends Object>

object means a class, and it means also that you can create an other class that exends from it, but you can not create a class that exends from int. So you can not use int variable as an object. I have tow solutions for your problem:

Map<String, Integer> map = new HashMap<>();

or

Map<String, int[]> map = new HashMap<>();
int x = 1;

//put x in map
int[] x_ = new int[]{x};
map.put("x", x_);

//get the value of x
int y = map.get("x")[0];

Can I set an unlimited length for maxJsonLength in web.config?

I suggest setting it to Int32.MaxValue.

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How do I set the default page of my application in IIS7?

If you want to do something like,User enter url "www.xxxxxx.com/views/root/" & default page is displayed then I guess you have to set the default/home/welcome page attribute in IIS. But if user just enters "www.xxxxxx.com" and you still want to forward to your url, then you have write a line of code in the default page to forward to your desired url. This default page should be in root directory of your application, so www.xxxxx.com will load www.xxxx.com/index.html which will redirect the user to your desired url

How to set environment via `ng serve` in Angular 6

You can use command ng serve -c dev for development environment ng serve -c prod for production environment

while building also same applies. You can use ng build -c dev for dev build

Curl to return http status code along with the response

In my experience we usually use curl this way

curl -f http://localhost:1234/foo || exit 1

curl: (22) The requested URL returned error: 400 Bad Request

This way we can pipe the curl when it fails, and it also shows the status code.

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Simple state machine example in C#?

I've just contributed this:

https://code.google.com/p/ysharp/source/browse/#svn%2Ftrunk%2FStateMachinesPoC

Here's one of the examples demoing direct and indirect sending of commands, with states as IObserver(of signal), thus responders to a signal source, IObservable(of signal):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    using Machines;

    public static class WatchingTvSampleAdvanced
    {
        // Enum type for the transition triggers (instead of System.String) :
        public enum TvOperation { Plug, SwitchOn, SwitchOff, Unplug, Dispose }

        // The state machine class type is also used as the type for its possible states constants :
        public class Television : NamedState<Television, TvOperation, DateTime>
        {
            // Declare all the possible states constants :
            public static readonly Television Unplugged = new Television("(Unplugged TV)");
            public static readonly Television Off = new Television("(TV Off)");
            public static readonly Television On = new Television("(TV On)");
            public static readonly Television Disposed = new Television("(Disposed TV)");

            // For convenience, enter the default start state when the parameterless constructor executes :
            public Television() : this(Television.Unplugged) { }

            // To create a state machine instance, with a given start state :
            private Television(Television value) : this(null, value) { }

            // To create a possible state constant :
            private Television(string moniker) : this(moniker, null) { }

            private Television(string moniker, Television value)
            {
                if (moniker == null)
                {
                    // Build the state graph programmatically
                    // (instead of declaratively via custom attributes) :
                    Handler<Television, TvOperation, DateTime> stateChangeHandler = StateChange;
                    Build
                    (
                        new[]
                        {
                            new { From = Television.Unplugged, When = TvOperation.Plug, Goto = Television.Off, With = stateChangeHandler },
                            new { From = Television.Unplugged, When = TvOperation.Dispose, Goto = Television.Disposed, With = stateChangeHandler },
                            new { From = Television.Off, When = TvOperation.SwitchOn, Goto = Television.On, With = stateChangeHandler },
                            new { From = Television.Off, When = TvOperation.Unplug, Goto = Television.Unplugged, With = stateChangeHandler },
                            new { From = Television.Off, When = TvOperation.Dispose, Goto = Television.Disposed, With = stateChangeHandler },
                            new { From = Television.On, When = TvOperation.SwitchOff, Goto = Television.Off, With = stateChangeHandler },
                            new { From = Television.On, When = TvOperation.Unplug, Goto = Television.Unplugged, With = stateChangeHandler },
                            new { From = Television.On, When = TvOperation.Dispose, Goto = Television.Disposed, With = stateChangeHandler }
                        },
                        false
                    );
                }
                else
                    // Name the state constant :
                    Moniker = moniker;
                Start(value ?? this);
            }

            // Because the states' value domain is a reference type, disallow the null value for any start state value : 
            protected override void OnStart(Television value)
            {
                if (value == null)
                    throw new ArgumentNullException("value", "cannot be null");
            }

            // When reaching a final state, unsubscribe from all the signal source(s), if any :
            protected override void OnComplete(bool stateComplete)
            {
                // Holds during all transitions into a final state
                // (i.e., stateComplete implies IsFinal) :
                System.Diagnostics.Debug.Assert(!stateComplete || IsFinal);

                if (stateComplete)
                    UnsubscribeFromAll();
            }

            // Executed before and after every state transition :
            private void StateChange(IState<Television> state, ExecutionStep step, Television value, TvOperation info, DateTime args)
            {
                // Holds during all possible transitions defined in the state graph
                // (i.e., (step equals ExecutionStep.LeaveState) implies (not state.IsFinal))
                System.Diagnostics.Debug.Assert((step != ExecutionStep.LeaveState) || !state.IsFinal);

                // Holds in instance (i.e., non-static) transition handlers like this one :
                System.Diagnostics.Debug.Assert(this == state);

                switch (step)
                {
                    case ExecutionStep.LeaveState:
                        var timeStamp = ((args != default(DateTime)) ? String.Format("\t\t(@ {0})", args) : String.Empty);
                        Console.WriteLine();
                        // 'value' is the state value that we are transitioning TO :
                        Console.WriteLine("\tLeave :\t{0} -- {1} -> {2}{3}", this, info, value, timeStamp);
                        break;
                    case ExecutionStep.EnterState:
                        // 'value' is the state value that we have transitioned FROM :
                        Console.WriteLine("\tEnter :\t{0} -- {1} -> {2}", value, info, this);
                        break;
                    default:
                        break;
                }
            }

            public override string ToString() { return (IsConstant ? Moniker : Value.ToString()); }
        }

        public static void Run()
        {
            Console.Clear();

            // Create a signal source instance (here, a.k.a. "remote control") that implements
            // IObservable<TvOperation> and IObservable<KeyValuePair<TvOperation, DateTime>> :
            var remote = new SignalSource<TvOperation, DateTime>();

            // Create a television state machine instance (automatically set in a default start state),
            // and make it subscribe to a compatible signal source, such as the remote control, precisely :
            var tv = new Television().Using(remote);
            bool done;

            // Always holds, assuming the call to Using(...) didn't throw an exception (in case of subscription failure) :
            System.Diagnostics.Debug.Assert(tv != null, "There's a bug somewhere: this message should never be displayed!");

            // As commonly done, we can trigger a transition directly on the state machine :
            tv.MoveNext(TvOperation.Plug, DateTime.Now);

            // Alternatively, we can also trigger transitions by emitting from the signal source / remote control
            // that the state machine subscribed to / is an observer of :
            remote.Emit(TvOperation.SwitchOn, DateTime.Now);
            remote.Emit(TvOperation.SwitchOff);
            remote.Emit(TvOperation.SwitchOn);
            remote.Emit(TvOperation.SwitchOff, DateTime.Now);

            done =
                (
                    tv.
                        MoveNext(TvOperation.Unplug).
                        MoveNext(TvOperation.Dispose) // MoveNext(...) returns null iff tv.IsFinal == true
                    == null
                );

            remote.Emit(TvOperation.Unplug); // Ignored by the state machine thanks to the OnComplete(...) override above

            Console.WriteLine();
            Console.WriteLine("Is the TV's state '{0}' a final state? {1}", tv.Value, done);

            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
    }
}

Note : this example is rather artificial and mostly meant to demo a number of orthogonal features. There should seldomly be a real need to implement the state value domain itself by a full blown class, using the CRTP ( see : http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern ) like this.

Here's for a certainly simpler and likely much more common implementation use case (using a simple enum type as the states value domain), for the same state machine, and with the same test case :

https://code.google.com/p/ysharp/source/browse/trunk/StateMachinesPoC/WatchingTVSample.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    using Machines;

    public static class WatchingTvSample
    {
        public enum Status { Unplugged, Off, On, Disposed }

        public class DeviceTransitionAttribute : TransitionAttribute
        {
            public Status From { get; set; }
            public string When { get; set; }
            public Status Goto { get; set; }
            public object With { get; set; }
        }

        // State<Status> is a shortcut for / derived from State<Status, string>,
        // which in turn is a shortcut for / derived from State<Status, string, object> :
        public class Device : State<Status>
        {
            // Executed before and after every state transition :
            protected override void OnChange(ExecutionStep step, Status value, string info, object args)
            {
                if (step == ExecutionStep.EnterState)
                {
                    // 'value' is the state value that we have transitioned FROM :
                    Console.WriteLine("\t{0} -- {1} -> {2}", value, info, this);
                }
            }

            public override string ToString() { return Value.ToString(); }
        }

        // Since 'Device' has no state graph of its own, define one for derived 'Television' :
        [DeviceTransition(From = Status.Unplugged, When = "Plug", Goto = Status.Off)]
        [DeviceTransition(From = Status.Unplugged, When = "Dispose", Goto = Status.Disposed)]
        [DeviceTransition(From = Status.Off, When = "Switch On", Goto = Status.On)]
        [DeviceTransition(From = Status.Off, When = "Unplug", Goto = Status.Unplugged)]
        [DeviceTransition(From = Status.Off, When = "Dispose", Goto = Status.Disposed)]
        [DeviceTransition(From = Status.On, When = "Switch Off", Goto = Status.Off)]
        [DeviceTransition(From = Status.On, When = "Unplug", Goto = Status.Unplugged)]
        [DeviceTransition(From = Status.On, When = "Dispose", Goto = Status.Disposed)]
        public class Television : Device { }

        public static void Run()
        {
            Console.Clear();

            // Create a television state machine instance, and return it, set in some start state :
            var tv = new Television().Start(Status.Unplugged);
            bool done;

            // Holds iff the chosen start state isn't a final state :
            System.Diagnostics.Debug.Assert(tv != null, "The chosen start state is a final state!");

            // Trigger some state transitions with no arguments
            // ('args' is ignored by this state machine's OnChange(...), anyway) :
            done =
                (
                    tv.
                        MoveNext("Plug").
                        MoveNext("Switch On").
                        MoveNext("Switch Off").
                        MoveNext("Switch On").
                        MoveNext("Switch Off").
                        MoveNext("Unplug").
                        MoveNext("Dispose") // MoveNext(...) returns null iff tv.IsFinal == true
                    == null
                );

            Console.WriteLine();
            Console.WriteLine("Is the TV's state '{0}' a final state? {1}", tv.Value, done);

            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
    }
}

'HTH

Is there a MessageBox equivalent in WPF?

If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows

here is xaml :

<Window x:Class="popup.MessageboxNew"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:popup"
        mc:Ignorable="d"
        Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
        >
    <Window.Resources>

    </Window.Resources>
    <Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Window.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <Grid Loaded="FrameworkElement_OnLoaded">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border Name="Mask" CornerRadius="8" Background="White" />
            <Grid x:Name="Grid" Background="White">
                <Grid.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=Mask}"/>
                </Grid.OpacityMask>
                <StackPanel Name="StackPanel" >
                    <TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14" 
                             Foreground="Black" FontWeight="Normal"
                             Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
                    <DockPanel Name="ContentHost" Margin="0,10,0,10" >
                        <TextBlock Margin="10" Name="Textbar"></TextBlock>
                    </DockPanel>
                    <DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
                        <Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
                        <Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
                    </DockPanel>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

for cs of this file :

public partial class MessageboxNew : Window
    {
        public MessageboxNew()
        {
            InitializeComponent();
            //second time show error solved
            if (Application.Current == null) new Application();
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.MouseDown += delegate { DragMove(); };
        }
    }

then create a class to use this :

public class Mk_MessageBox
{
    public static bool? Show(string title, string text)
    {
        MessageboxNew msg = new MessageboxNew
        {
            TitleBar = {Text = title},
            Textbar = {Text = text}
        };
        msg.noBtn.Focus();
        return msg.ShowDialog();
    }
}

now you can create your message box like this:

var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
            if (result == true)
            {
                // whatever
            }

copy this to App.xaml inside

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
            <!-- Accent and AppTheme setting -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />

            <!--two new guys-->
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />

            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

--------------IMAGE of Result-----------------

My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/

for logic how can i make my own messagebox

gdb fails with "Unable to find Mach task port for process-id" error

Following the instructions here Codesign gdb on macOS seemed to resolve this issue, for me, on macOS High Sierra (10.13.3).

Declare Variable for a Query String

Using EXEC

You can use following example for building SQL statement.

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)

Using sp_executesql

With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Reference

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

How to add a spinner icon to button when it's in the Loading state?

If you look at the bootstrap-button.js source, you'll see that the bootstrap plugin replaces the buttons inner html with whatever is in data-loading-text when calling $(myElem).button('loading').

For your case, I think you should just be able to do this:

<button type="button"
        class="btn btn-primary start"
        id="btnStartUploads"
        data-loading-text="<i class='icon-spinner icon-spin icon-large'></i> @Localization.Uploading">
    <i class="icon-upload icon-large"></i>
    <span>@Localization.StartUpload</span>
</button>

How can I display a modal dialog in Redux that performs asynchronous actions?

The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you'd like to see:

Dispatching an Action to Show the Modal

this.props.dispatch({
  type: 'SHOW_MODAL',
  modalType: 'DELETE_POST',
  modalProps: {
    postId: 42
  }
})

(Strings can be constants of course; I’m using inline strings for simplicity.)

Writing a Reducer to Manage Modal State

Then make sure you have a reducer that just accepts these values:

const initialState = {
  modalType: null,
  modalProps: {}
}

function modal(state = initialState, action) {
  switch (action.type) {
    case 'SHOW_MODAL':
      return {
        modalType: action.modalType,
        modalProps: action.modalProps
      }
    case 'HIDE_MODAL':
      return initialState
    default:
      return state
  }
}

/* .... */

const rootReducer = combineReducers({
  modal,
  /* other reducers */
})

Great! Now, when you dispatch an action, state.modal will update to include the information about the currently visible modal window.

Writing the Root Modal Component

At the root of your component hierarchy, add a <ModalRoot> component that is connected to the Redux store. It will listen to state.modal and display an appropriate modal component, forwarding the props from the state.modal.modalProps.

// These are regular React components we will write soon
import DeletePostModal from './DeletePostModal'
import ConfirmLogoutModal from './ConfirmLogoutModal'

const MODAL_COMPONENTS = {
  'DELETE_POST': DeletePostModal,
  'CONFIRM_LOGOUT': ConfirmLogoutModal,
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span /> // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)

What have we done here? ModalRoot reads the current modalType and modalProps from state.modal to which it is connected, and renders a corresponding component such as DeletePostModal or ConfirmLogoutModal. Every modal is a component!

Writing Specific Modal Components

There are no general rules here. They are just React components that can dispatch actions, read something from the store state, and just happen to be modals.

For example, DeletePostModal might look like:

import { deletePost, hideModal } from '../actions'

const DeletePostModal = ({ post, dispatch }) => (
  <div>
    <p>Delete post {post.name}?</p>
    <button onClick={() => {
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    }}>
      Yes
    </button>
    <button onClick={() => dispatch(hideModal())}>
      Nope
    </button>
  </div>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

The DeletePostModal is connected to the store so it can display the post title and works like any connected component: it can dispatch actions, including hideModal when it is necessary to hide itself.

Extracting a Presentational Component

It would be awkward to copy-paste the same layout logic for every “specific” modal. But you have components, right? So you can extract a presentational <Modal> component that doesn’t know what particular modals do, but handles how they look.

Then, specific modals such as DeletePostModal can use it for rendering:

import { deletePost, hideModal } from '../actions'
import Modal from './Modal'

const DeletePostModal = ({ post, dispatch }) => (
  <Modal
    dangerText={`Delete post ${post.name}?`}
    onDangerClick={() =>
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    })
  />
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

It is up to you to come up with a set of props that <Modal> can accept in your application but I would imagine that you might have several kinds of modals (e.g. info modal, confirmation modal, etc), and several styles for them.

Accessibility and Hiding on Click Outside or Escape Key

The last important part about modals is that generally we want to hide them when the user clicks outside or presses Escape.

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.

You can even wrap react-modal in your own <Modal> that accepts props specific to your applications and generates child buttons or other content. It’s all just components!

Other Approaches

There is more than one way to do it.

Some people don’t like the verbosity of this approach and prefer to have a <Modal> component that they can render right inside their components with a technique called “portals”. Portals let you render a component inside yours while actually it will render at a predetermined place in the DOM, which is very convenient for modals.

In fact react-modal I linked to earlier already does that internally so technically you don’t even need to render it from the top. I still find it nice to decouple the modal I want to show from the component showing it, but you can also use react-modal directly from your components, and skip most of what I wrote above.

I encourage you to consider both approaches, experiment with them, and pick what you find works best for your app and for your team.