Programs & Examples On #Data driven tests

Redirect to an external URL from controller action in Spring MVC

For me works fine:

@RequestMapping (value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI uri = new URI("http://www.google.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uri);
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}

SQL QUERY replace NULL value in a row with a value from the previous known value

In a very general sense:

UPDATE MyTable
SET MyNullValue = MyDate
WHERE MyNullValue IS NULL

Angular2 disable button

I tried using disabled along with click event. Below is the snippet , the accepted answer also worked perfectly fine , I am adding this answer to give an example how it can be used with disabled and click properties.

<button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I had similar problem, but the wrong setting was in the extern .lib file from which I did not have sources. If you do not have the source files, the simplest workaround is to just change the content of the .lib file.

Open the .lib file in an editor (I used PSPad, bud Windows notepad is also possible) and replace all occurences of _ITERATOR_DEBUG_LEVEL=2 to _ITERATOR_DEBUG_LEVEL=0

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

toggle show/hide div with button?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
    $('#content').toggle('show');
  });
});
</script>

And the html

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

Limit file format when using <input type="file">?

Technically you can specify the accept attribute (alternative in html5) on the input element, but it's not properly supported.

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

Pressed <button> selector

You could use :focus which will remain the style as long as the user doesn't click elsewhere.

button:active {
    border: 2px solid green;
}

button:focus {
    border: 2px solid red;
}

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

Place cursor at the end of text in EditText

editText.setSelection is the magic here. Basically selection gives you place cursor at any position you want.

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());

This places cursor to end of EditText. Basically editText.getText().length() gives you text length. Then you use setSelection with length.

editText.setSelection(0);

It is for setting cursor at start position (0).

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Read File:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

How can I initialize a MySQL database with schema in a Docker container?

After Aug. 4, 2015, if you are using the official mysql Docker image, you can just ADD/COPY a file into the /docker-entrypoint-initdb.d/ directory and it will run with the container is initialized. See github: https://github.com/docker-library/mysql/commit/14f165596ea8808dfeb2131f092aabe61c967225 if you want to implement it on other container images

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Ahah! Cade is on the money.

An artifact in TOAD prints \r\n as two placeholder 'blob' characters, but prints a single \r also as two placeholders. The 1st step toward a solution is to use ..

REPLACE( col_name, CHR(13) || CHR(10) )

.. but I opted for the slightly more robust ..

REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )

.. which catches offending characters in any order. My many thanks to Cade.

M.

What is the difference between a "function" and a "procedure"?

Inside procedure we can use DML (Insert /Update/Delete) statements, But Inside function we can not use DML statements.

Procedure can have both input\output parameters, But Function can have only input parameter.

We can use Try-Catch Block in Stored Procedure, But In Function We can not use Try-Catch block.

We can not use Stored Procedure in Select statement, But In Function We can use in Select statement.

Stored Procedure can return 0 or n values (max 1024), But Function can return only 1 value which is mandatory.

Stored Procedure can not be call from Function, But We can call function from Stored Procedure.

We can use transaction in Stored Procedure, But In function we can not use transaction.

We can not use Stored Procedure in Sql statement anywhere in the Where/Having/select section, But In function we can use.

We can not join Stored Procedure, But we can join function.

for more.. click here...http://dotnet-developers-cafe.blogspot.in/2013/08/difference-between-stored-procedure-and.html

Find and copy files

for i in $(ls); do cp -r "$i" "$i"_dev; done;

"Fade" borders in CSS

I know this is old but this seems to work well for me in 2020...

Using the border-image CSS property I was able to quickly manipulate the borders for this fading purpose.

Note: I don't think border-image works well with border-radius... I seen someone saying that somewhere but for this purpose it works well.

1 Liner:

CSS

 .bbdr_rfade_1      { border: 4px solid; border-image: linear-gradient(90deg, rgba(60,74,83,0.90), rgba(60,74,83,.00)) 1; border-left:none; border-top:none; border-right:none;  }

HTML

<div class = 'bbdr_rfade_1'>Oh I am so going to not up-vote this guy...</div>

How do I make a redirect in PHP?

Like others here said, sending the location header with:

header( "Location: http://www.mywebsite.com/otherpage.php" );

but you need to do it before you've sent any other output to the browser.

Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.

Java variable number or arguments for a method

Yes Java allows vargs in method parameter .

public class  Varargs
{
   public int add(int... numbers)
   { 
      int result = 1; 
      for(int number: numbers)
      {
         result= result+number;  
      }  return result; 
   }
}

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Probably you missing @SpringBootApplication in your spring boot starter class.

@SpringBootApplication
public class LoginSecurityAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoginSecurityAppApplication.class, args);
    }

}

How can I make a div stick to the top of the screen once it's been scrolled to?

As Josh Lee and Colin 't Hart have said, you could optionally just use position: sticky; top: 0; applying to the div that you want the scrolling at...

Plus, the only thing you will have to do is copy this into the top of your page or format it to fit into an external CSS sheet:

<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>

Just replace #sticky_div's_name_here with the name of your div, i.e. if your div was <div id="example"> you would put #example { position: sticky; top: 0; }.

Can't connect to local MySQL server through socket homebrew

Just to add to these answers, In my case I had no local mySQL server, it was running inside a docker container. So the socket file does not exist and will not be accessible for the "mysql" client.

The sock file gets created by mysqld and mysql uses this to communicate with it. However if your mySql server is not running local, it does not require the sock file.

By specifying a host name/ip the sock file is not required e.g.

mysql --host=127.0.0.1 --port=3306 --user=xyz --password=xyz

ng-change get new value and original value

You can use a scope watch:

$scope.$watch('user', function(newValue, oldValue) {
  // access new and old value here
  console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

Java - get index of key in HashMap?

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap

How can I create a war file of my project in NetBeans?

Right click your project, hit "Clean and Build". Netbeans does the rest.

under the dist directory of your app, you should find a pretty looking .war all ready for deployment.

How to make "if not true condition"?

On Unix systems that supports it (not macOS it seems):

if getent passwd "$username" >/dev/null; then
    printf 'User %s exists\n' "$username"
else
    printf 'User %s does not exist\n' "$username"
fi 

This has the advantage that it will query any directory service that may be in use (YP/NIS or LDAP etc.) and the local password database file.


The issue with grep -q "$username" /etc/passwd is that it will give a false positive when there is no such user, but something else matches the pattern. This could happen if there is a partial or exact match somewhere else in the file.

For example, in my passwd file, there is a line saying

build:*:21:21:base and xenocara build:/var/empty:/bin/ksh

This would provoke a valid match on things like cara and enoc etc., even though there are no such users on my system.

For a grep solution to be correct, you will need to properly parse the /etc/passwd file:

if cut -d ':' -f 1 /etc/passwd | grep -qxF "$username"; then
    # found
else
    # not found
fi

... or any other similar test against the first of the :-delimited fields.

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

Shortest way to check for null and assign another value if not

Use the C# coalesce operator: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

How to remove decimal part from a number in C#

If you just need the integer part of the double then use explicit cast to int.

int number = (int) a;

You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

Automatic vertical scroll bar in WPF TextBlock?

I tried to to get these suggestions to work for a textblock, but couldn't get it to work. I even tried to get it to work from the designer. (Look in Layout and expand the list by clicking the down-arrow "V" at the bottom) I tried setting the scrollviewer to Visible and then Auto, but it still wouldn't work.

I eventually gave up and changed the TextBlock to a TextBox with the Readonly attribute set, and it worked like a charm.

How to position the div popup dialog to the center of browser screen?

Here, this ones working. :)

http://jsfiddle.net/nDNXc/1/

upd: Just in case jsfiddle is not responding here is the code...
CSS:

.holder{        
    width:100%;
    display:block;
}
.content{
    background:#fff;
    padding: 28px 26px 33px 25px;
}
.popup{
    border-radius: 7px;
    background:#6b6a63;
    margin:30px auto 0;
    padding:6px;  
    // here it comes
    position:absolute;
    width:800px;
    top: 50%;
    left: 50%;
    margin-left: -400px; // 1/2 width
    margin-top: -40px; // 1/2 height
}

HTML:

<div class="holder">     
    <div id="popup" class="popup">            
        <div class="content">some lengthy text</div>
    </div>
</div>

What's with the dollar sign ($"string")

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Why do some functions have underscores "__" before and after the function name?

Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".

jQuery call function after load

$(document).ready(my_function);

Or

$(document).ready(function () {
  // Function code here.
});

Or the shorter but less readable variant:

$(my_function);

All of these will cause my_function to be called after the DOM loads.

See the ready event documentation for more details.

Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.

Edit:

To simulate a click, use the click() method without arguments:

$('#button').click();

From the docs:

Triggers the click event of each matched element. Causes all of the functions that have been bound to that click event to be executed.

To put it all together, the following code simulates a click when the document finishes loading:

$(function () {
  $('#button').click();
});

Async/Await Class Constructor

You can definitely do this. Basically:

class AsyncConstructor {
    constructor() {
        return (async () => {

            // All async code here
            this.value = await asyncFunction();

            return this; // when done
        })();
    }
}

to create the class use:

let instance = await new AsyncConstructor();

This solution has a few short falls though:

super note: If you need to use super, you cannot call it within the async callback.

TypeScript note: this causes issues with TypeScript because the constructor returns type Promise<MyClass> instead of MyClass. There is no definitive way to resolve this that I know of. One potential way suggested by @blitter is to put /** @type {any} */ at the beginning of the constructor body— I do not know if this works in all situations however.

How to check if a Constraint exists in Sql server?

If you are looking for other type of constraint, e.g. defaults, you should use different query (From How do I find a default constraint using INFORMATION_SCHEMA? answered by devio). Use:

SELECT * FROM sys.objects WHERE type = 'D' AND name = @name

to find a default constraint by name.

I've put together different 'IF not Exists" checks in my post "DDL 'IF not Exists" conditions to make SQL scripts re-runnable"

How do I update the GUI from another thread?

Threading code is often buggy and always hard to test. You don't need to write threading code to update the user interface from a background task. Just use the BackgroundWorker class to run the task and its ReportProgress method to update the user interface. Usually, you just report a percentage complete, but there's another overload that includes a state object. Here's an example that just reports a string object:

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(5000);
        backgroundWorker1.ReportProgress(0, "A");
        Thread.Sleep(5000);
        backgroundWorker1.ReportProgress(0, "B");
        Thread.Sleep(5000);
        backgroundWorker1.ReportProgress(0, "C");
    }

    private void backgroundWorker1_ProgressChanged(
        object sender, 
        ProgressChangedEventArgs e)
    {
        label1.Text = e.UserState.ToString();
    }

That's fine if you always want to update the same field. If you've got more complicated updates to make, you could define a class to represent the UI state and pass it to the ReportProgress method.

One final thing, be sure to set the WorkerReportsProgress flag, or the ReportProgress method will be completely ignored.

Hide div if screen is smaller than a certain width

Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none in to a block and vice versa.

Row count on the Filtered data

I would think that now you have the range for each of the row, you can easily manipulate that range with the offset(row, column) action? What is the point of counting the records filtered (unless you need that count in a variable)? So instead of (or as well as in the same block) write your code action to move each row to an empty hidden sheet and once all done, you can do any work you like from the transferred range data?

Call multiple functions onClick ReactJS

this onclick={()=>{ f1(); f2() }} helped me a lot if i want two different functions at the same time. But now i want to create an audiorecorder with only one button. So if i click first i want to run the StartFunction f1() and if i click again then i want to run StopFunction f2().

How do you guys realize this?

How to get only the date value from a Windows Forms DateTimePicker control?

You mean how to get date without the time component? Use DateTimePicker.Value.Date But you need to format the output to your needs.

Datatable to html Table

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

The controller might look something like this.

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

Hope this helps :)

List<T> OrderBy Alphabetical Order

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Matplotlib discrete colorbar

The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:

import matplotlib.pyplot as plt
import numpy as np

def discrete_matshow(data):
    #get discrete colormap
    cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
    # set limits .5 outside true range
    mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))

#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)

example of discrete colorbar

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

Jersey Exception : SEVERE: A message body reader for Java class

To make it work you only need two things. Check if you are missing:

  1. First of all, you need @XmlRootElement annotation for your object class/entity.
  2. You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.17.1</version>
    </dependency>
    

You don't have permission to access / on this server

Set SELinux in Permissive Mode using the command below:

setenforce 0;

nodejs npm global config missing on windows

Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.

  1. Global NPM config => C:\Users\%username%\AppData\Roaming\npm\etc\npmrc
  2. Per-user NPM config => C:\Users\%username%.npmrc
  3. Built-in NPM config => C:\Program Files\nodejs\node_modules\npm\npmrc

To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050

After that open the .npmrc files to see which file get updated.

jquery data selector

$('a[data-category="music"]')

It works. See Attribute Equals Selector [name=”value”].

Python timedelta in years

Here's a updated DOB function, which calculates birthdays the same way humans do:

import datetime
import locale


# Source: https://en.wikipedia.org/wiki/February_29
PRE = [
    'US',
    'TW',
]
POST = [
    'GB',
    'HK',
]


def get_country():
    code, _ = locale.getlocale()
    try:
        return code.split('_')[1]
    except IndexError:
        raise Exception('Country cannot be ascertained from locale.')


def get_leap_birthday(year):
    country = get_country()
    if country in PRE:
        return datetime.date(year, 2, 28)
    elif country in POST:
        return datetime.date(year, 3, 1)
    else:
        raise Exception('It is unknown whether your country treats leap year '
                      + 'birthdays as being on the 28th of February or '
                      + 'the 1st of March. Please consult your country\'s '
                      + 'legal code for in order to ascertain an answer.')
def age(dob):
    today = datetime.date.today()
    years = today.year - dob.year

    try:
        birthday = datetime.date(today.year, dob.month, dob.day)
    except ValueError as e:
        if dob.month == 2 and dob.day == 29:
            birthday = get_leap_birthday(today.year)
        else:
            raise e

    if today < birthday:
        years -= 1
    return years

print(age(datetime.date(1988, 2, 29)))

How can I delete a service in Windows?

Click Start | Run and type regedit in the Open: line. Click OK.

Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Scroll down the left pane, locate the service name, right click it and select Delete.

Reboot the system.

how to read xml file from url using php

It is working for me. I think you probably need to use urlencode() on each of the components of $map_url.

Meaning of delta or epsilon argument of assertEquals for double values

Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as Math.abs(expected - actual) < epsilon

How to Convert double to int in C?

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0

// Now cast
int b = (int) a;
// Now a is 3668

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

Calling virtual functions inside constructors

One solution to your problem is using factory methods to create your object.

  • Define a common base class for your class hierarchy containing a virtual method afterConstruction():
class Object
{
public:
  virtual void afterConstruction() {}
  // ...
};
  • Define a factory method:
template< class C >
C* factoryNew()
{
  C* pObject = new C();
  pObject->afterConstruction();

  return pObject;
}
  • Use it like this:
class MyClass : public Object 
{
public:
  virtual void afterConstruction()
  {
    // do something.
  }
  // ...
};

MyClass* pMyObject = factoryNew();

jQuery UI 1.10: dialog and zIndex option

You may want to try jQuery dialog method:

$( ".selector" ).dialog( "moveToTop" );

reference: http://api.jqueryui.com/dialog/#method-moveToTop

AngularJS : Difference between the $observe and $watch methods

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").


Inside directive you can use both of them on very similar way:

    attrs.$observe('attrYouWatch', function() {
         // body
    });

or

    scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

Transparent CSS background color

In this case background-color:rgba(0,0,0,0.5); is the best way. For example: background-color:rgba(0,0,0,opacity option);

could not access the package manager. is the system running while installing android application

Check your project build is in Debug mode not Release, I had some problem for debugging always I forget to change Release mode to Debug (Xamarin Users)

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Shortcut to comment out a block of code with sublime text

With a non-US keyboard layout the default shortcut Ctrl+/ (Win/Linux) does not work.

I managed to change it into Ctrl+1 as per Robert's comment by writing

[
{
    "keys": ["ctrl+1"],
    "command": "toggle_comment",
    "args": { "block": false } 
}
,
{   "keys": ["ctrl+shift+1"],
    "command": "toggle_comment",
    "args": { "block": true }
}
]

to Preferences -> Key Bindings (on the right half, the user keymap).

Note that there should be only one set of brackets ('[]') at the right side; if you had there something already, copy paste this between the brackets and keep only the outermost brackets.

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

Convert AM/PM time to 24 hours format?

int hour = your hour value;
int min = your minute value;
String ampm = your am/pm value;

hour = ampm == "AM" ? hour : (hour % 12) + 12; //convert 12-hour time to 24-hour

var dateTime = new DateTime(0,0,0, hour, min, 0);
var timeString = dateTime.ToString("HH:mm");

Given URL is not permitted by the application configuration

Settings -> Advanced, add url to "Valid OAuth redirect URIs". This works for me.

Trigger event on body load complete js/jquery

jQuery:

$(function(){
  // your code...this will run when DOM is ready
});

If you want to run your code after all page resources including images/frames/DOM have loaded, you need to use load event:

$(window).load(function(){
  // your code...
});

JavaScript:

window.onload = function(){
  // your code...
};

The program can't start because libgcc_s_dw2-1.dll is missing

In Eclipse, you will find it under the project properties > C/C++ Build > Settings > MinGW C++ Linker > Misc

You must add it to the "linker flags" at the top; nowhere else. Then just rebuild.

Eclipse properties screenshot

I have found that linking those statically explodes the size up to 1,400kb even with optimizations. It's 277kb larger compared to just copying over the shared DLLs. It's 388kb larger as well after UPXing everything. Very lose/lose here. Just include the DLLs as the end-user can decide to delete them or not if they have them installed elsewhere.

Where is localhost folder located in Mac or Mac OS X?

There's no such thing as a "localhost" folder; the word "localhost" is an alias for your local computer. The document root for your apache server, by default, is "Sites" in your home directory.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

If you are using Ajax update panel. Add <Triggers> tag and inside it trigger the Button or control causing the postBack using <asp:PostBackTrigger .../>

Provide schema while reading csv file as a dataframe

In pyspark 2.4 onwards, you can simply use header parameter to set the correct header:

data = spark.read.csv('data.csv', header=True)

Similarly, if using scala you can use header parameter as well.

How to use 'cp' command to exclude a specific directory?

Another simpler option is to install and use rsync which has an --exclude-dir option, and can be used for both local and remote files.

Pentaho Data Integration SQL connection

I just came across the same issue while trying to query a MySQL Database from Pentaho.

Error connecting to database [Local MySQL DB] : org.pentaho.di.core.exception.KettleDatabaseException: Error occured while trying to connect to the database

Exception while loading class org.gjt.mm.mysql.Driver

Expanding post by @user979331 the solution is:

  1. Download the MySQL Java Connector / Driver that is compatible with your kettle version
  2. Unzip the zip file (in my case it was mysql-connector-java-5.1.31.zip)
  3. copy the .jar file (mysql-connector-java-5.1.31-bin.jar) and paste it in your Lib folder:

    PC: C:\Program Files\pentaho\design-tools\data-integration\lib

    Mac: /Applications/data-integration/lib

Restart Pentaho (Data Integration) and re-test the MySQL Connection.

Additional interesting replies from others that could also help:

Can You Get A Users Local LAN IP Address Via JavaScript?

_x000D_
_x000D_
function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs_x000D_
  //compatibility for firefox and chrome_x000D_
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;_x000D_
  var pc = new myPeerConnection({_x000D_
      iceServers: []_x000D_
    }),_x000D_
    noop = function() {},_x000D_
    localIPs = {},_x000D_
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
    key;_x000D_
_x000D_
  function iterateIP(ip) {_x000D_
    if (!localIPs[ip]) onNewIP(ip);_x000D_
    localIPs[ip] = true;_x000D_
  }_x000D_
  onNewIP_x000D_
  //create a bogus data channel_x000D_
  pc.createDataChannel("");_x000D_
_x000D_
  // create offer and set local description_x000D_
  pc.createOffer().then(function(sdp) {_x000D_
    sdp.sdp.split('\n').forEach(function(line) {_x000D_
      if (line.indexOf('candidate') < 0) return;_x000D_
      line.match(ipRegex).forEach(iterateIP);_x000D_
    });_x000D_
_x000D_
    pc.setLocalDescription(sdp, noop, noop);_x000D_
  }).catch(function(reason) {_x000D_
    // An error occurred, so handle the failure to connect_x000D_
  });_x000D_
_x000D_
  //listen for candidate events_x000D_
  pc.onicecandidate = function(ice) {_x000D_
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;_x000D_
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);_x000D_
  };_x000D_
}_x000D_
getUserIP(console.log)
_x000D_
_x000D_
_x000D_

How the int.TryParse actually works

If you only need the bool result, just use the return value and ignore the out parameter.

bool successfullyParsed = int.TryParse(str, out ignoreMe);
if (successfullyParsed){
    // ...
}

Edit: Meanwhile you can also have a look at the original source code:

System.Int32.TryParse


If i want to know how something is actually implemented, i'm using ILSpy to decompile the .NET-code.

This is the result:

// int
/// <summary>Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.</summary>
/// <returns>true if s was converted successfully; otherwise, false.</returns>
/// <param name="s">A string containing a number to convert. </param>
/// <param name="result">When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null, is not of the correct format, or represents a number less than <see cref="F:System.Int32.MinValue"></see> or greater than <see cref="F:System.Int32.MaxValue"></see>. This parameter is passed uninitialized. </param>
/// <filterpriority>1</filterpriority>
public static bool TryParse(string s, out int result)
{
    return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}


// System.Number
internal unsafe static bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
    byte* stackBuffer = stackalloc byte[1 * 114 / 1];
    Number.NumberBuffer numberBuffer = new Number.NumberBuffer(stackBuffer);
    result = 0;
    if (!Number.TryStringToNumber(s, style, ref numberBuffer, info, false))
    {
        return false;
    }
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!Number.HexNumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    else
    {
        if (!Number.NumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    return true;
}

And no, i cannot see any Try-Catchs on the road:

// System.Number
private unsafe static bool TryStringToNumber(string str, NumberStyles options, ref Number.NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal)
{
    if (str == null)
    {
        return false;
    }
    fixed (char* ptr = str)
    {
        char* ptr2 = ptr;
        if (!Number.ParseNumber(ref ptr2, options, ref number, numfmt, parseDecimal) || ((ptr2 - ptr / 2) / 2 < str.Length && !Number.TrailingZeros(str, (ptr2 - ptr / 2) / 2)))
        {
            return false;
        }
    }
    return true;
}

// System.Number
private unsafe static bool ParseNumber(ref char* str, NumberStyles options, ref Number.NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal)
{
    number.scale = 0;
    number.sign = false;
    string text = null;
    string text2 = null;
    string str2 = null;
    string str3 = null;
    bool flag = false;
    string str4;
    string str5;
    if ((options & NumberStyles.AllowCurrencySymbol) != NumberStyles.None)
    {
        text = numfmt.CurrencySymbol;
        if (numfmt.ansiCurrencySymbol != null)
        {
            text2 = numfmt.ansiCurrencySymbol;
        }
        str2 = numfmt.NumberDecimalSeparator;
        str3 = numfmt.NumberGroupSeparator;
        str4 = numfmt.CurrencyDecimalSeparator;
        str5 = numfmt.CurrencyGroupSeparator;
        flag = true;
    }
    else
    {
        str4 = numfmt.NumberDecimalSeparator;
        str5 = numfmt.NumberGroupSeparator;
    }
    int num = 0;
    char* ptr = str;
    char c = *ptr;
    while (true)
    {
        if (!Number.IsWhite(c) || (options & NumberStyles.AllowLeadingWhite) == NumberStyles.None || ((num & 1) != 0 && ((num & 1) == 0 || ((num & 32) == 0 && numfmt.numberNegativePattern != 2))))
        {
            bool flag2;
            char* ptr2;
            if ((flag2 = ((options & NumberStyles.AllowLeadingSign) != NumberStyles.None && (num & 1) == 0)) && (ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
            {
                num |= 1;
                ptr = ptr2 - (IntPtr)2 / 2;
            }
            else
            {
                if (flag2 && (ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
                {
                    num |= 1;
                    number.sign = true;
                    ptr = ptr2 - (IntPtr)2 / 2;
                }
                else
                {
                    if (c == '(' && (options & NumberStyles.AllowParentheses) != NumberStyles.None && (num & 1) == 0)
                    {
                        num |= 3;
                        number.sign = true;
                    }
                    else
                    {
                        if ((text == null || (ptr2 = Number.MatchChars(ptr, text)) == null) && (text2 == null || (ptr2 = Number.MatchChars(ptr, text2)) == null))
                        {
                            break;
                        }
                        num |= 32;
                        text = null;
                        text2 = null;
                        ptr = ptr2 - (IntPtr)2 / 2;
                    }
                }
            }
        }
        c = *(ptr += (IntPtr)2 / 2);
    }
    int num2 = 0;
    int num3 = 0;
    while (true)
    {
        if ((c >= '0' && c <= '9') || ((options & NumberStyles.AllowHexSpecifier) != NumberStyles.None && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))))
        {
            num |= 4;
            if (c != '0' || (num & 8) != 0)
            {
                if (num2 < 50)
                {
                    number.digits[(IntPtr)(num2++)] = c;
                    if (c != '0' || parseDecimal)
                    {
                        num3 = num2;
                    }
                }
                if ((num & 16) == 0)
                {
                    number.scale++;
                }
                num |= 8;
            }
            else
            {
                if ((num & 16) != 0)
                {
                    number.scale--;
                }
            }
        }
        else
        {
            char* ptr2;
            if ((options & NumberStyles.AllowDecimalPoint) != NumberStyles.None && (num & 16) == 0 && ((ptr2 = Number.MatchChars(ptr, str4)) != null || (flag && (num & 32) == 0 && (ptr2 = Number.MatchChars(ptr, str2)) != null)))
            {
                num |= 16;
                ptr = ptr2 - (IntPtr)2 / 2;
            }
            else
            {
                if ((options & NumberStyles.AllowThousands) == NumberStyles.None || (num & 4) == 0 || (num & 16) != 0 || ((ptr2 = Number.MatchChars(ptr, str5)) == null && (!flag || (num & 32) != 0 || (ptr2 = Number.MatchChars(ptr, str3)) == null)))
                {
                    break;
                }
                ptr = ptr2 - (IntPtr)2 / 2;
            }
        }
        c = *(ptr += (IntPtr)2 / 2);
    }
    bool flag3 = false;
    number.precision = num3;
    number.digits[(IntPtr)num3] = '\0';
    if ((num & 4) != 0)
    {
        if ((c == 'E' || c == 'e') && (options & NumberStyles.AllowExponent) != NumberStyles.None)
        {
            char* ptr3 = ptr;
            c = *(ptr += (IntPtr)2 / 2);
            char* ptr2;
            if ((ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
            {
                c = *(ptr = ptr2);
            }
            else
            {
                if ((ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
                {
                    c = *(ptr = ptr2);
                    flag3 = true;
                }
            }
            if (c >= '0' && c <= '9')
            {
                int num4 = 0;
                do
                {
                    num4 = num4 * 10 + (int)(c - '0');
                    c = *(ptr += (IntPtr)2 / 2);
                    if (num4 > 1000)
                    {
                        num4 = 9999;
                        while (c >= '0' && c <= '9')
                        {
                            c = *(ptr += (IntPtr)2 / 2);
                        }
                    }
                }
                while (c >= '0' && c <= '9');
                if (flag3)
                {
                    num4 = -num4;
                }
                number.scale += num4;
            }
            else
            {
                ptr = ptr3;
                c = *ptr;
            }
        }
        while (true)
        {
            if (!Number.IsWhite(c) || (options & NumberStyles.AllowTrailingWhite) == NumberStyles.None)
            {
                bool flag2;
                char* ptr2;
                if ((flag2 = ((options & NumberStyles.AllowTrailingSign) != NumberStyles.None && (num & 1) == 0)) && (ptr2 = Number.MatchChars(ptr, numfmt.positiveSign)) != null)
                {
                    num |= 1;
                    ptr = ptr2 - (IntPtr)2 / 2;
                }
                else
                {
                    if (flag2 && (ptr2 = Number.MatchChars(ptr, numfmt.negativeSign)) != null)
                    {
                        num |= 1;
                        number.sign = true;
                        ptr = ptr2 - (IntPtr)2 / 2;
                    }
                    else
                    {
                        if (c == ')' && (num & 2) != 0)
                        {
                            num &= -3;
                        }
                        else
                        {
                            if ((text == null || (ptr2 = Number.MatchChars(ptr, text)) == null) && (text2 == null || (ptr2 = Number.MatchChars(ptr, text2)) == null))
                            {
                                break;
                            }
                            text = null;
                            text2 = null;
                            ptr = ptr2 - (IntPtr)2 / 2;
                        }
                    }
                }
            }
            c = *(ptr += (IntPtr)2 / 2);
        }
        if ((num & 2) == 0)
        {
            if ((num & 8) == 0)
            {
                if (!parseDecimal)
                {
                    number.scale = 0;
                }
                if ((num & 16) == 0)
                {
                    number.sign = false;
                }
            }
            str = ptr;
            return true;
        }
    }
    str = ptr;
    return false;
}

Cannot implicitly convert type 'int?' to 'int'.

The first problem encountered with your code is the message

Local variable OrdersPerHour might not be initialized before accessing.

It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).

To fix this, set the value to what you'd want to have if the query fails, which is probably 0 :

int? OrdersPerHour = 0;

Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int, but you are in fact returning a nullable int, int?, variable.

So to get the int part of your int?, you can use the .Value property:

return OrdersPerHour.Value;

However, if you declared your OrdersPerHour to be null at start instead of 0, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).

To do so, you can use the HasValue property to be sure you're having a value before returning it:

if (OrdersPerHour.HasValue){
    return OrdersPerHour.Value;
}
else{
    // Handle the case here
}

As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User and OrdersPerHour would be user and ordersPerHour.

How to ensure that there is a delay before a service is started in systemd?

Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.

For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):

[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'

Simply replace nc -z -v -w1 localhost 443 with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.

For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.

Android Studio - How to increase Allocated Heap Size

If you are using MAC BOOK, this option is available inside Applications -> Right click Android Studio then choose Show Package contents -> bin.

enter image description here

or

open -e /Applications/Android\ Studio.app/Contents/bin/studio.vmoptions

Then increase Xmx value

-Xms128m
-Xmx2048m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Now your Android Studio will be super-fast.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

How to Check whether Session is Expired or not in asp.net

Check if it is null or not e.g

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}

How to set up java logging using a properties file? (java.util.logging)

Are you searching for the log file in the right path: %h/one%u.log

Here %h resolves to your home : In windows this defaults to : C:\Documents and Settings(user_name).

I have tried the sample code you have posted and it works fine after you specify the configuration file path (logging.properties either through code or java args) .

How to fully clean bin and obj folders within Visual Studio?

Based on Joe answer, I've converted the VB code into C# :

/// <summary>
/// Based on code of VSProjCleaner tool (C) 2005 Francesco Balena, Code Archirects
/// </summary>
static class VisualStudioCleaner
{
    public static void Process(string rootDir)
    {
        // Read all the folder names in the specified directory tree
        string[] dirNames = Directory.GetDirectories(rootDir, "*.*", SearchOption.AllDirectories);
        List<string> errorsList = new List<string>();

        // delete any .suo and csproj.user file
        foreach (string dir in dirNames) {
            var files = new List<string>();
            files.AddRange(Directory.GetFiles(dir, "*.suo"));
            files.AddRange(Directory.GetFiles(dir, "*.user"));
            foreach (string fileName in files) {
                try {
                    Console.Write("Deleting {0} ...", fileName);
                    File.Delete(fileName);
                    Console.WriteLine("DONE");
                } catch (Exception ex) {
                    Console.WriteLine();
                    Console.WriteLine(" ERROR: {0}", ex.Message);
                    errorsList.Add(fileName + ": " + ex.Message);
                }
            }
        }

        // Delete all the BIN and OBJ subdirectories
        foreach (string dir in dirNames) {
            string dirName = Path.GetFileName(dir).ToLower();
            if (dirName == "bin" || dirName == "obj") {
                try {
                    Console.Write("Deleting {0} ...", dir);
                    Directory.Delete(dir, true);
                    Console.WriteLine("DONE");
                } catch (Exception ex) {
                    Console.WriteLine();
                    Console.WriteLine(" ERROR: {0}", ex.Message);
                    errorsList.Add(dir + ": " + ex.Message);
                }
            }
        }
        Console.WriteLine(new string('-', 60));
        if (errorsList.Count == 0) {
            Console.WriteLine("All directories and files were removed successfully");
        } else {
            Console.WriteLine("{0} directories or directories couldn't be removed", errorsList.Count);
            Console.WriteLine(new string('-', 60));
            foreach (string msg in errorsList) {
                Console.WriteLine(msg);
            }
        }
    }
}

HTML5 Email input pattern attribute

I used following Regex to satisfy for following emails.

[email protected] # Minimum three characters
[email protected] # Accepts Caps as well.
[email protected] # Accepts . before @

Code

<input type="email" pattern="[A-Za-z0-9._%+-]{3,}@[a-zA-Z]{3,}([.]{1}[a-zA-Z]{2,}|[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,})" />

Adding items to end of linked list

The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().

Node.java

package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}

LinkedList.java

package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }


    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }


    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}

pip installs packages successfully, but executables not found from command line

In addition to adding python's bin directory to $PATH variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.

chown -R ~/Library/Python/

Write objects into file with Node.js

Just incase anyone else stumbles across this, I use the fs-extra library in node and write javascript objects to a file like this:

const fse = require('fs-extra');
fse.outputJsonSync('path/to/output/file.json', objectToWriteToFile); 

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

Difference between F5, Ctrl + F5 and click on refresh button?

F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.

So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.

Vector of Vectors to create matrix

As it is, both dimensions of your vector are 0.

Instead, initialize the vector as this:

vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
   matrix[i].resize(CC);

This will give you a matrix of dimensions RR * CC with all elements set to 0.

How to Create simple drag and Drop in angularjs

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

Code is here: http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

What are the differences between Pandas and NumPy+SciPy in Python?

Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

CSS div element - how to show horizontal scroll bars only?

You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.

However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.

IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:

overflow: auto;
overflow-y: hidden;

You may also need to add for IE8:

-ms-overflow-y: hidden;

as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)

On the other hand it's entirely possible IE8 will have fixed the bug anyway.

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

Works fine for me in 5.0.27

I just get a warning (not an error) that the table exists;

How to make a flat list out of list of lists?

from nltk import flatten

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
flatten(l)

The advantage of this solution over most others here is that if you have a list like:

l = [1, [2, 3], [4, 5, 6], [7], [8, 9]]

while most other solutions throw an error this solution handles them.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

CSS Transition doesn't work with top, bottom, left, right

In my case div position was fixed , adding left position was not enough it started working only after adding display block

left:0; display:block;

Regex pattern to match at least 1 number and 1 character in a string

The accepted answers is not worked as it is not allow to enter special characters.

Its worked perfect for me.

^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$

  • one digit must
  • one character must (lower or upper)
  • every other things optional

Thank you.

What is the JUnit XML format specification that Hudson supports?

I couldn't find any good information on this, so I did some trial and error. The following attributes and fields (and only these) are recognized by Jenkins (v1.585).

<?xml version="1.0" encoding="UTF-8"?>
<testsuite>

  <!-- if your classname does not include a dot, the package defaults to "(root)" -->
  <testcase name="my testcase" classname="my package.my classname" time="29">

    <!-- If the test didn't pass, specify ONE of the following 3 cases -->

    <!-- option 1 --> <skipped />
    <!-- option 2 --> <failure message="my failure message">my stack trace</failure>
    <!-- option 3 --> <error message="my error message">my crash report</error>

    <system-out>my STDOUT dump</system-out>

    <system-err>my STDERR dump</system-err>

  </testcase>

</testsuite>

(I started with this sample XML document and worked backwards from there.)

In C++, what is a virtual base class?

Explaining multiple-inheritance with virtual bases requires a knowledge of the C++ object model. And explaining the topic clearly is best done in an article and not in a comment box.

The best, readable explanation I found that solved all my doubts on this subject was this article: http://www.phpcompiler.org/articles/virtualinheritance.html

You really won't need to read anything else on the topic (unless you are a compiler writer) after reading that...

How to bind bootstrap popover on dynamic elements

I did this and it works for me. "content" is placesContent object. not the html content!

var placesContent = $('#placescontent');
$('#places').popover({
        trigger: "click",
        placement: "bottom",
        container: 'body',
        html : true,
        content : placesContent,
    });

$('#places').on('shown.bs.popover', function(){
  $('#addPlaceBtn').on('click', addPlace);
}

<div id="placescontent"><div id="addPlaceBtn">Add</div></div>

regular expression for finding 'href' value of a <a> link

Using regex to parse html is not recommended

regex is used for regularly occurring patterns.html is not regular with it's format(except xhtml).For example html files are valid even if you don't have a closing tag!This could break your code.

Use an html parser like htmlagilitypack

You can use this code to retrieve all href's in anchor tag using HtmlAgilityPack

HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);

var hrefList = doc.DocumentNode.SelectNodes("//a")
                  .Select(p => p.GetAttributeValue("href", "not found"))
                  .ToList();

hrefList contains all href`s

Zooming MKMapView to fit annotation pins?

You've got it right.

Find your maximum and minimum latitudes and longitudes, apply some simple arithmetic, and use MKCoordinateRegionMake.

For iOS 7 and above, use showAnnotations:animated:, from MKMapView.h:

// Position the map such that the provided array of annotations are all visible to the fullest extent possible. 
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

How do I truly reset every setting in Visual Studio 2012?

Executing the command: Devenv.exe /ResetSettings like :

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv.exe /ResetSettings , resolved my issue :D

For more: https://msdn.microsoft.com/en-us/library/ms241273.aspx

How can I select all children of an element except the last child?

Make it simple:

You can apply your style to all the div and re-initialize the last one with :last-child:

for example in CSS:

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

or in SCSS:

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}
  • easy to read/remember
  • fast to execute
  • browser compatible (IE9+ since it's still CSS3)

How to dynamically remove items from ListView on a button click?

 List<String> entries;
 private ArrayAdapter<String> categoryAdapter;
 //Your list of entries {Example: <"category1","category2","category3">}
 entries =  new ArrayList<String>();
 categoryAdapter = new ArrayAdapter<String>(ViewBeaconsActivity.this,
                                   android.R.layout.simple_list_item_1, entries);
 //Remove that specific category from the list
 entries.remove(categoryName);
 //Notify the adapter that your dataset has changed.
 categoryAdapter.notifyDataSetChanged();

how to add new <li> to <ul> onclick with javascript

First you have to create a li(with id and value as you required) then add it to your ul.

Javascript ::

addAnother = function() {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var children = ul.children.length + 1
    li.setAttribute("id", "element"+children)
    li.appendChild(document.createTextNode("Element "+children));
    ul.appendChild(li)
}

Check this example that add li element to ul.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Actually, everything is typically stored as Unicode of some kind internally, but lets not go into that. I'm assuming you're getting the iconic "åäö" type strings because you're using an ISO-8859 as your character encoding. There's a trick you can do to convert those characters. The escape and unescape functions used for encoding and decoding query strings are defined for ISO characters, whereas the newer encodeURIComponent and decodeURIComponent which do the same thing, are defined for UTF8 characters.

escape encodes extended ISO-8859-1 characters (UTF code points U+0080-U+00ff) as %xx (two-digit hex) whereas it encodes UTF codepoints U+0100 and above as %uxxxx (%u followed by four-digit hex.) For example, escape("å") == "%E5" and escape("?") == "%u3042".

encodeURIComponent percent-encodes extended characters as a UTF8 byte sequence. For example, encodeURIComponent("å") == "%C3%A5" and encodeURIComponent("?") == "%E3%81%82".

So you can do:

fixedstring = decodeURIComponent(escape(utfstring));

For example, an incorrectly encoded character "å" becomes "Ã¥". The command does escape("Ã¥") == "%C3%A5" which is the two incorrect ISO characters encoded as single bytes. Then decodeURIComponent("%C3%A5") == "å", where the two percent-encoded bytes are being interpreted as a UTF8 sequence.

If you'd need to do the reverse for some reason, that works too:

utfstring = unescape(encodeURIComponent(originalstring));

Is there a way to differentiate between bad UTF8 strings and ISO strings? Turns out there is. The decodeURIComponent function used above will throw an error if given a malformed encoded sequence. We can use this to detect with a great probability whether our string is UTF8 or ISO.

var fixedstring;

try{
    // If the string is UTF-8, this will work and not throw an error.
    fixedstring=decodeURIComponent(escape(badstring));
}catch(e){
    // If it isn't, an error will be thrown, and we can assume that we have an ISO string.
    fixedstring=badstring;
}

Get size of a View in React Native

Here is the code to get the Dimensions of the complete view of the device.

var windowSize = Dimensions.get("window");

Use it like this:

width=windowSize.width,heigth=windowSize.width/0.565

Matrix Multiplication in pure Python?

The fault occurs here:

C[i][j]+=A[i][k]*B[k][j]

It crashes when k=2. This is because the tuple A[i] has only 2 values, and therefore you can only call it up to A[i][1] before it errors.

EDIT: Listen to Gerard's answer too, your C is wrong. It should be C=[[0 for row in range(len(A))] for col in range(len(A[0]))].

Just a tip: you could replace the first loop with a multiplication, so it would be C=[[0]*len(A) for col in range(len(A[0]))]

How does the "view" method work in PyTorch?

Let's try to understand view by the following examples:

    a=torch.range(1,16)

print(a)

    tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14.,
            15., 16.])

print(a.view(-1,2))

    tensor([[ 1.,  2.],
            [ 3.,  4.],
            [ 5.,  6.],
            [ 7.,  8.],
            [ 9., 10.],
            [11., 12.],
            [13., 14.],
            [15., 16.]])

print(a.view(2,-1,4))   #3d tensor

    tensor([[[ 1.,  2.,  3.,  4.],
             [ 5.,  6.,  7.,  8.]],

            [[ 9., 10., 11., 12.],
             [13., 14., 15., 16.]]])
print(a.view(2,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.],
             [ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.],
             [13., 14.],
             [15., 16.]]])

print(a.view(4,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.]],

            [[ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.]],

            [[13., 14.],
             [15., 16.]]])

-1 as an argument value is an easy way to compute the value of say x provided we know values of y, z or the other way round in case of 3d and for 2d again an easy way to compute the value of say x provided we know values of y or vice versa..

How do I lock the orientation to portrait mode in a iPhone Web Application?

I came up with this CSS only method of rotating the screen using media queries. The queries are based on screen sizes that I found here. 480px seemed to be a good as no/few devices had more than 480px width or less than 480px height.

@media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { 
    html{
        -webkit-transform: rotate(-90deg);
           -moz-transform: rotate(-90deg);
            -ms-transform: rotate(-90deg);
             -o-transform: rotate(-90deg);
                transform: rotate(-90deg);
        -webkit-transform-origin: left top;
           -moz-transform-origin: left top;
            -ms-transform-origin: left top;
             -o-transform-origin: left top;
                transform-origin: left top;
        width: 320px; /*this is the iPhone screen width.*/
        position: absolute;
        top: 100%;
            left: 0
    }
}

Set IDENTITY_INSERT ON is not working

In VB code, when trying to submit an INSERT query, you must submit a double query in the same 'executenonquery' like this:

sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"

I used a ; separator instead of a GO.

Works for me. Late but efficient!

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

IE6/IE7 css border on select element

It solves to me, for my purposes:

.select-container {
  position:relative;
  width:200px;
  height:18px;
  overflow:hidden;
  border:1px solid white !important
}
.select-container select {
  position:relative;
  left:-2px;
  top:-2px
}

To put more style will be necessary to use nested divs .

Determine if running on a rooted device

if you don't want to use any 3rd party library or any random solution then just use google lib for detecting it.

Android Device Verification

response :

{
  "timestampMs": 9860437986543,
  "nonce": "R2Rra24fVm5xa2Mg",
  "apkPackageName": "com.package.name.of.requesting.app",
  "apkCertificateDigestSha256": ["base64 encoded, SHA-256 hash of the
                                  certificate used to sign requesting app"],
  "ctsProfileMatch": true,
  "basicIntegrity": true,
}

ctsProfileMatch it gives false if the device is rooted.

ref link: [1]: https://developer.android.com/training/safetynet/attestation

Why do we need virtual functions in C++?

You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:

class Animal
{        
    public: 
      // turn the following virtual modifier on/off to see what happens
      //virtual   
      std::string Says() { return "?"; }  
};

class Dog: public Animal
{
    public: std::string Says() { return "Woof"; }
};

void test()
{
    Dog* d = new Dog();
    Animal* a = d;       // refer to Dog instance with Animal pointer

    std::cout << d->Says();   // always Woof
    std::cout << a->Says();   // Woof or ?, depends on virtual
}

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

One can simply use java.bean.ConstructorProperties annotation - it's much less verbose and Jackson also accepts it. For example :

  import java.beans.ConstructorProperties;

  @ConstructorProperties({"answer","closed","language","interface","operation"})
  public DialogueOutput(String answer, boolean closed, String language, String anInterface, String operation) {
    this.answer = answer;
    this.closed = closed;
    this.language = language;
    this.anInterface = anInterface;
    this.operation = operation;
  }

Proper way to handle multiple forms on one page in Django

If you are using approach with class-based views and different 'action' attrs i mean

Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

You can easily handle errors from different forms using overloaded get_context_data method, e.x:

views.py:

class LoginView(FormView):
    form_class = AuthFormEdited
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(LoginView, self).dispatch(request, *args, **kwargs)

    ....

    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = True
        return context

class SignInView(FormView):
    form_class = SignInForm
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(SignInView, self).dispatch(request, *args, **kwargs)

    .....

    def get_context_data(self, **kwargs):
        context = super(SignInView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = False
        return context

template:

<div class="login-form">
<form action="/login/" method="post" role="form">
    {% csrf_token %}
    {% if login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
    .....
    </form>
</div>

<div class="signin-form">
<form action="/registration/" method="post" role="form">
    {% csrf_token %}
    {% if not login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
   ....
  </form>
</div>

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

Defining static const integer members in class definition

My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.

You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr038.htm

Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).

Any idea as to what's going on?

std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.

Here's chapter/verse:

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

See Chu's answer for a possible workaround.

How do I integrate Ajax with Django applications?

I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:

ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin. If the request is an ajax request, it will not call the super.form_valid method, just call the form.save() directly.

from django.http import JsonResponse
from django import forms
from django.db import models

class AjaxableResponseMixin(object):
    success_return_code = 1
    error_return_code = 0
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            form.errors.update({'result': self.error_return_code})
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        if self.request.is_ajax():
            self.object = form.save()
            data = {
                'result': self.success_return_code
            }
            return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_valid(form)
            return response

class Product(models.Model):
    name = models.CharField('product name', max_length=255)

class ProductAddForm(forms.ModelForm):
    '''
    Product add form
    '''
    class Meta:
        model = Product
        exclude = ['id']


class PriceUnitAddView(AjaxableResponseMixin, CreateView):
    '''
    Product add view
    '''
    model = Product
    form_class = ProductAddForm

Convert a byte array to integer in Java and vice versa

byte[] toByteArray(int value) {
     return  ByteBuffer.allocate(4).putInt(value).array();
}

byte[] toByteArray(int value) {
    return new byte[] { 
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)value };
}

int fromByteArray(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, | 
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
     return ((bytes[0] & 0xFF) << 24) | 
            ((bytes[1] & 0xFF) << 16) | 
            ((bytes[2] & 0xFF) << 8 ) | 
            ((bytes[3] & 0xFF) << 0 );
}

When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).

There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int

byte[] bytes = (…)
if (bytes[0] == 0xFF) {
   // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}

Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.

GetFiles with multiple extensions

You can get every file, then filter the array:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dirInfo, params string[] extensions)
{
    var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);

    return dirInfo.EnumerateFiles()
                  .Where(f => allowedExtensions.Contains(f.Extension));
}

This will be (marginally) faster than every other answer here.
In .Net 3.5, replace EnumerateFiles with GetFiles (which is slower).

And use it like this:

var files = new DirectoryInfo(...).GetFilesByExtensions(".jpg", ".mov", ".gif", ".mp4");

How to set Status Bar Style in Swift 3

Swift 5

To add more detail for PRAVEEN's answer at https://stackoverflow.com/a/40066798/2082851, I would like to provide my implementation. It supports the flexibility to customize each controller's status bar.

In overall, we will create a BaseViewController which handle the statusBarStyle property in all the case. When you create a new controller, make it as subclass of this base controller.

Whenever you want to change the status appearance, you only need to update this property. The status bar style will be updated immediately.

Implementation

class BaseViewController: UIViewController {

    var statusBarStyle: UIStatusBarStyle = .default {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return statusBarStyle
    }
}

Demo

class ViewController: BaseViewController, UIScrollViewDelegate {

    let scrollView = UIScrollView()
    ... 
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        UIView.animate(withDuration: 0.3) {
            if scrollView.contentOffset.y > 30 {
                self.statusBarStyle = .darkContent
            } else {
                self.statusBarStyle = .lightContent
            }
        }
    }
}

enter image description here

2. UINavigationController

For UINavigationController, it is a special case, which you can follow either solutions:

Solution A: Override with message dispatch

Since UINavigationController is an NSObject and inherit from ObjectiveC, its methods are message dispatch and you can override them.

extension UINavigationController {
   open override var preferredStatusBarStyle: UIStatusBarStyle {
      return topViewController?.preferredStatusBarStyle ?? .default
   }
}

Solution B: Create UINavigationController subclass

If you already have a custom UINavigationController (which usually need to control more requirements), this is the best solution for you.

final class NavigationController: UINavigationController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return topViewController?.preferredStatusBarStyle ?? super.preferredStatusBarStyle
    }
}

converting multiple columns from character to numeric format in r

type.convert()

Convert a data object to logical, integer, numeric, complex, character or factor as appropriate.

Add the as.is argument type.convert(df,as.is = T) to prevent character vectors from becoming factors when there is a non-numeric in the data set.

See.

Convert absolute path into relative path given a current directory using Bash

My Solution:

computeRelativePath() 
{

    Source=$(readlink -f ${1})
    Target=$(readlink -f ${2})

    local OLDIFS=$IFS
    IFS="/"

    local SourceDirectoryArray=($Source)
    local TargetDirectoryArray=($Target)

    local SourceArrayLength=$(echo ${SourceDirectoryArray[@]} | wc -w)
    local TargetArrayLength=$(echo ${TargetDirectoryArray[@]} | wc -w)

    local Length
    test $SourceArrayLength -gt $TargetArrayLength && Length=$SourceArrayLength || Length=$TargetArrayLength


    local Result=""
    local AppendToEnd=""

    IFS=$OLDIFS

    local i

    for ((i = 0; i <= $Length + 1 ; i++ ))
    do
            if [ "${SourceDirectoryArray[$i]}" = "${TargetDirectoryArray[$i]}" ]
            then
                continue    
            elif [ "${SourceDirectoryArray[$i]}" != "" ] && [ "${TargetDirectoryArray[$i]}" != "" ] 
            then
                AppendToEnd="${AppendToEnd}${TargetDirectoryArray[${i}]}/"
                Result="${Result}../"               

            elif [ "${SourceDirectoryArray[$i]}" = "" ]
            then
                Result="${Result}${TargetDirectoryArray[${i}]}/"
            else
                Result="${Result}../"
            fi
    done

    Result="${Result}${AppendToEnd}"

    echo $Result

}

Reset Entity-Framework Migrations

You need to :

  1. Delete the state: Delete the migrations folder in your project; And
  2. Delete the __MigrationHistory table in your database (may be under system tables); Then
  3. Run the following command in the Package Manager Console:

    Enable-Migrations -EnableAutomaticMigrations -Force
    

    Use with or without -EnableAutomaticMigrations

  4. And finally, you can run:

    Add-Migration Initial
    

Django, creating a custom 500/404 error page

In Django 3.x, the accepted answer won't work because render_to_response has been removed completely as well as some more changes have been made since the version the accepted answer worked for.

Some other answers are also there but I'm presenting a little cleaner answer:

In your main urls.py file:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

In yourapp/views.py file:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response


def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

Ensure that you have imported render() in yourapp/views.py file:

from django.shortcuts import render

Side note: render_to_response() was deprecated in Django 2.x and it has been completely removed in verision 3.x.

Definition of "downstream" and "upstream"

Upstream (as related to) Tracking

The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking

For example :

   $git rev-list --count --left-right "@{upstream}"...HEAD
   >4   12

will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:

    >error: No upstream branch found for ''
  • As has already been said, you may have any number of remotes for one local repository, for example, if you fork a repository from github, then issue a 'pull request', you most certainly have at least two: origin (your forked repo on github) and upstream (the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.

Your .git/configreads :

   [remote "origin"]
       fetch = +refs/heads/*:refs/remotes/origin/*
       url = [email protected]:myusername/reponame.git
   [remote "upstream"]
       fetch = +refs/heads/*:refs/remotes/upstream/*
       url = [email protected]:authorname/reponame.git
  • On the other hand, @{upstream}'s meaning for GIT is unique :

it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.

It's the branch you fetch/pull from whenever you issue a plain git fetch/git pull, without arguments.

Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :

   $ git branch --set-upstream  master origin/master
   > Branch master set up to track remote branch master from origin.

This adds 2 parameters in .git/config :

   [branch "master"]
       remote = origin
       merge = refs/heads/master

now try (provided 'upstream' remote has a 'dev' branch)

   $ git branch --set-upstream  master upstream/dev
   > Branch master set up to track remote branch dev from upstream.

.git/config now reads:

   [branch "master"]
       remote = upstream
       merge = refs/heads/dev

git-push(1) Manual Page :

   -u
   --set-upstream

For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.<name>.merge in git-config(1).

git-config(1) Manual Page :

   branch.<name>.merge

Defines, together with branch.<name>.remote, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)

   branch.<name>.remote

When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.

Upstream and Push (Gotcha)

take a look at git-config(1) Manual Page

   git config --global push.default upstream
   git config --global push.default tracking  (deprecated)

This is to prevent accidental pushes to branches which you’re not ready to push yet.

Python conversion between coordinates

If your coordinates are stored as complex numbers you can use cmath

How to redirect page after click on Ok button on sweet alert?

Existing answers did not work for me i just used $('.confirm').hide(). and it worked for me.

success: function(res) {
$('.confirm').hide()
swal("Deleted!", "Successfully deleted", "success")
setTimeout(function(){
window.location = res.redirect_url;
},700);

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Download a file with Android, and showing the progress in a ProgressDialog

I found this blog post very helpful, Its using loopJ to download file, it has only one Simple function, will be helpful to some new android guys.

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

SELECT only rows that contain only alphanumeric characters in MySQL

Change the REGEXP to Like

SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'

this one works fine

How do I implement onchange of <input type="text"> with jQuery?

Here's the code I use:

$("#tbSearch").on('change keyup paste', function () {
    ApplyFilter();
});

function ApplyFilter() {
    var searchString = $("#tbSearch").val();
    //  ... etc...
}

<input type="text" id="tbSearch" name="tbSearch" />

This works quite nicely, particularly when paired up with a jqGrid control. You can just type into a textbox and immediately view the results in your jqGrid.

How to install XNA game studio on Visual Studio 2012?

On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I've just bumped into this same problem when listening for onMouseLeave events on a disabled button. I worked around it by listening for the native mouseleave event on an element that wraps the disabled button.

componentDidMount() {
    this.watchForNativeMouseLeave();
},
componentDidUpdate() {
    this.watchForNativeMouseLeave();
},
// onMouseLeave doesn't work well on disabled elements
// https://github.com/facebook/react/issues/4251
watchForNativeMouseLeave() {
    this.refs.hoverElement.addEventListener('mouseleave', () => {
        if (this.props.disabled) {
            this.handleMouseOut();
        }
    });
},
render() {
    return (
        <span ref='hoverElement'
            onMouseEnter={this.handleMouseEnter}
            onMouseLeave={this.handleMouseLeave}
        >
            <button disabled={this.props.disabled}>Submit</button>
        </span>
    );
}

Here's a fiddle https://jsfiddle.net/qfLzkz5x/8/

Java JTable getting the data of the selected row

Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

Cannot get a text value from a numeric cell “Poi”

CellType cell = row.getCell(j).getCellTypeEnum();

switch(cell) {
    case NUMERIC:
        intVal = row.getCell(j).getNumericCellValue();
        System.out.print(intVal);
        break;
    case STRING:
        stringVal = row.getCell(j).getStringCellValue();
        System.out.print(stringVal);
        break;
}

CSS3 Rotate Animation

I have a rotating image using the same thing as you:

.knoop1 img{
    position:absolute;
    width:114px;
    height:114px;
    top:400px;
    margin:0 auto;
    margin-left:-195px;
    z-index:0;

    -webkit-transition-duration: 0.8s;
    -moz-transition-duration: 0.8s;
    -o-transition-duration: 0.8s;
    transition-duration: 0.8s;

    -webkit-transition-property: -webkit-transform;
    -moz-transition-property: -moz-transform;
    -o-transition-property: -o-transform;
     transition-property: transform;

     overflow:hidden;
}

.knoop1:hover img{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg); 
    -o-transform:rotate(360deg);
}

Find intersection of two nested lists?

For people just looking to find the intersection of two lists, the Asker provided two methods:

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]

and

def intersect(a, b):
     return list(set(a) & set(b))

print intersect(b1, b2)

But there is a hybrid method that is more efficient, because you only have to do one conversion between list/set, as opposed to three:

b1 = [1,2,3,4,5]
b2 = [3,4,5,6]
s2 = set(b2)
b3 = [val for val in b1 if val in s2]

This will run in O(n), whereas his original method involving list comprehension will run in O(n^2)

How to grant permission to users for a directory using command line in Windows?

  1. navigate to top level directory you want to set permissions to with explorer
  2. type cmd in the address bar of your explorer window
  3. enter icacls . /grant John:(OI)(CI)F /T where John is the username
  4. profit

Just adding this because it seemed supremely easy this way and others may profit - all credit goes to Calin Darie.

How to show/hide if variable is null

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

How to dynamically set bootstrap-datepicker's date value?

Try

$("#datepicker").datepicker('setDate','25-05-2020').datepicker('fill');

This works for me when setDate is not updating the date picker text field value on browser. " The additional .datepicker('fill');" repopulate the bootstrap datepicker for new date which is set by setDate method.

How do I disable right click on my web page?

If your goal is to disallow users to simply save your images, you can also check if the clicked target is an image, only disable right click in that case. So right click can be used for other purposes. Taken from the code above:

document.addEventListener("contextmenu", function(e){
    if (e.target.nodeName === "IMG") {
        e.preventDefault();
    }
}, false);

This is just to take away the easiest way of saving your images, but it can still be done.

Static Initialization Blocks

It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):

public enum Language { 
  ENGLISH("eng", "en", "en_GB", "en_US"),   
  GERMAN("de", "ge"),   
  CROATIAN("hr", "cro"),   
  RUSSIAN("ru"),
  BELGIAN("be",";-)");

  static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>(); 
  static { 
    for (Language l:Language.values()) { 
      // ignoring the case by normalizing to uppercase
      ALIAS_MAP.put(l.name().toUpperCase(),l); 
      for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l); 
    } 
  } 

  static public boolean has(String value) { 
    // ignoring the case by normalizing to uppercase
    return ALIAS_MAP.containsKey(value.toUpper()); 
  } 

  static public Language fromString(String value) { 
    if (value == null) throw new NullPointerException("alias null"); 
    Language l = ALIAS_MAP.get(value); 
    if (l == null) throw new IllegalArgumentException("Not an alias: "+value); 
    return l; 
  } 

  private List<String> aliases; 
  private Language(String... aliases) { 
    this.aliases = Arrays.asList(aliases); 
  } 
} 

Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.

As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:

  1. The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
  2. static block and initialization of static fields in the order of occurrence.

This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):

public class Foo {
  static { System.out.println("Static Block 1"); }
  public static final Foo FOO = new Foo();
  static { System.out.println("Static Block 2"); }
  public Foo() { System.out.println("Constructor"); }
  static public void main(String p[]) {
    System.out.println("In Main");
    new Foo();
  }
}

What we see is the following output:

Static Block 1
Constructor
Static Block 2
In Main
Constructor

Clear is that the static initialization actually can happen before the constructor, and even after:

Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.

For more info on this see the book "Effective Java".

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Try putting this in your app/web.config:

<system.net>
    <settings>
        <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

If this doesn't work you may also try setting the KeepAlive property to false.

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

how to add value to a tuple?

OUTPUTS = []
for number in range(len(list_of_tuples))):
    tup_ = list_of_tuples[number]
    list_ = list(tup_)  
    item_ = list_[0] + list_[1] + list_[2] + list_[3]
    list_.append(item_)
    OUTPUTS.append(tuple(list_))

OUTPUTS is what you desire

Easiest way to convert a List to a Set in Java

Set<Foo> foo = new HashSet<Foo>(myList);

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

The exact name of the extension depends on the repository from which you got PHP but look here. For example on CentOS:

yum install -y php56w php56w-opcache php56w-xml php56w-mcrypt php56w-gd php56w-devel php56w-mysql php56w-intl php56w-mbstring php56w-bcmath

How to get english language word database?

You can find what you need on infochimps.org.

They have a list of 350,000 simple (ie non-compound) words available for free download.

Word List - 350,000+ Simple English Words

Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.

Extract substring from a string

If you know the Start and End index, you can use

String substr=mysourcestring.substring(startIndex,endIndex);

If you want to get substring from specific index till end you can use :

String substr=mysourcestring.substring(startIndex);

If you want to get substring from specific character till end you can use :

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));

If you want to get substring from after a specific character, add that number to .indexOf(char):

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

window.open with headers

If you are in control of server side, it might be possible to set header value in query string and send it like that? That way you could parse it from query string if it's not found in the headers.

Just an idea... And you asked for a cunning hack :)

Map a network drive to be used by a service

The reason why you are able to access the drive in when you normally run the executable from command prompt is that when u are executing it as normal exe you are running that application in the User account from which you have logged on . And that user has the privileges to access the network. But , when you install the executable as a service , by default if you see in the task manage it runs under 'SYSTEM' account . And you might be knowing that the 'SYSTEM' doesn't have rights to access network resources.

There can be two solutions to this problem.

  1. To map the drive as persistent as already pointed above.

  2. There is one more approach that can be followed. If you open the service manager by typing in the 'services.msc'you can go to your service and in the properties of your service there is a logOn tab where you can specify the account as any other account than 'System' you can either start service from your own logged on user account or through 'Network Service'. When you do this .. the service can access any network component and drive even if they are not persistent also. To achieve this programmatically you can look into 'CreateService' function at http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx and can set the parameter 'lpServiceStartName ' to 'NT AUTHORITY\NetworkService'. This will start your service under 'Network Service' account and then you are done.

  3. You can also try by making the service as interactive by specifying SERVICE_INTERACTIVE_PROCESS in the servicetype parameter flag of your CreateService() function but this will be limited only till XP as Vista and 7 donot support this feature.

Hope the solutions help you.. Let me know if this worked for you .

Could not instantiate mail function. Why this error occurring

An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

Due to controversial votes on this answer (+4/-4 as of this edit), PLEASE LOOK AT THE OTHER ANSWERS FIRST AND USE THIS ONLY AS A LAST RESORT. I only used this once for a networking app that runs as root and I agree with the general opinion that this solution should not be used under normal circumstances.

Original answer below:

The other answers are all correct, but I'd like to point out that another way to get around this is to ask user to disable battery optimizations for your app (this isn't usually a good idea unless your app is system related). See this answer for how to request to opt out of battery optimizations without getting your app banned in Google Play.

You should also check whether battery optimizations are turned off in your receiver to prevent crashes via:

if (Build.VERSION.SDK_INT < 26 || getSystemService<PowerManager>()
        ?.isIgnoringBatteryOptimizations(packageName) != false) {
    startService(Intent(context, MyService::class.java))
} // else calling startService will result in crash

MySQL Error 1215: Cannot add foreign key constraint

Reasons you may get a foreign key constraint error:

  1. You are not using InnoDB as the engine on all tables.
  2. You are trying to reference a nonexistent key on the target table. Make sure it is a key on the other table (it can be a primary or unique key, or just a key)
  3. The types of the columns are not the same (exception is the column on the referencing table can be nullable even if it is not nullable on the referenced table).
  4. If the PK/FK is a varchar make sure the collation is the same for both.

Update:

  1. One of the reasons may also be that the column you are using for ON DELETE SET NULL is not defined to be null. So make sure that the column is set default null.

Check these.

How do I access the HTTP request header fields via JavaScript?

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

How to kill a running SELECT statement

To kill a session in Oracle, you use the ALTER SYSTEM KILL SESSION command.

Details here: http://www.oracle-base.com/articles/misc/KillingOracleSessions.php

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

Adding devices to team provisioning profile

login to developer account of apple and open the provision profile that you have selected in settings and add the device . The device will automatically displayed if connected to PC.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

My solution, having encountered the same error message, was even simpler than the ones above, I just updated the to basicHttpsBinding>

  <bindings>
    <basicHttpsBinding>
    <binding name="ShipServiceSoap" maxBufferPoolSize="512000" maxReceivedMessageSize="512000" />
    </basicHttpsBinding>
    </bindings>

And the same in the section below:

  <client>
    <endpoint address="https://s.asmx" binding="basicHttpsBinding" bindingConfiguration="ShipServiceSoap" contract="..ServiceSoap" name="ShipServiceSoap" />
    </client>

Programmatically relaunch/recreate an activity?

UPDATE: Android SDK 11 added a recreate() method to activities.


I've done that by simply reusing the intent that started the activity. Define an intent starterIntent in your class and assign it in onCreate() using starterIntent = getIntent();. Then when you want to restart the activity, call finish(); startActivity(starterIntent);

It isn't a very elegant solution, but it's a simple way to restart your activity and force it to reload everything.

What is the App_Data folder used for in Visual Studio?

It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.

"The semaphore timeout period has expired" error for USB connection

This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

How can I wait for 10 second without locking application UI in android

1with handler:

handler.sendEmptyMessageDelayed(1, 10000);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
};

How to move a file?

os.rename(), shutil.move(), or os.replace()

All employ the same syntax:

import os
import shutil

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

Note also that in the first two cases the directory in which the new file is being created must already exist. On Windows, a file with that name must not exist or an exception will be raised, but os.replace() will silently replace a file even in that occurrence.

As has been noted in comments on other answers, shutil.move simply calls os.rename in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How do I find Waldo with Mathematica?

I've found Waldo!

waldo had been found

How I've done it

First, I'm filtering out all colours that aren't red

waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];

Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.

corr = ImageCorrelate[red, 
   Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]], 
   NormalizedSquaredEuclideanDistance];

I use Binarize to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation

pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];

I had to play around a little with the level. If the level is too high, too many false positives are picked out.

Finally I'm combining this result with the original image to get the result above

found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]

Getting the last n elements of a vector. Is there a better way than using the length() function?

Here is a function to do it and seems reasonably fast.

endv<-function(vec,val) 
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}

USAGE:

test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)

BENCHMARK:

                                                    test replications elapsed relative
1                                 expression(tail(x, 5))       100000    5.24    6.469
2 expression(x[seq.int(to = length(x), length.out = 5)])       100000    0.98    1.210
3                       expression(x[length(x) - (4:0)])       100000    0.81    1.000
4                                 expression(endv(x, 5))       100000    1.37    1.691

About .bash_profile, .bashrc, and where should alias be written in?

The reason you separate the login and non-login shell is because the .bashrc file is reloaded every time you start a new copy of Bash. The .profile file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.

Personally,

  • I put my PATH setup into a .profile file (because I sometimes use other shells);
  • I put my Bash aliases and functions into my .bashrc file;
  • I put this

    #!/bin/bash
    #
    # CRM .bash_profile Time-stamp: "2008-12-07 19:42"
    #
    # echo "Loading ${HOME}/.bash_profile"
    source ~/.profile # get my PATH setup
    source ~/.bashrc  # get my Bash aliases
    

    in my .bash_profile file.

Oh, and the reason you need to type bash again to get the new alias is that Bash loads your .bashrc file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc file (and not need a second shell) by typing

source ~/.bashrc

which loads the .bashrc file as if you had typed the commands directly to Bash.

What is the best method of handling currency/money?

If someone is using Sequel the migration would look something like:

add_column :products, :price, "decimal(8,2)"

somehow Sequel ignores :precision and :scale

(Sequel Version: sequel (3.39.0, 3.38.0))

How to import component into another root component in Angular 2

You should declare it with declarations array(meta property) of @NgModule as shown below (RC5 and later),

import {CoursesComponent} from './courses.component';

@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent,CoursesComponent],  //<----here
  providers:    [],      
  bootstrap:    [ AppComponent ]
})

Eclipse IDE: How to zoom in on text?

To zoom on Eclipse you can use : CTRL SHIFT + OR -

How to get the last character of a string in a shell?

Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...

str='abcd/'
echo "${str: -1}"

Output: /

str='abcd*'
echo "${str: -1}"

Output: *

Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!

Iterate over object in Angular

The dictionary is an object, not an array. I believe ng-repeat requires an array in Angular 2.

The simplest solution would be to create a pipe/filter that converts the object to an array on the fly. That said, you probably want to use an array as @basarat says.

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Be wary, too, of inheriting workspace settings in your projects for Java Compiler/Compliance settings. I had a project that was imported into Eclipse. Eclipse generated the project with a J2SE 1.4 JRE, compiler, and compliance settings.

When I went in and manually updated these settings and un-checked the "Enable project specific settings" box, I was still receiving build errors relating to 1.5 level compliance (even though the workspace settings were clearly 1.6). It wasn't until I re-checked the "Enable project specific settings" box and manually set the compiler/compliance levels to 1.6 did the errors go away.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

git fetch origin
git reset --hard origin/master
git pull

Explanation:

  • Fetch will download everything from another repository, in this case, the one marked as "origin".
  • Reset will discard changes and revert to the mentioned branch, "master" in repository "origin".
  • Pull will just get everything from a remote repository and integrate.

See documentation at http://git-scm.com/docs.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

I would say that you have a problem connecting from PHP to MySQL...

Something like PHP trying to find some socket file, and not finding it, maybe ?
(I've had this problem a couple of times -- not sure the error I got was exactly this one, though)


If you are running some Linux-based system, there should be a my.cnf file somewhere, that is used to configure MySQL -- on my Ubuntu, it's in /etc/mysql/.

In this file, there might be something like this :

socket = /var/run/mysqld/mysqld.sock


PHP need to use the same file -- and, depending on your distribution, the default file might not be the same as the one that MySQL uses.

In this case, adding these lines to your php.ini file might help :

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock
pdo_mysql.default_socket = /var/run/mysqld/mysqld.sock

(You'll need to restart Apache so the modification to php.ini is taken into account)

The last one should be enough for PDO, which is used by Zend Framework -- but the two previous ones will not do any harm, and can be useful for other applications.


If this doesn't help : can you connect to your database using PDO, in another script, that's totally independant of Zend Framework ?

i.e. does something like this work (quoting) :

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

If no, the problem is definitly not with ZF, and is a configuration / installation problem of PHP.

If yes... Well, it means you have a problem with ZF, and you'll need to give us more informations about your setup (like your DSN, for instance ? )

How do I toggle an ng-show in AngularJS based on a boolean?

You just need to toggle the value of "isReplyFormOpen" on ng-click event

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

How is CountDownLatch used in Java Multithreading?

As mentioned in JavaDoc (https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html), CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code

    T1.join();
    T2.join();
    T3.join();

The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests : countDownLatch.await();
where as "T1","T2","T3" does countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

Add a scrollbar to a <textarea>

What you need is overflow-y: scroll;

Demo

_x000D_
_x000D_
    textarea {_x000D_
        overflow-y: scroll;_x000D_
        height: 100px;_x000D_
        resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
    }
_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851