Programs & Examples On #Facetime

How to convert Map keys to array?

OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:

The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

As you mentioned, you can easily create an instance of Map using new keyword... In your case:

let myMap = new Map().set('a', 1).set('b', 2);

So let's see...

The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...

Map has many methods which you can use, like set() which you already used to assign the key values...

One of them is keys() which returns all the keys...

In your case, it will return:

MapIterator {"a", "b"}

and you easily convert them to an Array using ES6 ways, like spread operator...

const b = [...myMap.keys()];

Difference between an API and SDK

API is like the building blocks of some puzzling game that a child plays with to join blocks in different shapes and build something they can think of.

SDK, on the other hand, is a proper workshop where all of the development tools are available, rather than pre-shaped building blocks. In a workshop you have the actual tools and you are not limited to blocks, and can therefore make your own blocks, or can create something without any blocks to begin with.

coding without an SDK or API is like making everything from scratch without a workshop - you have to even make your own tools

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder

for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"

CSS '>' selector; what is it?

It means parent/child

example:

html>body

that's saying that body is a child of html

Check out: Selectors

Why do you need to invoke an anonymous function on the same line?

Drop the semicolon after the function definition.

(function (msg){alert(msg)})
('SO');

Above should work.

DEMO Page: https://jsfiddle.net/e7ooeq6m/

I have discussed this kind of pattern in this post:

jQuery and $ questions

EDIT:

If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)

1. Using Function constructor

var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2. Using Function declaration.

function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10

So you may ask, what's the difference between declaration and expression?

From ECMA Script specification:

FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }

FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }

If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.

This means following is valid.

var sum = function mySum(a, b) { return a + b; }

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:

var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

Live Demo

Compare this to

 function test1() { alert(typeof test1) };

 alert(typeof test1); //alerts 'function'

 test1(); //alerts 'function'

Armed with this knowledge, let's try to analyze your code.

When you have code like,

    function(msg) { alert(msg); }

You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.

    (function(msg) { alert(msg); })('SO'); //alerts SO.

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

I think this is similar to kouton's answer, but this one just takes in a timeStamp and returns a timestamp SOMEWHERE in the next month. You could use date("m", $nextMonthDateN) from there.

function nextMonthTimeStamp($curDateN){ 
   $nextMonthDateN = $curDateN;
   while( date("m", $nextMonthDateN) == date("m", $curDateN) ){
      $nextMonthDateN += 60*60*24*27;
   }
   return $nextMonthDateN; //or return date("m", $nextMonthDateN);
}

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Convert a string into an int

Swift 3.0:

Int("5")

or

let stringToConvert = "5"
Int(stringToConvert)

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

While variable is not defined - wait

I prefer something simple like this:

function waitFor(variable, callback) {
  var interval = setInterval(function() {
    if (window[variable]) {
      clearInterval(interval);
      callback();
    }
  }, 200);
}

And then to use it with your example variable of someVariable:

waitFor('someVariable', function() {
  // do something here now that someVariable is defined
});

Note that there are various tweaks you can do. In the above setInterval call, I've passed 200 as how often the interval function should run. There is also an inherent delay of that amount of time (~200ms) before the variable is checked for -- in some cases, it's nice to check for it right away so there is no delay.

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

ipynb import another ipynb file

Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well. Thanks all!

How to exit an Android app programmatically?

It's way too easy. Use System.exit(0);

Using GSON to parse a JSON array

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
    "number": "...",
    "title": ".." ,  //<- see that comma?
}

If you remove them your data will become

[
    {
        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"
    }
]

and

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

should work fine.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

In my case, my site was hosted on shared hosting and there was a resource over usage not even relating to my database, thus my database was locked down, the hosting panel was Plesk

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

hibernate could not get next sequence value

For anyone using FluentNHibernate (my version is 2.1.2), it's just as repetitive but this works:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id).Column("id").GeneratedBy.SequenceIdentity("users_id_seq");

How to add an existing folder with files to SVN?

If I correctly understood your use case, I suggest to try using svn add to put the new folder under version, see here. The following will add the new folder with files recursively under version control (if you are inside valid working copy):

svn add new_folder
svn commit -m "Add New folder to the project"

If you are not in a working copy, create it with svn checkout, copy new_folder there and do the above steps.

OR

Try svn import, see here; the following will create a new folder and upload files to the repository:

svn import -m "Import new folder to the project" new_folder \
        http://SVN_REPO/repos/trunk/new_folder

Also note that:

After importing data, note that the original tree is not under version control. To start working, you still need to svn checkout a fresh working copy of the tree

Eclipse doesn't stop at breakpoints

Running under Ubuntu 18.04LTS in a VirtualBox VM. This answer pertains to Eclipse PTP.

By default, double clicking on the left margin was adding PTP Breakpoints (I am not familiar with PTP debugging). Those apparently do not make debugging stop. I right-clicked on a breakpoint -> Breakpoint Types -> C/C++ Breakpoints, and it started inserting this other "usual" type of breakpoints.

You can tell one from the other, as they are indicated with large green vs. small purple circles.

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

How long is the SHA256 hash?

Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.

Identifier not found error on function call

Add this line before main function:

void swapCase (char* name);

int main()
{
   ...
   swapCase(name);    // swapCase prototype should be known at this point
   ...
}

This is called forward declaration: compiler needs to know function prototype when function call is compiled.

Add a summary row with totals

If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

SELECT
  Type = ISNULL(Type, 'Total'),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

SELECT
  Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

How might I force a floating DIV to match the height of another floating DIV?

If you are trying to force a floating div to match another to create a column effect, this is what I do. I like it because it's simple and clean.

<div style="background-color: #CCC; width:300px; overflow:hidden; ">
    <!-- Padding-Bottom is equal to 100% of the container's size, Margin-bottom hides everything beyond
         the container equal to the container size. This allows the column to grow with the largest
         column. -->
    <div style="float: left;width: 100px; background:yellow; padding-bottom:100%; margin-bottom:-100%;">column a</div>
    <div style="float: left;width: 100px;  background:#09F;">column b<br />Line 2<br />Line 3<br />Line 4<br />Line 5</div>
    <div style="float:left; width:100px; background: yellow; padding-bottom:100%; margin-bottom:-100%;">Column C</div>
    <div style="clear: both;"></div>
</div>

I think this makes sense. It seems to work well even with dynamic content.

What is the difference between Swing and AWT?

  • swing component provide much flexible user interface because it follow model view controller(mvc).
  • awt is not mvc based.
  • swing works faster.
  • awt does not work faster.
  • swing components are light weight.
  • awt components are heavy weight.
  • swing occupies less memory space.
  • awt occupies more memory space.
  • swing component is platform independent.
  • awt is platform dependent.
  • swing require javax.swing package.
  • awt require javax.awt package.

Unable to load DLL 'SQLite.Interop.dll'

Try to set the platform target to x86 or x64 (and not Any CPU) before you build: Project->Properties->Build->Platform target in Visual Studio.

How to remove a TFS Workspace Mapping?

Finally deleted ALL workspaces and started from scratch. Fixed.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

SSH SCP Local file to Remote in Terminal Mac Os X

At first, you need to add : after the IP address to indicate the path is following:

scp magento.tar.gz [email protected]:/var/www

I don't think you need to sudo the scp. In this case it doesn't affect the remote machine, only the local command.

Then if your user@xx.x.x.xx doesn't have write access to /var/www then you need to do it in 2 times:

Copy to remote server in your home folder (: represents your remote home folder, use :subfolder/ if needed, or :/home/user/ for full path):

scp magento.tar.gz [email protected]:

Then SSH and move the file:

ssh [email protected]
sudo mv magento.tar.gz /var/www

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

Tools for making latex tables in R

Another R package for aggregating multiple regression models into LaTeX tables is texreg.

How to make an Android Spinner with initial text "Select One"?

I found this solution:

String[] items = new String[] {"Select One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
        items[0] = "One";
        selectedItem = items[position];
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }
});

Just change the array[0] with "Select One" and then in the onItemSelected, rename it to "One".

Not a classy solution, but it works :D

zsh compinit: insecure directories

These two lines have fixed for me.

sudo chown -R _user_:root /usr/local/share/zsh

sudo chown -R _user_:root /usr/local/share/zsh/*

How would I create a UIAlertView in Swift?

SwiftUI on Swift 5.x and Xcode 11.x

import SwiftUI

struct ContentView: View {

    @State private var isShowingAlert = false

    var body: some View {
        VStack {
            Button("A Button") {

                self.isShowingAlert.toggle()
            }
            .alert(isPresented: $isShowingAlert) { () -> Alert in
                Alert(
                    title: Text("Alert"),
                    message: Text("This is an alert"),
                    dismissButton:
                        .default(
                            Text("OK"),
                            action: {
                                print("Dismissing alert")
                            }
                        )
                )
            }

        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Applying styles to tables with Twitter Bootstrap

you can Add contextual classes to every single row as follows:

<tr class="table-success"></tr>
<tr class="table-error"></tr>
<tr class="table-warning"></tr>
<tr class="table-info"></tr>
<tr class="table-danger"></tr>

You can also add them to table data same as above

You can set your table size by setting classes as table-sm and so on.

You can add custom classes and add your own styling:

<table class="table">
  <thead style = "color:red;background-color:blue">
    <tr>
      <th></th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>   
      <td>Asdf</td>
      <td>qwerty</td>
    </tr>
  </tbody>
</table>

This way you can add custom styling. I have showed inline styling just for example how it works, you can add classes and call them in your css as well.

phonegap open link in browser

As suggested in a similar question, use JavaScript to call window.open with the target argument set to _system, as per the InAppBrowser documentation:

<a href="#" onclick="window.open('http://www.kidzout.com', '_system'); return false;">www.kidzout.com</a>

This should work, though a better and more flexible solution would be to intercept all links' click events, and call window.open with arguments read from the link's attributes.

Remember you must install the InAppBrowser plugin for this to work:

cordova plugin add cordova-plugin-inappbrowser

Error:java: javacTask: source release 8 requires target release 1.8

I fixed this by going to Project Structure -> Modules, find the module in question, click on Dependencies tab, change Module SDK to Project SDK.

iPhone Navigation Bar Title text color

Modern approach

The modern way, for the entire navigation controller… do this once, when your navigation controller's root view is loaded.

[self.navigationController.navigationBar setTitleTextAttributes:
   @{NSForegroundColorAttributeName:[UIColor yellowColor]}];

However, this doesn't seem have an effect in subsequent views.

Classic approach

The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):

You need to use a UILabel as the titleView of the navigationItem.

The label should:

  • Have a clear background color (label.backgroundColor = [UIColor clearColor]).
  • Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).
  • Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).
  • You'll want to set the text alignment to centered as well (label.textAlignment = NSTextAlignmentCenter (UITextAlignmentCenter for older SDKs).

Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.

I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)

If you want to verify this, drop this code into initWithNibName:bundle: in PageThreeViewController.m of Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // this will appear as the title in the navigation bar
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = NSTextAlignmentCenter;
                           // ^-Use UITextAlignmentCenter for older SDKs.
        label.textColor = [UIColor yellowColor]; // change this color
        self.navigationItem.titleView = label;
        label.text = NSLocalizedString(@"PageThreeTitle", @"");
        [label sizeToFit];
    }

    return self;
}

Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.

Database design for a survey

No 2 looks fine.

For a table with only 4 columns it shouldn't be a problem, even with a good few million rows. Of course this can depend on what database you are using. If its something like SQL Server then it would be no problem.

You'd probably want to create an index on the QuestionID field, on the tblAnswer table.

Of course, you need to specify what Database you are using as well as estimated volumes.

How to reset AUTO_INCREMENT in MySQL?

Best way is remove the field with AI and add it again with AI, works for all tables

Is there a way to create multiline comments in Python?

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

Can an html element have multiple ids?

That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.

Cannot assign requested address - possible causes?

It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.

EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.

What's the difference between all the Selection Segues?

Here is a quick summary of the segues and an example for each type.

Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail

Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout

Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings

Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar

Custom - You may implement your own custom segue and have control over its behavior

The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.

For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Bash script error [: !=: unary operator expected

Quotes!

if [ "$1" != -v ]; then

Otherwise, when $1 is completely empty, your test becomes:

[ != -v ]

instead of

[ "" != -v ]

...and != is not a unary operator (that is, one capable of taking only a single argument).

Display A Popup Only Once Per User

Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.

$scope.storage = $localStorage; //connects an object to $localstorage

$scope.storage.hasSeenPopup = "false";  // they haven't seen it


$scope.showPopup = function() {  // popup to tell people to turn sound on

    $scope.data = {}
    // An elaborate, custom popup
    var myPopup = $ionicPopup.show({
        template: '<p class="popuptext">Turn Sound On!</p>',
        cssClass: 'popup'

    });        
    $timeout(function() {
        myPopup.close(); //close the popup after 3 seconds for some reason
    }, 2000);
    $scope.storage.hasSeenPopup = "true"; // they've now seen it

};

$scope.playStream = function(show) {
    PlayerService.play(show);

    $scope.audioObject = audioObject; // this allow for styling the play/pause icons

    if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
        $scope.showPopup();
    }
}

Send Email Intent

This works for me:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL  , new String[] { "[email protected]" });
intent.putExtra(Intent.EXTRA_SUBJECT, "My subject");

startActivity(Intent.createChooser(intent, "Email via..."));

i.e. use the ACTION_SENDTO action rather than the ACTION_SEND action. I've tried it on a couple of Android 4.4 devices and it limits the chooser pop-up to only display email applications (Email, Gmail, Yahoo Mail etc) and it correctly inserts the email address and subject into the email.

What is the "Temporary ASP.NET Files" folder for?

These are what's known as Shadow Copy Folders.

Simplistically....and I really mean it:

When ASP.NET runs your app for the first time, it copies any assemblies found in the /bin folder, copies any source code files (found for example in the App_Code folder) and parses your aspx, ascx files to c# source files. ASP.NET then builds/compiles all this code into a runnable application.

One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.

ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.

Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.

This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

Can't start Eclipse - Java was started but returned exit code=13

Your version of Eclipse is 64-bit, based on the paths and filenames. However, the version of Java that it's picking up is 32-bit, as indicated by where it is coming from, on this line:

-vm C:\Program Files (x86)\Java\jre7\bin\javaw.exe

Program Files (x86) is the folder where 64-bit Windows places 32-bit programs.

Program Files is the folder where 64-bit Windows places 64-bit programs.

This can happen when a system has more than one JVM installed, as is often the case on Windows 64-bit (for example, the JRE download page uses the bit-ness of the browser to determine what bit-ness download to offer you, and many people use(d) 32-bit browsers even though they run 64-bit Windows).

The best way to fix this, assuming you do in fact have 64-bit JRE or JDK on your system, is to specify in eclipse.ini exactly which JVM you want it to use. The instructions are detailed in the Eclipse wiki page, but basically you have to specify the -vm option in the ini file - make sure to read the wiki page carefully as the format is very specific.

Specifying the JVM path in eclipse.ini is strongly recommended because doing so isolates Eclipse from any potential changes to your system PATH that some program installers might make (I'm talking to you, Oracle!).

Another option would be to download and use 32-bit Eclipse instead of 64-bit, but it's still strongly recommended to specify the path to the JVM in eclipse.ini.


Left for historical reference:

To check your version of Java, run

  java -version 

in a console (command prompt). On Windows 7 with 64-bit Java 6 I get:

  java version "1.6.0_27"
  Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
  Java HotSpot(TM) 64-Bit Server VM (build 20.2-b06, mixed mode)

Note the 3rd line, which shows that this is a 64-bit version.

On a 32-bit version you'll get something like:

  Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing) 

If you are on a 64-bit machine, then you can install the 64-bit JDK and uninstall the 32-bit one. For instance on Windows 10, just go to Settings and under Apps, you will find Java. Click on it and you will find all the different versions. Now you can select which one to uninstall.

How to tell which commit a tag points to in Git?

On my repository, git show-ref TAG shows the tag's hash, not the hash of the commit it points to.

git show-ref --dereference TAG shows, additionally, the commit being pointed at.

Using 24 hour time in bootstrap timepicker

This will surely help on bootstrap timepicker

format :"DD:MM:YYYY HH:mm"

Cut Corners using CSS

I recently cut off the top right corner and overlaid the tabs like folders. Complete code noob, so ignore the shitty code, but I did this by combining a square, a triangle, and a rectangle... This may or may not be a new approach, but hopefully, someone finds it helpful.

https://i.stack.imgur.com/qFMRz.png

Here is the HTML:

<!DOCTYPE html>
<html lang ="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="style.css"> 
    </head>
    <body>
        <div class="folders">
            <div class="container">
                <div class="triangleOne">
                    <p class="folderNames">Home</p>
                </div>
                <div class="triangleOneCut">
                </div>
                <div class="triangleOneFill">
                </div>
            </div>

            <div class="container2">
                <div class="triangleOne blue">
                    <p class="folderNames">About</p>
                </div>
                <div class="triangleOneCut blueCut">
                </div>
                <div class="triangleOneFill blue">
                </div>
            </div>

            <div class="container3">
                <div class="triangleOne green">
                    <p class="folderNames">Contact</p>
                </div>
                <div class="triangleOneCut greenCut">
                </div>
                <div class="triangleOneFill green">
                </div>
            </div>
        </div>
    </body>
</html>

Here is the CSS:

.triangleOne {
    height: 50px;
    width: 40px;
    background: red;
    border-radius: 5px 0px 0px 5px;
    position: absolute;
}

.triangleOneCut {
    content: '';
    position: absolute;
    top: 0; left: 40px;
    border-top: 10px solid transparent;
    border-left: 10px solid red;
    width: 0;
}

.triangleOneFill {
    content: '';
    position: absolute;
    top: 10px; left: 40px;
    width: 10px;
    height: 40px;
    background-color: red;
    border-radius: 0px 0px 5px 0px;
}

.container {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    z-index: 3;
}

.container2 {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    left: -10px;
    z-index: 2;
}

.container3 {
    position: relative;
    height: 50px;
    width: 50px;
    display: inline-block;
    left: -20px;
    z-index: 1;
}

.blue {
    background-color: blue;
}

.green {
    background-color: green;
}

.blueCut {
    border-left: 10px solid blue;
}

.greenCut {
    border-left: 10px solid green;
}

.folders {
    width: 160px;
    height: 50px;
    /* border: 10px solid white; */
    margin: auto;
    padding-left: 25px;
    margin-top: 100px;
}

.folderNames {
    text-align: right;
    padding-left: 2px;
    color: white;
    margin-top: 1.5px;
    font-family: monospace;
    font-size: 6.5px;
    border-bottom: double 1.5px white;
}

difference between variables inside and outside of __init__()

Without Self

Create some objects:

class foo(object):
    x = 'original class'

c1, c2 = foo(), foo()

I can change the c1 instance, and it will not affect the c2 instance:

c1.x = 'changed instance'
c2.x
>>> 'original class'

But if I change the foo class, all instances of that class will be changed as well:

foo.x = 'changed class'
c2.x
>>> 'changed class'

Please note how Python scoping works here:

c1.x
>>> 'changed instance'

With Self

Changing the class does not affect the instances:

class foo(object):
    def __init__(self):
        self.x = 'original self'

c1 = foo()
foo.x = 'changed class'
c1.x
>>> 'original self'

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

Vim: faster way to select blocks of text in visual mode

} means move cursor to next paragraph. so, use v} to select entire paragraph.

Running Composer returns: "Could not open input file: composer.phar"

You can do

curl -sS https://getcomposer.org/installer | php

The -sS flag meaning don't show progress, do show errors

and then

php composer.phar install

from: How do I get cURL to not show the progress bar?

https://packagist.org/

WPF User Control Parent

Different approaches and different strategies. In my case I could not find the window of my dialog either through using VisualTreeHelper or extension methods from Telerik to find parent of given type. Instead, I found my my dialog view which accepts custom injection of contents using Application.Current.Windows.

public Window GetCurrentWindowOfType<TWindowType>(){
 return Application.Current.Windows.OfType<TWindowType>().FirstOrDefault() as Window;
}

HTML5 Video tag not working in Safari , iPhone and iPad

What helped in my case was dropping the audio track. It was silent before, but it had to be gone completely.

On ubuntu:

ffmpeg -i input.mp4 -vcodec copy -an output.mp4

And safari/desktop start to play the video

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How can I list all tags for a Docker image on a remote registry?

I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.

<html>
<pre style="background-color:#bcbbbb;">
@echo off

docker login --username=xxxx --password=xxxx
docker pull %1:%2

IF NOT %ERRORLEVEL%==0 (
echo "Specified Version is Not Found "
echo "Available Version for this image is :"
for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" https://hub.docker.com/v2/users/login ^|jq -r .token ') do set TOKEN=%%i
curl -sH "Authorization: JWT %TOKEN%" "https://hub.docker.com/v2/repositories/%1/tags/" | jq .results[].name
)
</pre>
</html>

So in this we can give arguments to out batch file like:

Dockerfile java version7 

How to implement if-else statement in XSLT?

The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:

<xsl:variable name="CreatedDate" select="@createDate"/>
     <xsl:variable name="IDAppendedDate" select="2012-01-01" />
     <b>date: <xsl:value-of select="$CreatedDate"/></b> 
     <xsl:if test="$CreatedDate &gt; $IDAppendedDate">
        <h2> mooooooooooooo </h2>
     </xsl:if>
     <xsl:if test="$CreatedDate &lt;= $IDAppendedDate">
        <h2> dooooooooooooo </h2>
     </xsl:if>

Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl

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

Upgrade pip as follows:

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

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

What's happening:

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

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

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

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

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

and we recommend you do that by April 8th.

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

Also, the Python status page:

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

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

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

pip install --upgrade setuptools

Is there a way to use max-width and height for a background image?

Unfortunately there's no min (or max)-background-size in CSS you can only use background-size. However if you are seeking a responsive background image you can use Vmin and Vmaxunits for the background-size property to achieve something similar.

example:

#one {
    background:url('../img/blahblah.jpg') no-repeat;
    background-size:10vmin 100%;
}

that will set the height to 10% of the whichever smaller viewport you have whether vertical or horizontal, and will set the width to 100%.

Read more about css units here: https://www.w3schools.com/cssref/css_units.asp

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at https://youtu.be/nuugoG5c-7M

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/logging.properties points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

What is the difference between partitioning and bucketing a table in Hive ?

The difference is bucketing divides the files by Column Name, and partitioning divides the files under By a particular value inside table

Hopefully I defined it correctly

Node.js Hostname/IP doesn't match certificate's altnames

To fix the issue for package http-proxy

1) HTTP (localhost) accessing HTTPS To fix this issue set changeOrigin to true.

const proxy = httpProxy.createProxyServer();

proxy.web(req, res, {
  changeOrigin: true,
  target: https://example.com:3000,
});

2) HTTPS accessing HTTPS you should include SSL certificate

httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  },
  target: 'https://example.com:3000',
  secure: true
}).listen(443);

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

MVC4 HTTP Error 403.14 - Forbidden

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/> 
 </system.webServer>

U can use above code

jQuery Mobile: Stick footer to bottom of page

http://ryanfait.com/sticky-footer/

You could possibly use this and use jQuery to update the css height of the elements to make sure it stays in place.

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

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

I hope this helps someone.

STUFF ( character_expression , start , length ,character_expression )

select stuff(@str, 1, 0, replicate('0', @n - len(@str)))

Java error - "invalid method declaration; return type required"

I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

How to wait in a batch script?

Well, does sleep even exist on your Windows XP box? According to this post: http://malektips.com/xp_dos_0002.html sleep isn't available on Windows XP, and you have to download the Windows 2003 Resource Kit in order to get it.

Chakrit's answer gives you another way to pause, too.

Try running sleep 10 from a command prompt.

How to get the html of a div on another page with jQuery ajax?

$.ajax({
  url:href,
  type:'get',
  success: function(data){
   console.log($(data)); 
  }
});

This console log gets an array like object: [meta, title, ,], very strange

You can use JavaScript:

var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))

SQL Joins Vs SQL Subqueries (Performance)?

I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN is a very slow operator, since SQL normally evaluates it as a series of WHERE clauses separated by "OR" (WHERE x=Y OR x=Z OR...).

As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.

The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

How to delete a stash created with git stash create?

If you are 100% sure that you have just one stash or you want to delete all stashes (make a git stash list to be 107% sure), you can do a:

git stash clear

..and forget about them (it deletes all stashes).

Note: Added this answer for those who ended up here looking for a way to clear them all (like me).

Could not find any resources appropriate for the specified culture or the neutral culture

I just hit this same exception in a WPF project. The issue occurred within an assembly that we recently moved to another namespace (ProblemAssembly.Support to ProblemAssembly.Controls). The exception was happening when trying to access resources from a second resource file that exists in the assembly.

Turns out the additional resource file did not properly move references from the old namespace name to the new namespace name.

In the designer.cs for the resource file, there is a static property to get the ResourceManager. Within that getter, the string was still referring the old namespace. Once correcting it to the new namespace, the problem was resolved:

global::System.Resources.ResourceManager temp = 
     new global::System.Resources.ResourceManager(
          "ProblemAssembly.Support.Properties.Stuff", typeof(Stuff).Assembly);

should have been:

global::System.Resources.ResourceManager temp = 
     new global::System.Resources.ResourceManager(
          "ProblemAssembly.Controls.Properties.Stuff", typeof(Stuff).Assembly);

Hope this helps the next person.

Adding an identity to an existing column

As I understood in normal cases we are creating a table with Primary key which is having Identity property
So Rename or Delete a column which is associated with Primary Key constraint will not be possible because constraint Rules are validating column structure.
Tto achieve this we have to process some steps in the following way:
Let us assume TableName = 'Employee' and ColumnName = 'EmployeeId'

1. Add new column 'EmployeeId_new' in the 'Employee' table
ALTER TABLE Employee ADD EmployeeId_new INT IDENTITY(1,1)

  1. Now remove column 'EmployeeId' from 'Employee' table
    ALTER TABLE Employee DROP COLUMN EmployeeId

  2. This will throw error because of Primary Key Constraint rules are applicable and validating column structure.
    *### 'Msg 5074, Level 16, State 1, Line 1 The object [PK_dbo.Employee] is dependent on colmn [EmployeeId].'###

  3. So we have to remove the Primary Key constraint first from the table 'Employee' then we can remove the column
    ALTER TABLE Employee DROP constraint [PK_dbo.Employee]

  4. Now we can remove the column 'EmployeeId' from 'Employee' table as did in the previous step where we got error
    ALTER TABLE Employee DROP COLUMN EmployeeId

  5. Now Column 'EmployeeId' removed from table So we will Rename the newly added new column 'EmployeeId_new' with 'EmployeeId'
    sp_rename 'Employee.EmployeeId', 'EmployeeId_new', 'COLUMN'

  6. To rearrange the table in the same form as It was, we have to add Primary Key Constraint for the column 'EmployeeId'
    ALTER TABLE Employee add constraint [PK_dbo.Employee] primary key (EmployeeId)

8. Now the table 'Employee' with 'EmployeeId' is modified for Identity rules along with existing primary key constraint

How are parameters sent in an HTTP POST request?

The values are sent in the request body, in the format that the content type specifies.

Usually the content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string:

parameter=value&also=another

When you use a file upload in the form, you use the multipart/form-data encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.

How to set an image as a background for Frame in Swing GUI of java?

Here is another quick approach without using additional panel.

JFrame f = new JFrame("stackoverflow") { 
  private Image backgroundImage = ImageIO.read(new File("background.jpg"));
  public void paint( Graphics g ) { 
    super.paint(g);
    g.drawImage(backgroundImage, 0, 0, null);
  }
};

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I had the exact same problem.

[ERROR] Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5: Failure to find org.apache.maven.plugins:maven-resources-plugin:pom:2.5 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
...

Had maven 3.0.5, eclipse Kepler with JBoss Dev Studio 7 installed. Computer sitting on internal network with proxy to the internet. Here's what I did.

0. Check the maven repositiory server is up

1. Check Proxy is set up and working

First I thought it was a proxy problem, I made sure that maven settings.xml contained the proxy settings (settings.xml can exist in two places one in MAVEN_HOME. The other in %userprofile%.m2\ with the later having higher precedence):

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>optional-proxyuser</username>
  <password>optional-proxypass</password>
  <host>proxy.host.net</host>
  <port>80</port>
  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

and checked that the proxy is working by trying to telnet to it:

telnet [proxy] [port number]

2. Check not Eclipse Issue

ran 'mvn compile' at command line level outside of eclipse - same issue.

If 'mvn compile' worked. But it doesn't work using the maven plugin in eclipse, see Maven plugin not using eclipse's proxy settings

3. Check not Cache Issue Deleted all contents in my local maven repository. (Default location: ~/.m2/repository) And then reran maven - same issue came up.

4. What worked for me

Automatically download & install missing plugin: By declaring the missing plugin in the POM file build section for pluginManagement Maven will automatically retrieve the required plugin. In the POM file, add this code for the version of the plugin you require:

  <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>2.7</version>
            </plugin>           
          </plugins>
        </pluginManagement>   
    </build>

Manually install missing plugin: I went to http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin/2.5 and downloaded maven-resources-plugin-2.5.jar and maven-resources-plugin-2.5.pom . Copied it directly into the maven repository into the correct folder ( ~/.m2/repository/org/apache/maven/plugins/maven-resources-plugin/2.5) and reran 'mvn compile'. This solved the problem.


Edit1

Following this I had another two problem with 'mvn install':

The POM for org.apache.maven.plugins:maven-surefire-plugin:jar:2.10 is missing, no dependency information available

The POM for org.apache.maven.plugins:maven-install-plugin:jar:2.3.1 is missing, no dependency information available

I approached this problem the same way as above, downloading from http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin/2.10 and http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-install-plugin/2.3.1

How do you run a single query through mysql from the command line?

From the mysql man page:

   You can execute SQL statements in a script file (batch file) like this:

       shell> mysql db_name < script.sql > output.tab

Put the query in script.sql and run it.

Calculate execution time of a SQL query?

Why are you doing it in SQL? Admittedly that does show a "true" query time as opposed to the query time + time taken to shuffle data each way across the network, but it's polluting your database code. I doubt that your users will care - in fact, they'd probably rather include the network time, as it all contributes to the time taken for them to see the page.

Why not do the timing in your web application code? Aside from anything else, that means that for cases where you don't want to do any timing, but you want to execute the same proc, you don't need to mess around with something you don't need.

Convert StreamReader to byte[]

You can use this code: You shouldn't use this code:

byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());

Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.

How do you update Xcode on OSX to the latest version?

You can try mas-cli (Mac Apple Store cli). Github project here

It would be

$ brew install mas
$ mas list
$ mas search Xcode
$ mas install <id> 

$ mas upgrade <id>

upd:

Had issues installing Xcode 12.2 in Big Sur. Solved them by entering into the App Store from the devs link.

https://developer.apple.com/download/release/

.NET String.Format() to add commas in thousands place for a number

Below is a good solution in Java though!

NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(n));

or for a more robust way you may want to get the locale of a particular place, then use as below:

int n=9999999;
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(n));

US Locale OUTPUT: $9,999,999.00

German Locale output

Locale locale = new Locale("de", "DE");

OUTPUT: 9.999.999,00 €

Indian Locale output

Locale locale = new Locale("de", "DE");

OUTPUT: Rs.9,999,999.00

Estonian Locale output

Locale locale = new Locale("et", "EE");

OUTPUT: 9 999 999 €

As you can see in different outputs you don't have to worry about the separator being a comma or dot or even space you can get the number formatted according to the i18n standards

Returning string from C function

Your pointer is pointing to local variable of the function. So as soon as you return from the function, memory gets deallocated. You have to assign memory on heap in order to use it in other functions.

Instead char *rtnPtr = word;

do this char *rtnPtr = malloc(length);

So that it is available in the main function. After it is used free the memory.

NSCameraUsageDescription in iOS 10.0 runtime crash?

Alternatively open Info.plist as source code and add this:

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

how to parse JSONArray in android

Here is a better way for doing it. Hope this helps

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

Server unable to read htaccess file, denying access to be safe

"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess file are world-readable.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Count the number of all words in a string

The solution 7 does not give the correct result in the case there's just one word. You should not just count the elements in gregexpr's result (which is -1 if there where not matches) but count the elements > 0.

Ergo:

sapply(gregexpr("\\W+", str1), function(x) sum(x>0) ) + 1 

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

@property retain, assign, copy, nonatomic in Objective-C

After reading many articles I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak= unsafe_unretained
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

  1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

@property (retain) NSString *name;

@synthesize name;
  1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

Explain:

Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

  1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
  1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

  1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
  1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
  1. unsafe_unretained

    -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
  1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

How to remove extension from string (only real extension!)

This works when there is multiple parts to an extension and is both short and efficient:

function removeExt($path)
{
    $basename = basename($path);
    return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}

echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

The best and the safest way to show a 'ProgressDialog' in an AsyncTask, avoiding memory leak problem is to use a 'Handler' with Looper.main().

    private ProgressDialog tProgressDialog;

then in the 'onCreate'

    tProgressDialog = new ProgressDialog(this);
    tProgressDialog.setMessage(getString(R.string.loading));
    tProgressDialog.setIndeterminate(true);

Now you r done with the setup part. Now call 'showProgress()' and 'hideProgress()' in AsyncTask.

    private void showProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.show();
            }
        }.sendEmptyMessage(1);
    }

    private void hideProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.dismiss();
            }
        }.sendEmptyMessage(1);
    }

How to store NULL values in datetime fields in MySQL?

MySQL does allow NULL values for datetime fields. I just tested it:

mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL       | 
+------------+
1 row in set (0.00 sec)

I'm using this version:

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45    | 
+-----------+
1 row in set (0.03 sec)

EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''), not null. An empty string is different than null and is not a valid datetime value which is why you are getting that error message. You must pass the special sql keyword null if that's what you mean. Also, don't put any quotes around the word null. See my insert statement above for an example of how to insert null.

EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1] type when binding a null. See the answer to this stackoverflow question on how to properly insert null using PDO.

How to get a value from the last inserted row?

See the API docs for java.sql.Statement.

Basically, when you call executeUpdate() or executeQuery(), use the Statement.RETURN_GENERATED_KEYS constant. You can then call getGeneratedKeys to get the auto-generated keys of all rows created by that execution. (Assuming your JDBC driver provides it.)

It goes something along the lines of this:

Statement stmt = conn.createStatement();
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keyset = stmt.getGeneratedKeys();

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

This error comes when you are trying to load jasper report file with the extension .jasper
For Example 
c://reports//EmployeeReport.jasper"

While you should load jasper report file with the extension .jrxml
For Example 
c://reports//EmployeeReport.jrxml"
[See Problem Screenshot ][1] [1]: https://i.stack.imgur.com/D5SzR.png
[See Solution Screenshot][2] [2]: https://i.stack.imgur.com/VeQb9.png

  
  

Java image resize, maintain aspect ratio

public class ImageTransformation {

public static final String PNG = "png";

public static byte[] resize(FileItem fileItem, int width, int height) {

    try {
        ResampleOp resampleOp = new ResampleOp(width, height);
        BufferedImage scaledImage = resampleOp.filter(ImageIO.read(fileItem.getInputStream()), null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, PNG, baos);

        return baos.toByteArray();
    } catch (Exception ex) {
        throw new MapsException("An error occured during image resizing.", ex);
    }

}

public static byte[] resizeAdjustMax(FileItem fileItem, int maxWidth, int maxHeight) {

    try {
        BufferedInputStream bis = new BufferedInputStream(fileItem.getInputStream());  
        BufferedImage bufimg = ImageIO.read(bis);   

        //check size of image 
        int img_width = bufimg.getWidth();
        int img_height = bufimg.getHeight();
        if(img_width > maxWidth || img_height > maxHeight) {
            float factx = (float) img_width / maxWidth;
            float facty = (float) img_height / maxHeight;
            float fact = (factx>facty) ? factx : facty;
            img_width = (int) ((int) img_width / fact);
            img_height = (int) ((int) img_height / fact);
        }

        return resize(fileItem,img_width, img_height);

    } catch (Exception ex) {
        throw new MapsException("An error occured during image resizing.", ex);
    }

}

}

How to make a countdown timer in Android?

public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

How do you fade in/out a background color using jquery?

Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'}) to change the color.

As others have written, some of this can be done using the jQuery UI library as well.

CSV API for Java

For the last enterprise application I worked on that needed to handle a notable amount of CSV -- a couple of months ago -- I used SuperCSV at sourceforge and found it simple, robust and problem-free.

Create a dictionary with list comprehension

To add onto @fortran's answer, if you want to iterate over a list of keys key_list as well as a list of values value_list:

d = dict((key, value) for (key, value) in zip(key_list, value_list))

or

d = {(key, value) for (key, value) in zip(key_list, value_list)}

What is the difference between jQuery: text() and html() ?

((please update if necessary, this answer is a Wiki))

Sub-question: when only text, what is faster, .text() or .html()?

Answer: .html() is faster! See here a "behaviour test-kit" for all the question.

So, in conclusion, if you have "only a text", use html() method.

Note: Doesn't make sense? Remember that the .html() function is only a wrapper to .innerHTML, but in the .text() function jQuery adds an "entity filter", and this filter naturally consumes time.


Ok, if you really want performance... Use pure Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

  • jQuery's .html() is ~2x faster than .text().
  • pure JS' .innerHTML is ~3x faster than .html().
  • pure JS' .nodeValue is ~50x faster than .html(), ~100x than .text(), and ~20x than .innerHTML.

PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

See this complete benchmark:

// Using jQuery:
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").html('BENCHMARK WORK');
var ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    $("#work").text('BENCHMARK WORK');
alert("JQuery (3000x): \nhtml="+ht+"\ntext="+simplecron.duration());

// Using pure JavaScript only:
simplecron.restart(); for (var i=1; i<3000; i++)
    document.getElementById('work').innerHTML = 'BENCHMARK WORK';
ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++) 
    document.getElementById('work').nodeValue = 'BENCHMARK WORK';
alert("Pure JS (3000x):\ninnerHTML="+ht+"\nnodeValue="+simplecron.duration());

How to do a join in linq to sql with method syntax?

To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:

public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
    using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
    {
        var result = entityFrameworkObjectContext.SomeClass
            .Join(entityFrameworkObjectContext.SomeOtherClass,
                sc => sc.property1,
                soc => soc.property2,
                (sc, soc) => new {sc, soc})
            .Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
            .Select(s => new ThirdNonEntityClass 
            {
                dataValue1 = s.sc.dataValueA,
                dataValue2 = s.soc.dataValueB
            })
            .ToList();
    }

    return result;

}    

Pay special attention to the intermediate object that is created in the Where and Select clauses.

Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.

I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.

Get viewport/window height in ReactJS

I've just edited QoP's current answer to support SSR and use it with Next.js (React 16.8.0+):

/hooks/useWindowDimensions.js:

import { useState, useEffect } from 'react';

export default function useWindowDimensions() {

  const hasWindow = typeof window !== 'undefined';

  function getWindowDimensions() {
    const width = hasWindow ? window.innerWidth : null;
    const height = hasWindow ? window.innerHeight : null;
    return {
      width,
      height,
    };
  }

  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    if (hasWindow) {
      function handleResize() {
        setWindowDimensions(getWindowDimensions());
      }

      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }
  }, [hasWindow]);

  return windowDimensions;
}

/yourComponent.js:

import useWindowDimensions from './hooks/useWindowDimensions';

const Component = () => {
  const { height, width } = useWindowDimensions();
  /* you can also use default values or alias to use only one prop: */
  // const { height: windowHeight = 480 } useWindowDimensions();

  return (
    <div>
      width: {width} ~ height: {height}
    </div>
  );
}

Cannot execute script: Insufficient memory to continue the execution of the program

Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.

You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.

Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.

Convert generic List/Enumerable to DataTable?

Se probó el método para que acepte campos con null.

// remove "this" if not on C# 3.0 / .NET 3.5
    public static DataTable ToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection props =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        Type Propiedad = null;
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            Propiedad = prop.PropertyType;
            if (Propiedad.IsGenericType && Propiedad.GetGenericTypeDefinition() == typeof(Nullable<>)) 
            {
                Propiedad = Nullable.GetUnderlyingType(Propiedad);
            }
            table.Columns.Add(prop.Name, Propiedad);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;
    }

js window.open then print()

What worked for me was adding myWindow.document.close() after myWindow.document.write(). Here's my solution with a timeout to wait for the new window to finish loading (if you have a lot to load):

var win = window.open('', 'PrintWindow');
win.document.write('Stuff to print...');

setTimeout(function () {
    win.document.close();
    win.focus();
    win.print();
    win.close(); 
}, 1000);

How to make tesseract to recognize only numbers, when they are mixed with letters?

This feature is not supported in version 4. You can still use it via -c tessedit_char_whitelist=0123456789 with "--oem 0" which reverts to the old model.

There is a bounty to fix this issue.

Possible workarounds:

As stated by @amitdo

How to add a class to a given element?

You can use the classList.add OR classList.remove method to add/remove a class from a element.

var nameElem = document.getElementById("name")
nameElem.classList.add("anyclss")

The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.

nameElem.classList.remove("anyclss")

How to get a responsive button in bootstrap 3

I know this already has a marked answer, but I feel I have an improvement to it.

The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.

One thing not mentioned here, is that the words may break in the middle of a word and look messed up.

My solution, forces the break to happen between words, a nice word wrap.

.btn-responsive {
    white-space: normal !important;
    word-wrap: break-word;
}

<a href="#" class="btn btn-primary btn-responsive">Click Here</a>

how to convert current date to YYYY-MM-DD format with angular 2

Solution in ES6/TypeScript:

let d = new Date;
console.log(d, [`${d.getFullYear()}`, `0${d.getMonth()}`.substr(-2), `0${d.getDate()}`.substr(-2)].join("-"));

How to monitor SQL Server table changes by using c#?

Use SqlTableDependency. It is a c# component raising events when a record is changes. You can find others detail at: https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency

It is similat to .NET SqlDependency except that SqlTableDependency raise events containing modified / deleted or updated database table values:

string conString = "data source=.;initial catalog=myDB;integrated security=True";

using(var tableDependency = new SqlTableDependency<Customers>(conString))
{
    tableDependency.OnChanged += TableDependency_Changed;
    tableDependency.Start();

    Console.WriteLine("Waiting for receiving notifications...");
    Console.WriteLine("Press a key to stop");
    Console.ReadKey();
}
...
...
void TableDependency_Changed(object sender, RecordChangedEventArgs<Customers> e)
{
    if (e.ChangeType != ChangeType.None)
    {
        var changedEntity = e.Entity;
        Console.WriteLine("DML operation: " + e.ChangeType);
        Console.WriteLine("ID: " + changedEntity.Id);
        Console.WriteLine("Name: " + changedEntity.Name);
        Console.WriteLine("Surname: " + changedEntity.Surname);
    }
}

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

Referencing another schema in Mongoose

Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing

http://mongoosejs.com/docs/populate.html

Collapse all methods in Visual Studio Code

  • Fold All:

    • Windows: Ctrl + K + 0
    • Mac: ? + K + 0
  • Unfold All:

    • Windows: Ctrl + K + J
    • Mac: ? + K + J

To see all available shortcuts in the editor:

  • Windows: Ctrl + K + S
  • Mac: ? + K + S

Screenshot of Visual Studio keyboard shortcuts

All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts

Numpy where function multiple conditions

One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.

When we use 'and':

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)

Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When we use Ampersand(&):

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)

Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')

And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.

UPDATE

A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.

Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".

Case1:

np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)

Since there are no brackets here, the bitwise operator(&) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, & is given precedence over < or > operators. Here's the table from from lowest precedence to highest precedence.

enter image description here

It's not even performing the < and > operation and being asked to perform a logical AND operation. So that's why it gives that error.

One can check out the following link to learn more about: operator precedence

Now to Case 2:

If you do use the bracket, you clearly see what happens.

np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False,  True,  True,  True, False,  True, False,  True])) & (array([ True,  True,  True, False,  True,  True,  True, False])), 'yo', ar)

Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:

np.where( array([False,  True,  True, False, False,  True, False, False]),  'yo', ar)

And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).

That's all. I hope I explained the query well.

Git Push Error: insufficient permission for adding an object to repository database

This can easily happen if you ran git init with a different user from the one you are planning to use when pushing changes.

If you blindly follow the instructions on [1] this will happen as you probably created the git-user as root and then immediately moved on to git init without changing user in between.

[1] http://git-scm.com/book/en/Git-on-the-Server-Setting-Up-the-Server

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

While ln -s is the obvious easiest fix, a piece of explanation:

Because of a conflict with another package, the executable from the Ubuntu repositories is called nodejs instead of node. Keep this in mind as you are running software.

This advice comes up, when installing sudo apt-get install nodejs.

So some other known tool (I don't know what it does. While being known to ubuntu repositories, it is not installed by default in 16.04) occupies that namespace.

Would have been nice, if Ubuntu had offered an advice how to fix this 'cleanly', if not by doing by hand what otherwise the package would do. (a collision remains a collision... if+when it would occur)

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise

Checking if a website is up via Python

If server if down, on python 2.7 x86 windows urllib have no timeout and program go to dead lock. So use urllib2

import urllib2
import socket

def check_url( url, timeout=5 ):
    try:
        return urllib2.urlopen(url,timeout=timeout).getcode() == 200
    except urllib2.URLError as e:
        return False
    except socket.timeout as e:
        print False


print check_url("http://google.fr")  #True 
print check_url("http://notexist.kc") #False     

Back button and refreshing previous activity

private Cursor getAllFavorites() {
    return mDb.query(DocsDsctnContract.DocsDsctnEntry.Description_Table_Name,
            null,
            null,
            null,
            null,
            null,
            DocsDsctnContract.DocsDsctnEntry.COLUMN_Timest);
}
@Override
public void onResume()
{  // After a pause OR at startup
    super.onResume();
    mAdapter.swapCursor(getAllFavorites());
    mAdapter.notifyDataSetChanged();

}

public void swapCursor(Cursor newCursor){
    if (mCursor!=null) mCursor.close();
    mCursor = newCursor;
    if (newCursor != null){
        mAdapter.notifyDataSetChanged();
    }
}

I just have favorites category so when i click to the item from favorites there appear such information and if i unlike it - this item should be deleted from Favorites : for that i refresh database and set it to adapter(for recyclerview)[I wish you will understand my problem & solution]

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

PHP Unset Session Variable

Unset is a function. Therefore you have to submit which variable has to be destroyed.

unset($var);

In your case

unset ($_SESSION["products"]);

If you need to reset whole session variable just call

session_destroy ();

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

PyPI packages not in the standard library:

  • virtualenv is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I'll be making comparisons to it for the rest of this answer.

    It works by installing a bunch of files in a directory (eg: env/), and then modifying the PATH environment variable to prefix it with a custom bin directory (eg: env/bin/). An exact copy of the python or python3 binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip.

  • pyenv is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the PATH environment variable with ~/.pyenv/shims, where there are special files matching the Python commands (python, pip). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION environment variable, or the .python-version file, or the ~/.pyenv/version file. pyenv also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install.

  • pyenv-virtualenv is a plugin for pyenv by the same author as pyenv, to allow you to use pyenv and virtualenv at the same time conveniently. However, if you're using Python 3.3 or later, pyenv-virtualenv will try to run python -m venv if it is available, instead of virtualenv. You can use virtualenv and pyenv together without pyenv-virtualenv, if you don't want the convenience features.

  • virtualenvwrapper is a set of extensions to virtualenv (see docs). It gives you commands like mkvirtualenv, lssitepackages, and especially workon for switching between different virtualenv directories. This tool is especially useful if you want multiple virtualenv directories.

  • pyenv-virtualenvwrapper is a plugin for pyenv by the same author as pyenv, to conveniently integrate virtualenvwrapper into pyenv.

  • pipenv aims to combine Pipfile, pip and virtualenv into one command on the command-line. The virtualenv directory typically gets placed in ~/.local/share/virtualenvs/XXX, with XXX being a hash of the path of the project directory. This is different from virtualenv, where the directory is typically in the current working directory. pipenv is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv, such as poetry, which I won't list here since this question is only about the packages that are similarly named.

Standard library:

  • pyvenv is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv.

  • venv is a package shipped with Python 3, which you can run using python3 -m venv (although for some reason some distros separate it out into a separate distro package, such as python3-venv on Ubuntu/Debian). It serves the same purpose as virtualenv, but only has a subset of its features (see a comparison here). virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.

Recommendation for beginners:

This is my personal recommendation for beginners: start by learning virtualenv and pip, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.

Java : Cannot format given Object as a Date

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

How to detect Ctrl+V, Ctrl+C using JavaScript?

Live Demo : http://jsfiddle.net/abdennour/ba54W/

$(document).ready(function() {

    $("#textA").bind({
        copy : function(){
            $('span').text('copy behaviour detected!');
        },
        paste : function(){
            $('span').text('paste behaviour detected!');
        },
        cut : function(){
            $('span').text('cut behaviour detected!');
        }
    });

}); 

How to correctly set Http Request Header in Angular 2

We can do it nicely using Interceptors. You dont have to set options in all your services neither manage all your error responses, just define 2 interceptors (one to do something before sending the request to server and one to do something before sending the server's response to your service)

  1. Define an AuthInterceptor class to do something before sending the request to the server. You can set the api token (retrieve it from localStorage, see step 4) and other options in this class.
  2. Define an responseInterceptor class to do something before sending the server response to your service (httpClient). You can manage your server response, the most comon use is to check if the user's token is valid (if not clear token from localStorage and redirect to login).
  3. In your app.module import HTTP_INTERCEPTORS from '@angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.

  4. At login http response (use http service), save the token at localStorage.

  5. Then use httpClient for all your apirest services.

You can check some good practices on my github proyect here

enter image description here

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

What is the best open source help ticket system?

There is good information on Wikipedia at

Comparison of Issue Tracking Systems

Personally, I'm fond of Trac, which has the capability of integrating with subversion, so when you check in a file, if you say something like...

$ svn ci -m "automatically fix any broken dates in the input.  fixes #87"

....then Trac will automatically add this comment and close bug #87 for you.

Java Desktop application: SWT vs. Swing

Pros Swing:

  • part of java library, no need for additional native libraries
  • works the same way on all platforms
  • Integrated GUI Editor in Netbeans and Eclipse
  • good online tutorials by Sun/Oracle
  • Supported by official java extensions (like java OpenGL)

Cons Swing:

  • Native look and feel may behave different from the real native system.
  • heavy components (native/awt) hide swing components, not a problem most of the time as as use of heavy components is rather rare

Pros SWT:

  • uses native elements when possible, so always native behavior
  • supported by eclipse, gui editor VEP (VEP also supports Swing and AWT)
  • large number of examples online
  • has an integrated awt/swt bridge to allow use of awt and swing components

Cons SWT:

  • requires native libraries for each supported system
  • may not support every behavior on all systems because of native resources used (hint options)
  • managing native resources, while native components will often be disposed with their parent other resources such as Fonts have to be manually released or registered as dispose listener to a component for automatic release.

Get only filename from url in php without any variable values which exist in the url

Try the following code:

For PHP 5.4.0 and above:

$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);

For PHP Version < 5.4.0

$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);

Open images? Python

Open any file

import os
os.startfile(<filepath>)

Uploading/Displaying Images in MVC 4

Have a look at the following

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

your controller should have action method which would accept HttpPostedFileBase;

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

Update 1

In case you want to upload files using jQuery with asynchornously, then try this article.

the code to handle the server side (for multiple upload) is;

 try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

Returning unique_ptr from functions

I would like to mention one case where you must use std::move() otherwise it will give an error. Case: If the return type of the function differs from the type of the local variable.

class Base { ... };
class Derived : public Base { ... };
...
std::unique_ptr<Base> Foo() {
     std::unique_ptr<Derived> derived(new Derived());
     return std::move(derived); //std::move() must
}

Reference: https://www.chromium.org/developers/smart-pointer-guidelines

Using :: in C++

The :: are used to dereference scopes.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated: cout and cin are not functions, but instances of stream objects.

EDIT fixed as Keine Lust suggested

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Splitting applicationContext to multiple files

Mike Nereson has this to say on his blog at:

http://blog.codehangover.com/load-multiple-contexts-into-spring/

There are a couple of ways to do this.

1. web.xml contextConfigLocation

Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value>
          applicationContext1.xml
          applicationContext2.xml
      </param-value>
  </context-param>

  <listener>
      <listener-class>
          org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>

The above uses carriage returns. Alternatively, yo could just put in a space.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value> applicationContext1.xml applicationContext2.xml </param-value>
  </context-param>

  <listener>
      <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
  </listener>

2. applicationContext.xml import resource

Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.

In applicationContext.xml you might have…

  <!-- hibernate configuration and mappings -->
  <import resource="applicationContext-hibernate.xml"/>

  <!-- ldap -->
  <import resource="applicationContext-ldap.xml"/>

  <!-- aspects -->
  <import resource="applicationContext-aspects.xml"/>

Which strategy should you use?

1. I always prefer to load up via web.xml.

Because , this allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.

2. If you are loading contexts into a non-web application, I would use the import resource.

Turn off warnings and errors on PHP and MySQL

PHP error_reporting reference:

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

How to drop all tables from the database with manage.py CLI in Django?

python manage.py migrate <app> zero

sqlclear was removed from 1.9.

Release notes mention that it is due to the introduction of migrations: https://docs.djangoproject.com/en/1.9/releases/1.9/

Unfortunately I could not find a method that works on all apps at once, nor a built-in way to list all installed apps from the admin: How to list all installed apps with manage.py in Django?

Related: How to reset migrations in Django 1.7?

How to get last month/year in java?

Your solution is here but instead of addition you need to use subtraction

c.add(Calendar.MONTH, -1);

Then you can call getter on the Calendar to acquire proper fields

int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year  = c.get(Calendar.YEAR);

COALESCE with Hive SQL

From Language DDL & UDF of Hive

NVL(value, default value) 

Returns default value if value is null else returns value

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Is it because some culture format issue?

Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.

How can I make sure the result string is delimited by colon instead of dot?

I'd suggest specifying CultureInfo.InvariantCulture:

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

Alternatively, you could just quote the time and date separators:

string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");

... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()        
    {
        DateTime now = DateTime.Now;
        CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
        Thread.CurrentThread.CurrentCulture = culture;
        Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
    }
} 

That produces output (on September 18th 2013) of:

11/12/1434 15:04:31.750

My guess is that your web service would be surprised by that!

I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:

string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)

iText - add content to existing PDF file

This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.

Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.

I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).

Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.

<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%

response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );  

// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());

// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields 
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );

// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
    background = stamperDoc.getUnderContent(i);
    background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close(); 
%>

There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.

// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();

Understanding .get() method in Python

I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.

from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
    letter_counter[letter] += 1

>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.

As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.

JavaScript validation for empty input field

Customizing the input message using HTML validation when clicking on Javascript button

_x000D_
_x000D_
function msgAlert() {
  const nameUser = document.querySelector('#nameUser');
  const passUser = document.querySelector('#passUser');

  if (nameUser.value === ''){
    console.log('Input name empty!');
    nameUser.setCustomValidity('Insert a name!');
  } else {
    nameUser.setCustomValidity('');
    console.log('Input name ' + nameUser.value);
  }
}

const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
_x000D_
.container{display:flex;max-width:960px;}
.w-auto {
    width: auto!important;
}
.p-3 {
    padding: 1rem!important;
}
.align-items-center {
    -ms-flex-align: center!important;
    align-items: center!important;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.d-flex {
    display: -ms-flexbox!important;
    display: flex!important;
}
.d-inline-block {
    display: inline-block!important;
}
.col {
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
    -ms-flex-positive: 1;
    flex-grow: 1;
    max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
    margin-right: .5rem!important;
}
label {
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    color: #007081;
    font-weight: 400;
    letter-spacing: 1px;
    text-transform: uppercase;
}
label {
    display: inline-block;
    margin-bottom: .5rem;
}
.x-input {
    background-color: #eaf3f8;
    font-family: "Montserrat", sans-serif;
    font-size: 14px;
}
.login-input {
    border: none !important;
    width: 100%;
}
.p-4 {
    padding: 1.5rem!important;
}
.form-control {
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
    overflow: visible;
    margin: 0;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
    padding-right: 5px;
    padding-left: 5px;
}
.col-lg-12 {
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.mt-1, .my-1 {
    margin-top: .25rem!important;
}
.mt-2, .my-2 {
    margin-top: .5rem!important;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
    cursor: pointer;
}
.btn-petroleo {
    background-color: #007081;
    color: white;
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    padding: 8px 30px;
    letter-spacing: 2px;
}
.btn-xg {
    padding: 20px 100px;
    width: 100%;
    display: block;
}
.btn {
    display: inline-block;
    font-weight: 400;
    color: #212529;
    text-align: center;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
    -webkit-writing-mode: horizontal-tb !important;
    text-rendering: auto;
    color: -internal-light-dark(black, white);
    letter-spacing: normal;
    word-spacing: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
    display: inline-block;
    text-align: start;
    appearance: textfield;
    background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
    -webkit-rtl-ordering: logical;
    cursor: text;
    margin: 0em;
    font: 400 13.3333px Arial;
    padding: 1px 2px;
    border-width: 2px;
    border-style: inset;
    border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
    border-image: initial;
}
_x000D_
<div class="container">
              <form name="myFormLogin" class="w-auto p-3 mw-10">
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="nameUser">Usuário</label><br>
                    <input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
                           name="nameUser" placeholder="Name" required>
                  </div>
                </div>
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="passUser">Senha</label><br>
                    <input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
                           name="passUser" placeholder="Password" required>
                    <div class="help">Esqueci meu usuário ou senha</div>
                  </div>
                </div>
                <div class="form-row d-flex align-items-center">
                  <div class="col-lg-12 my-1 mt-2 mb-2">
                    <button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
                  </div>
                </div>
                <div class="form-row align-items-center d-flex">
                  <div class="col-lg-12 my-1">
                    <div class="nova-conta">Ainda não é cadastrado? <a href="">Crie seu acesso</a></div>
                  </div>
                </div>
              </form>
            </div>
_x000D_
_x000D_
_x000D_

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

Since your integer array cannot contain a value larger than Integer.MAX_VALUE and smaller than Integer.MIN_VALUE your code works across all edge cases.

Generate sql insert script from excel worksheet

Depending on the database, you can export to CSV and then use an import method.

MySQL - http://dev.mysql.com/doc/refman/5.1/en/load-data.html

PostgreSQL - http://www.postgresql.org/docs/8.2/static/sql-copy.html

How to parse XML to R data frame

You can try the code below:

# Load the packages required to read XML files.
library("XML")
library("methods")

# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)

Creating a Zoom Effect on an image on hover using CSS?

Add jQuery JavaScript library together with the jquery.zbox.css and jquery.zbox.js to your webpage.

<link rel="stylesheet" href="jquery.zbox.css">
<script src="jquery.min.js"></script>
<script src="jquery.zbox.min.js"></script>

Add a group of thumbnails with links pointing to the full sized images into the webpage.

<a class="zb" rel="group" href="1.png" title="Image 1">
  <img src="thumb1.png">
</a>
<a class="zb" rel="group" href="2.png" title="Image 2">
  <img src="thumb2.png">
</a>
<a class="zb" rel="group" href="3.png" title="Image 3">
 <img src="thumb3.png">
</a>

Call the function on document ready. That's it.

In the view source do:

$(".zb").zbox();

What is App.config in C#.NET? How to use it?

Just adding one more point

Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below ConfigurationSettings.AppSettings["Key"]

Decimal or numeric values in regular expression validation

Here is my regex for validating numbers:

^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$

Valid numbers:

String []validNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};

Invalid numbers:

String []invalidNumbers={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};

How can I tell jaxb / Maven to generate multiple schema packages?

I had to specify different generateDirectory (without this, the plugin was considering that files were up to date and wasn't generating anything during the second execution). And I recommend to follow the target/generated-sources/<tool> convention for generated sources so that they will be imported in your favorite IDE automatically. I also recommend to declare several execution instead of declaring the plugin twice (and to move the configuration inside each execution element):

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.1</version>
  <executions>
    <execution>
      <id>schema1-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir1</schemaDirectory>
        <schemaIncludes>
          <include>shiporder.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package1</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc1</generateDirectory>
      </configuration>
    </execution>
    <execution>
      <id>schema2-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir2</schemaDirectory>
        <schemaIncludes>
          <include>books.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package2</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc2</generateDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

With this setup, I get the following result after a mvn clean compile

$ tree target/
target/
+-- classes
¦   +-- com
¦   ¦   +-- stackoverflow
¦   ¦       +-- App.class
¦   ¦       +-- package1
¦   ¦       ¦   +-- ObjectFactory.class
¦   ¦       ¦   +-- Shiporder.class
¦   ¦       ¦   +-- Shiporder$Item.class
¦   ¦       ¦   +-- Shiporder$Shipto.class
¦   ¦       +-- package2
¦   ¦           +-- BookForm.class
¦   ¦           +-- BooksForm.class
¦   ¦           +-- ObjectFactory.class
¦   ¦           +-- package-info.class
¦   +-- dir1
¦   ¦   +-- shiporder.xsd
¦   +-- dir2
¦       +-- books.xsd
+-- generated-sources
    +-- xjc
    ¦   +-- META-INF
    ¦       +-- sun-jaxb.episode
    +-- xjc1
    ¦   +-- com
    ¦       +-- stackoverflow
    ¦           +-- package1
    ¦               +-- ObjectFactory.java
    ¦               +-- Shiporder.java
    +-- xjc2
        +-- com
            +-- stackoverflow
                +-- package2
                    +-- BookForm.java
                    +-- BooksForm.java
                    +-- ObjectFactory.java
                    +-- package-info.java

Which seems to be the expected result.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Use a.any() or a.all()

If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False

Removing elements by class name?

Using jQuery (which you really could be using in this case, I think), you could do this like so:

$('.column').remove();

Otherwise, you're going to need to use the parent of each element to remove it:

element.parentNode.removeChild(element);

What exceptions should be thrown for invalid or unexpected parameters in .NET?

argument exception.

  • System.ArgumentException
  • System.ArgumentNullException
  • System.ArgumentOutOfRangeException

JSON Array iteration in Android/Java

I have done it two different ways,

1.) make a Map

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i=0; i<settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) make a JSONArray of names

    JSONArray names = json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i=0; i<values.length(); i++){
        if (names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if (names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if (names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if (names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if (names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if (names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }

Put icon inside input element in a form

.icon{
background: url(1.jpg) no-repeat;
padding-left:25px;
}

add above tags into your CSS file and use the specified class.

In c++ what does a tilde "~" before a function name signify?

As others have noted, in the instance you are asking about it is the destructor for class Stack.

But taking your question exactly as it appears in the title:

In c++ what does a tilde “~” before a function name signify?

there is another situation. In any context except immediately before the name of a class (which is the destructor context), ~ is the one's complement (or bitwise not) operator. To be sure it does not come up very often, but you can imagine a case like

if (~getMask()) { ...

which looks similar, but has a very different meaning.

What does %s and %d mean in printf in the C language?

% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers

No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.

Consider defining a bean of type 'service' in your configuration [Spring boot]

@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})

In the main class below springbootapplication annotation i have written componentscan and it worked for me.

Install numpy on python3.3 - Install pip for python3

The normal way to install Python libraries is with pip. Your way of installing it for Python 3.2 works because it's the system Python, and that's the way to install things for system-provided Pythons on Debian-based systems.

If your Python 3.3 is system-provided, you should probably use a similar command. Otherwise you should probably use pip.

I took my Python 3.3 installation, created a virtualenv and run pip install in it, and that seems to have worked as expected:

$ virtualenv-3.3 testenv
$ cd testenv
$ bin/pip install numpy
blablabl

$ bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> 

LOAD DATA INFILE Error Code : 13

This is normally a file access permissions issue but I see your already addressing that in point b, but it's worth going over just in case. Another option is to use LOAD DATA LOCAL INFILE which gets past a lot of these issues of file access permissions. To use this method though you need to copy the file locally (in the mysql folder is best) first. •If LOCAL is specified, the file is read by the client program on the client host and sent to the server.

Insufficient Directory Permissions

The error in this example has resulted because the file you are trying to import is not in a directory which is readable by the user the MySql server is running as. Note that all the parent directories of the directory the is in need to be readable by the MySql user for this to work. Saving the file to /tmp will usually work as this is usually readable (and writable) by all users. The error code number is 13. Source

EDIT:

Remember you will need permissions on not just the folder the holds the file but also the upper directories.

Example from this post on the MySql Forums.

If your file was contained within the following strucutre: /tmp/imports/site1/data.file

you would need (I think, 755 worked) r+x for 'other' on these directories:

/tmp

/tmp/imports

As well as the main two:

/tmp/imports/site1

/tmp/imports/site1/data.file

You need the file and directory to be world-readable. Apologies if you've already tried this method but it may be worth retracing your steps, never hurts to double check.

What is an ORM, how does it work, and how should I use one?

Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)

How do I check if an index exists on a table field in MySQL?

Try use this:

SELECT TRUE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_SCHEMA = "{DB_NAME}" 
AND TABLE_NAME = "{DB_TABLE}"
AND COLUMN_NAME = "{DB_INDEXED_FIELD}";

mysql-python install error: Cannot open include file 'config-win.h'

Assume you want to install package MySQL-python on Windows, maybe try pip install command with --global-option. See the example command below:

pip install MySQL-python ^
 --force-reinstall --no-cache-dir ^
 --global-option=build_ext ^
 --global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
 --global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
 --verbose

For this example, I fully installed 64-bit version of MySQL Connector C in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\.

By the way, I noticed that pip install MySQL-python by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.

Hope the above might be of some help.

Getting ssh to execute a command in the background on target machine

I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on nohup, copied here for your convenience.

Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams:

nohup myprogram > foo.out 2> foo.err < /dev/null &

Differences between Oracle JDK and OpenJDK

A key difference going forward is the release schedule and support policy.

OpenJDK

OpenJDK will have a feature release every 6 months which is only supported until the next feature release. It's essentially a continuous stream of releases targeted to developers.

Oracle JDK

The Oracle JDK is targeted more towards an enterprise audience which values stability. It's based on one of the OpenJDK releases but is then given long term support (LTS). The Oracle JDK has releases planned every 3 years.

enter image description here

Source: https://www.oracle.com/java/java9-screencasts.html?bcid=5582439790001&playerType=single-social&size=events

java: run a function after a specific number of seconds

As a variation of @tangens answer: if you can't wait for the garbage collector to clean up your thread, cancel the timer at the end of your run method.

Timer t = new java.util.Timer();
t.schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
                // close the thread
                t.cancel();
            }
        }, 
        5000 
);

How to emit an event from parent to child?

Using RxJs, you can declare a Subject in your parent component and pass it as Observable to child component, child component just need to subscribe to this Observable.

Parent-Component

eventsSubject: Subject<void> = new Subject<void>();

emitEventToChild() {
  this.eventsSubject.next();
}

Parent-HTML

<child [events]="eventsSubject.asObservable()"> </child>    

Child-Component

private eventsSubscription: Subscription;

@Input() events: Observable<void>;

ngOnInit(){
  this.eventsSubscription = this.events.subscribe(() => doSomething());
}

ngOnDestroy() {
  this.eventsSubscription.unsubscribe();
}

How to add property to object in PHP >= 5.3 strict mode without generating error

I don't know whether its the newer version of php, but this works. I'm using php 5.6

    <?php
    class Person
    {
       public $name;

       public function save()
       {
          print_r($this);
       }
    }

   $p = new Person;
   $p->name = "Ganga";
   $p->age = 23;

   $p->save();

This is the result. The save method actually gets the new property

    Person Object
    (
       [name] => Ganga
       [age] => 23
    )

Python math module

import math #imports math module

import math as m
print(m.sqrt(25))

from math import sqrt #imports a method from math module
print(sqrt(25))

from math import sqrt as s
print(s(25))

from math import *
print(sqrt(25))

Convert hex to binary

Here's a fairly raw way to do it using bit fiddling to generate the binary strings.

The key bit to understand is:

(n & (1 << i)) and 1

Which will generate either a 0 or 1 if the i'th bit of n is set.


import binascii

def byte_to_binary(n):
    return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8)))

def hex_to_binary(h):
    return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h))

print hex_to_binary('abc123efff')

>>> 1010101111000001001000111110111111111111

Edit: using the "new" ternary operator this:

(n & (1 << i)) and 1

Would become:

1 if n & (1 << i) or 0

(Which TBH I'm not sure how readable that is)

How do I align views at the bottom of the screen?

In a ScrollView this doesn't work, as the RelativeLayout would then overlap whatever is in the ScrollView at the bottom of the page.

I fixed it using a dynamically stretching FrameLayout :

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" 
    android:layout_width="match_parent"
    android:fillViewport="true">
    <LinearLayout 
        android:id="@+id/LinearLayout01"
        android:layout_width="match_parent" 
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical">

                <!-- content goes here -->

                <!-- stretching frame layout, using layout_weight -->
        <FrameLayout
            android:layout_width="match_parent" 
            android:layout_height="0dp"
            android:layout_weight="1">
        </FrameLayout>

                <!-- content fixated to the bottom of the screen -->
        <LinearLayout 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                                   <!-- your bottom content -->
        </LinearLayout>
    </LinearLayout>
</ScrollView>

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.