Programs & Examples On #Vb5

How to make a .jar out from an Android Studio project

If you set up the code as a plain Java module in Gradle, then it's really easy to have Gradle give you a jar file with the contents. That jar file will have only your code, not the other Apache libraries it depends on. I'd recommend distributing it this way; it's a little weird to bundle dependencies inside your library, and it's more normal for users of those libraries to have to include those dependencies on their own (because otherwise there are collisions of those projects are already linking copies of the library, perhaps of different versions). What's more, you avoid potential licensing problems around redistributing other people's code if you were to publish your library.

Take the code that also needs to be compiled to a jar, and move it to a separate plain Java module in Android Studio:

  1. File menu > New Module... > Java Library
  2. Set up the library, Java package name, and class names in the wizard. (If you don't want it to create a class for you, you can just delete it once the module is created)
  3. In your Android code, set up a dependency on the new module so it can use the code in your new library:
  4. File > Project Structure > Modules > (your Android Module) > Dependencies > + > Module dependency. See the screenshot below: enter image description here
  5. Choose your module from the list in the dialog that comes up: enter image description here

Hopefully your project should be building normally now. After you do a build, a jar file for your Java library will be placed in the build/libs directory in your module's directory. If you want to build the jar file by hand, you can run its jar build file task from the Gradle window: enter image description here

Twitter Bootstrap Datepicker within modal window

Try to change z-index value for .modal and .modal-backdrop less than .datepicker z-index value.

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

Difference between webdriver.Dispose(), .Close() and .Quit()

quit(): Quits this driver, closing every associated window that was open.

close() : Close the current window, quitting the browser if it's the last window currently open.

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

Render HTML to PDF in Django site

If you have context data along with css and js in your html template. Than you have good option to use pdfjs.

In your code you can use like this.

from django.template.loader import get_template
import pdfkit
from django.conf import settings

context={....}
template = get_template('reports/products.html')
html_string = template.render(context)
pdfkit.from_string(html_string, os.path.join(settings.BASE_DIR, "media", 'products_report-%s.pdf'%(id)))

In your HTML you can link extranal or internal css and js, it will generate best quality of pdf.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

What is difference between XML Schema and DTD?

From the Differences Between DTDs and Schema section of the Converting a DTD into a Schema article:

The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.

The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, "terseness in XML markup is of minimal importance," there is no real concern with keeping the syntax brief.

[...]

So what are some of the other differences which might be especially important when we are converting a DTD? Let's take a look.

Typing

The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it's such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, "XML Schema Datatypes."

[...]

Occurrence Constraints

Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, "Schema Structure" (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.

[...]

Enumerations

So, let's say we had a element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:

<!ELEMENT item (shirt)>
<!ELEMENT shirt (#PCDATA)>
<!ATTLIST shirt
    size_value (small | medium | large)>

[...]

But what if we wanted size to be an element? We can't do that with a DTD. DTDs do not provide for enumerations in an element's text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created a simpleType called size_values which we can now use with an element:

<xs:element name="size" type="size_value">

[...]

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

What is the format specifier for unsigned short int?

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

ISO/IEC 9899:201x - 7.21.6.1-7

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.

nodejs - first argument must be a string or Buffer - when using response.write with http.request

I get this error message and it mentions options.body

I had this originally

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: {
        email: req.user.email
    }
});

I changed it to this:

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: JSON.stringify({
        email: req.user.email
    })
});

and it seems to work now without the error message...seems like bug though.

I think this is the more official way to do it:

 request.post({
        url: apiServerBaseUrl + '/v1/verify',
        json: true,
        body: {
            email: req.user.email
        }
    });

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

How to set a Default Route (To an Area) in MVC

ummm, I don't know why all this programming, I think the original problem is solved easily by specifying this default route ...

routes.MapRoute("Default", "{*id}", 
                 new { controller = "Home"
                     , action = "Index"
                     , id = UrlParameter.Optional 
                     }
              );

How to allow <input type="file"> to accept only image files?

Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type

For HTML and javascript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }   
    }
</script>
</body>
</html>

Explanation:

  1. The accept attribute filters the files that will be displayed in the file chooser popup. However, it is not a validation. It is only a hint to the browser. The user can still change the options in the popup.
  2. The javascript only validates for file extension, but cannot really verify if the select file is an actual jpg or png.
  3. So you have to write for file content validation on server side.

How can I find where I will be redirected using cURL?

To make cURL follow a redirect, use:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Erm... I don't think you're actually executing the curl... Try:

curl_exec($ch);

...after setting the options, and before the curl_getinfo() call.

EDIT: If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
}

How do I get the web page contents from a WebView?

I managed to get this working using the code from @jluckyiv's answer but I had to add in @JavascriptInterface annotation to the processHTML method in the MyJavaScriptInterface.

class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    @JavascriptInterface
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

Transform DateTime into simple Date in Ruby on Rails

For old Ruby (1.8.x):

myDate = Date.parse(myDateTime.to_s)

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Upgrade Node.js to the latest version on Mac OS

for latest release: nvm install node

specific version: nvm install 6.14.4

https://github.com/creationix/nvm

How to install latest version of git on CentOS 7.x/6.x

You can use WANDisco's CentOS repository to install Git 2.x: for CentOS 6, for CentOS 7

  1. Install WANDisco repo package:

    yum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
    
  2. Install the latest version of Git 2.x:

    yum install git
    
  3. Verify the version of Git that was installed:

    git --version
    

As of 02 Mar. 2020, the latest available version from WANDisco is 2.22.0.

jQuery: Can I call delay() between addClass() and such?

I know this this is a very old post but I've combined a few of the answers into a jQuery wrapper function that supports chaining. Hope it benefits someone:

$.fn.queueAddClass = function(className) {
    this.queue('fx', function(next) {
        $(this).addClass(className);
        next();
    });
    return this;
};

And here's a removeClass wrapper:

$.fn.queueRemoveClass = function(className) {
    this.queue('fx', function(next) {
        $(this).removeClass(className);
        next();
    });
    return this;
};

Now you can do stuff like this - wait 1sec, add .error, wait 3secs, remove .error:

$('#div').delay(1000).queueAddClass('error').delay(2000).queueRemoveClass('error');

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

How to create a .NET DateTime from ISO 8601 format

DateTime.ParseExact(...) allows you to tell the parser what each character represents.

Which command do I use to generate the build of a Vue app?

I think you've created your project like this:

vue init webpack myproject

Well, now you can run

npm run build

Copy index.html and /dist/ folder into your website root directory. Done.

What exactly are DLL files, and how do they work?

http://support.microsoft.com/kb/815065

A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Therefore, each program can use the functionality that is contained in this DLL to implement an Open dialog box. This helps promote code reuse and efficient memory usage.

By using a DLL, a program can be modularized into separate components. For example, an accounting program may be sold by module. Each module can be loaded into the main program at run time if that module is installed. Because the modules are separate, the load time of the program is faster, and a module is only loaded when that functionality is requested.

Additionally, updates are easier to apply to each module without affecting other parts of the program. For example, you may have a payroll program, and the tax rates change each year. When these changes are isolated to a DLL, you can apply an update without needing to build or install the whole program again.

http://en.wikipedia.org/wiki/Dynamic-link_library

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

How many values can be represented with n bits?

A better way to solve it is to start small.

Let's start with 1 bit. Which can either be 1 or 0. That's 2 values, or 10 in binary.

Now 2 bits, which can either be 00, 01, 10 or 11 That's 4 values, or 100 in binary... See the pattern?

How to combine two vectors into a data frame

While this does not answer the question asked, it answers a related question that many people have had:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

df <- data.frame(x,y)
names(df) <- c(x_name,y_name)
print(df)

  cond rating
1    1    100
2    2    200
3    3    300

How can I make my match non greedy in vim?

G'day,

Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.

I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.

Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).

Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.

HTH

cheers,

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

Just wanted to add -- apparently this can also be caused by installing Instant Client for 10, then realizing you want the full install and installing it again in a parallel directory. I don't know why this broke it.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Prevent BODY from scrolling when a modal is opened

Bootstrap's modal automatically adds the class modal-open to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS:

body.modal-open {
    overflow: hidden;
}

You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site.

Update 8th feb, 2013
This has now stopped working in Twitter Bootstrap v. 2.3.0 -- they no longer add the modal-open class to the body.

A workaround would be to add the class to the body when the modal is about to be shown, and remove it when the modal is closed:

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});

Update 11th march, 2013 Looks like the modal-open class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll:

Reintroduces .modal-open on the body (so we can nuke the scroll there)

See this: https://github.com/twitter/bootstrap/pull/6342 - look at the Modal section.

Unit testing private methods in C#

Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...

In other words...

No, first things first.

Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.

Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.

In this case, the usual suspects are: OCP, SRP, and, as always, KIS.

But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.

What am I talking about?

private double TranslateMeasurementIntoLinear(double actualMeasurement);

It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.

To make this fairy tale short: We need a simple way to test private methods--without ado.

First: Happy new year everyone!

Second: Rehearse your architect lessons.

Third: The "public" modifier is religion, not a solution.

How to provide user name and password when connecting to a network share

For VB.lovers the VB.NET equivalent of Luke Quinane's code (thanks Luke!)

Imports System
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel

Public Class NetworkConnection
    Implements IDisposable

    Private _networkName As String

    Public Sub New(networkName As String, credentials As NetworkCredential)
        _networkName = networkName

        Dim netResource = New NetResource() With {
             .Scope = ResourceScope.GlobalNetwork,
             .ResourceType = ResourceType.Disk,
             .DisplayType = ResourceDisplaytype.Share,
             .RemoteName = networkName
        }

        Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format("{0}\{1}", credentials.Domain, credentials.UserName))

        Dim result = WNetAddConnection2(NetResource, credentials.Password, userName, 0)

        If result <> 0 Then
            Throw New Win32Exception(result, "Error connecting to remote share")
        End If
    End Sub

    Protected Overrides Sub Finalize()
        Try
            Dispose (False)
        Finally
            MyBase.Finalize()
        End Try
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose (True)
        GC.SuppressFinalize (Me)
    End Sub

    Protected Overridable Sub Dispose(disposing As Boolean)
        WNetCancelConnection2(_networkName, 0, True)
    End Sub

    <DllImport("mpr.dll")> _
    Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer
    End Function

    <DllImport("mpr.dll")> _
    Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer
    End Function

End Class

<StructLayout(LayoutKind.Sequential)> _
Public Class NetResource
    Public Scope As ResourceScope
    Public ResourceType As ResourceType
    Public DisplayType As ResourceDisplaytype
    Public Usage As Integer
    Public LocalName As String
    Public RemoteName As String
    Public Comment As String
    Public Provider As String
End Class

Public Enum ResourceScope As Integer
    Connected = 1
    GlobalNetwork
    Remembered
    Recent
    Context
End Enum

Public Enum ResourceType As Integer
    Any = 0
    Disk = 1
    Print = 2
    Reserved = 8
End Enum

Public Enum ResourceDisplaytype As Integer
    Generic = &H0
    Domain = &H1
    Server = &H2
    Share = &H3
    File = &H4
    Group = &H5
    Network = &H6
    Root = &H7
    Shareadmin = &H8
    Directory = &H9
    Tree = &HA
    Ndscontainer = &HB
End Enum

IIS w3svc error

Make sure these 2 services running and their startup type is automatic.If they disabled and not running right click on them and go to properties and change from there.

  1. Windows process activation service
  2. Worldwide web publishing service.

Create two blank lines in Markdown

I only know the options below. It would be great to take a list of all of them and comment them differences

# RAW
## Creates 2 Lines that CAN be selected as text
## -------------------------------------------------
### The non-breaking space ASCII character
&nbsp;
&nbsp;

### HTML <(br)/> tag
<br />
<br />

## Creates 2 Lines that CANNOT be selected as text
## -------------------------------------------------
### HTML Entity &NewLine;
&NewLine;
&NewLine;

### Backticks with a space inside followed by two spaces
`(space)`(space)(space)
`(space)`(space)(space)
#### sample:
` `  
` `

# End

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How to disable all div content

similar to cletu's solution, but i got an error using that solution, this is the workaround:

$('div *').prop('disabled',true);
// or
$('#the_div_id *').prop('disabled',true);

works fine on me

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

How do I redirect users after submit button click?

I hope this might be helpful

_x000D_
_x000D_
<script type="text/javascript">_x000D_
 function redirect() {_x000D_
  document.getElementById("formid").submit();_x000D_
 }_x000D_
 window.onload = redirect;_x000D_
</script>
_x000D_
<form id="formid" method="post" action="anypage.jsp">_x000D_
  ........._x000D_
</form>
_x000D_
_x000D_
_x000D_

Getting Django admin url for an object

I solved this by changing the expression to:

reverse( 'django-admin', args=["%s/%s/%s/" % (app_label, model_name, object_id)] )

This requires/assumes that the root url conf has a name for the "admin" url handler, mainly that name is "django-admin",

i.e. in the root url conf:

url(r'^admin/(.*)', admin.site.root, name='django-admin'),

It seems to be working, but I'm not sure of its cleanness.

Reverse order of foreach list items

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

How to check whether the user uploaded a file in PHP?

@karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.

/**
 * Tests all upload fields to determine whether any files were submitted.
 * 
 * @return boolean
 */
function files_uploaded() {

    // bail if there were no upload forms
   if(empty($_FILES))
        return false;

    // check for uploaded files
    $files = $_FILES['files']['tmp_name'];
    foreach( $files as $field_title => $temp_name ){
        if( !empty($temp_name) && is_uploaded_file( $temp_name )){
            // found one!
            return true;
        }
    }   
    // return false if no files were found
   return false;
}

C# convert int to string with padding zeros?

Simply

int i=123;
string paddedI = i.ToString("D4");

support FragmentPagerAdapter holds reference to old fragments

I solved the problem by saving the fragments in SparceArray:

public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {

    SparseArray<Fragment> fragments = new SparseArray<>();

    public SaveFragmentsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragments.append(position, fragment);
        return fragment;
    }

    @Nullable
    public Fragment getFragmentByPosition(int position){
        return fragments.get(position);
    }

}

jQuery removeClass wildcard

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

Python - Convert a bytes array into JSON format

To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.

dumps(s.decode()).replace("'", '"')[1:-1]

Div width 100% minus fixed amount of pixels

In some contexts, you can leverage margin settings to effectively specify "100% width minus N pixels". See the accepted answer to this question.

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

Convert string to a variable name

assign is what you are looking for.

assign("x", 5)

x
[1] 5

but buyer beware.

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

AngularJS: How to run additional code after AngularJS has rendered a template?

I came with a pretty simple solution. I'm not sure whether it is the correct way to do it but it works in a practical sense. Let's directly watch what we want to be rendered. For example in a directive that includes some ng-repeats, I would watch out for the length of text (you may have other things!) of paragraphs or the whole html. The directive will be like this:

.directive('myDirective', [function () {
    'use strict';
    return {

        link: function (scope, element, attrs) {
            scope.$watch(function(){
               var whole_p_length = 0;
               var ps = element.find('p');
                for (var i=0;i<ps.length;i++){
                    if (ps[i].innerHTML == undefined){
                        continue
                    }
                    whole_p_length+= ps[i].innerHTML.length;
                }
                //it could be this too:  whole_p_length = element[0].innerHTML.length; but my test showed that the above method is a bit faster
                console.log(whole_p_length);
                return whole_p_length;
            }, function (value) {   
                //Code you want to be run after rendering changes
            });
        }
}]);

NOTE that the code actually runs after rendering changes rather complete rendering. But I guess in most cases you can handle the situations whenever rendering changes happen. Also you could think of comparing this ps length (or any other measure) with your model if you want to run your code only once after rendering completed. I appreciate any thoughts/comments on this.

Inline Form nested within Horizontal Form in Bootstrap 3

To make it work in Chrome (and bootply) i had to change code in this way:

<form class="form-horizontal">
  <div class="form-group">
    <label for="name" class="col-xs-2 control-label">Name</label>
    <div class="col-xs-10">
      <input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
    </div>
  </div>

  <div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
      <div class="form-inline">
        <input type="text" class="form-control" placeholder="year" />
        <input type="text" class="form-control" placeholder="month" />
        <input type="text" class="form-control" placeholder="day" />
      </div>
    </div>
  </div>
</form>

MySQL equivalent of DECODE function in Oracle

The example translates directly to:

Select Name, CASE Age
       WHEN 13 then 'Thirteen' WHEN 14 then 'Fourteen' WHEN 15 then 'Fifteen' WHEN 16 then 'Sixteen'
       WHEN 17 then 'Seventeen' WHEN 18 then 'Eighteen' WHEN 19 then 'Nineteen'
       ELSE 'Adult' END AS AgeBracket
FROM Person

which you may prefer to format e.g. like this:

Select Name,
       CASE Age
         when 13 then 'Thirteen'
         when 14 then 'Fourteen'
         when 15 then 'Fifteen'
         when 16 then 'Sixteen'
         when 17 then 'Seventeen'
         when 18 then 'Eighteen'
         when 19 then 'Nineteen'
         else         'Adult'
       END AS AgeBracket
FROM Person

jQuery get the rendered height of an element?

NON JQUERY since there were a bunch of links using elem.style.height in the top of these answers...

INNER HEIGHT:
https://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight

document.getElementById(id_attribute_value).clientHeight;

OUTER HEIGHT:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetHeight

document.getElementById(id_attribute_value).offsetHeight; 

Or one of my favorite references: http://youmightnotneedjquery.com/

How to prevent a double-click using jQuery?

"Easy Peasy"

$(function() {
     $('.targetClass').dblclick(false);
});

How do you get the index of the current iteration of a foreach loop?

C# 7 finally gives us an elegant way to do this:

static class Extensions
{
    public static IEnumerable<(int, T)> Enumerate<T>(
        this IEnumerable<T> input,
        int start = 0
    )
    {
        int i = start;
        foreach (var t in input)
        {
            yield return (i++, t);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var s = new string[]
        {
            "Alpha",
            "Bravo",
            "Charlie",
            "Delta"
        };

        foreach (var (i, t) in s.Enumerate())
        {
            Console.WriteLine($"{i}: {t}");
        }
    }
}

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

I need to learn Web Services in Java. What are the different types in it?

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

React Native - Image Require Module using Dynamic Names

import React, { Component } from 'react';
import { Image } from 'react-native';

class Images extends Component {
  constructor(props) {
    super(props);
    this.state = {
           images: {
                './assets/RetailerLogo/1.jpg': require('../../../assets/RetailerLogo/1.jpg'),
                './assets/RetailerLogo/2.jpg': require('../../../assets/RetailerLogo/2.jpg'),
                './assets/RetailerLogo/3.jpg': require('../../../assets/RetailerLogo/3.jpg')
            }
    }
  }

  render() {
    const {  images } = this.state 
    return (
      <View>
        <Image
                            resizeMode="contain"
                            source={ images['assets/RetailerLogo/1.jpg'] }
                            style={styles.itemImg}
                        />
     </View>
  )}
}

Python Anaconda - How to Safely Uninstall

If you're uninstalling Anaconda to be able to use the base Python installation in the system, you could temporarily disable the path by following these steps and not uninstalling Anaconda.

Go to your home directory. Just a cd command will do.

Edit the file .bashrc.

Look for something like export PATH="/home/ubuntu/anaconda3/bin:$PATH" in the file.

Put a # at the beginning to comment it from the script.

#export PATH="/home/ubuntu/anaconda3/bin:$PATH"

Open a new terminal and you should be running the base python installation. This works on Linux systems. Should work on Mac too.

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.

This app won't run unless you update Google Play Services (via Bazaar)

I'm answering this question for the second time, because the solution I've tried that didn't work at first now works, and I can recreate the steps to make it work :)

I also had a feeling that lack of Google Play Store is a culprit here, so I've tried to install Google Play Store to the emulator by advice on this link and this link combined. I've had some difficulties, but at the end I've succeeded in installing Google Play Store and tested it by downloading some random app. But the maps activity kept displaying the message with the "Update" button. That button would take me to the store, but there I would get a message about "item not found" and maps still didn't work. At that point I gave up.

Yesterday, I've fired up the same test app by accident and it worked! I was very confused, but quickly I've made a diff from the emulator where it's working and new clean one and I've determined two apps on the working one in /data/app/ directory: com.android.vending-1.apk and com.google.android.gms-1.apk. This is strange since, when I were installing Google Play Store by instructions from those sites, I was pushing Phonesky.apk, GoogleServicesFramework.apk and GoogleLoginService.apk and to a different folder /system/app.

Anyway, now the Android Google Maps API v2 is working on my emulator. These are the steps to do this:


Create a new emulator

  • For device, choose "5.1'' WVGA (480 x 800: mdpi)"
  • For target, choose "Android 4.1.2 - API level 16"
  • For "CPU/ABI", choose "ARM"
  • Leave the rest to defaults

These are the settings that are working for me. I don't know for different ones.


Start the emulator


install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command


Google Maps should work now in your emulator.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

What is the difference between encrypting and signing in asymmetric encryption?

In your scenario, you do not encrypt in the meaning of asymmetric encryption; I'd rather call it "encode".

So you encode your data into some binary representation, then you sign with your private key. If you cannot verify the signature via your public key, you know that the signed data is not generated with your private key. ("verification" meaning that the unsigned data is not meaningful)

Passing data into "router-outlet" child components

Yes, you can set inputs of components displayed via router outlets. Sadly, you have to do it programmatically, as mentioned in other answers. There's a big caveat to that when observables are involved (described below).

Here's how:

(1) Hook up to the router-outlet's activate event in the parent template:

<router-outlet (activate)="onOutletLoaded($event)"></router-outlet>

(2) Switch to the parent's typescript file and set the child component's inputs programmatically each time they are activated:

onOutletLoaded(component) {
    component.node = 'someValue';
} 

Done.

However, the above version of onOutletLoaded is simplified for clarity. It only works if you can guarantee all child components have the exact same inputs you are assigning. If you have components with different inputs, use type guards:

onChildLoaded(component: MyComponent1 | MyComponent2) {
  if (component instanceof MyComponent1) {
    component.someInput = 123;
  } else if (component instanceof MyComponent2) {
    component.anotherInput = 456;
  }
}

Why may this method be preferred over the service method?

Neither this method nor the service method are "the right way" to communicate with child components (both methods step away from pure template binding), so you just have to decide which way feels more appropriate for the project.

This method, however, avoids the tight coupling associated with the "create a service for communication" approach (i.e., the parent needs the service, and the children all need the service, making the children unusable elsewhere). Decoupling is usually preferred.

In many cases this method also feels closer to the "angular way" because you can continue passing data to your child components through @Inputs (thats the decoupling part - this enables re-use elsewhere). It's also a good fit for already existing or third-party components that you don't want to or can't tightly couple with your service.

On the other hand, it may feel less like the angular way when...

Caveat

The caveat with this method is that since you are passing data in the typescript file, you no longer have the option of using the pipe-async pattern used in templates (e.g. {{ myObservable$ | async }}) to automagically use and pass on your observable data to child components.

Instead, you'll need to set up something to get the current observable values whenever the onChildLoaded function is called. This will likely also require some teardown in the parent component's onDestroy function. This is nothing too unusual, there are often cases where this needs to be done, such as when using an observable that doesn't even get to the template.

Convert serial.read() into a useable string using Arduino?

From Help with Serial.Read() getting string:

char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
       if(index < 19) // One less than the size of the array
       {
           inChar = Serial.read(); // Read a character
           inData[index] = inChar; // Store it
           index++; // Increment where to write next
           inData[index] = '\0'; // Null terminate the string
       }
    }

    if (strcmp(inData,This)  == 0) {
       for (int i=0;i<19;i++) {
            inData[i]=0;
       }
       index=0;
       return(0);
    }
    else {
       return(1);
    }
}

void loop()
{
    if (Comp("m1 on")==0) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")==0) {
       Serial.write("Motor 1 -> Offline\n");
    }
}

How to find out the server IP address (using JavaScript) that the browser is connected to?

Fairly certain this cannot be done. However you could use your preferred server-side language to print the server's IP to the client, and then use it however you like. For example, in PHP:

<script type="text/javascript">
    var ip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
    alert(ip);
</script>

This depends on your server's security setup though - some may block this.

Windows batch: formatted date into variable

If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:

FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C

I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.

SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%

While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.

Is there Java HashMap equivalent in PHP?

$fruits = array (
    "fruits"  => array("a" => "Orange", "b" => "Banana", "c" => "Apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);

echo $fruits["fruits"]["b"]

outputs 'Banana'

taken from http://in2.php.net/manual/en/function.array.php

How to check if a file exists before creating a new file

you can also use Boost.

 boost::filesystem::exists( filename );

it works for files and folders.

And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

You can match those three groups separately, and make sure that they all present. Also, [^\w] seems a bit too broad, but if that's what you want you might want to replace it with \W.

How do I change the default schema in sql developer?

I don't know of any way doing this in SQL Developer. You can see all the other schemas and their objects (if you have the correct privileges) when looking in "Other Users" -> "< Schemaname >".

In your case, either use the method described above or create a new connection for the schema in which you want to work or create synonyms for all the tables you wish to access.

If you would work in SQL*Plus, issuing ALTER SESSION SET CURRENT_SCHEMA=MY_NAME would set your current schema (This is probably what your DBA means).

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Open the key file in Notepad++ and verify the encoding. If it says UTF-8-BOM then change it to UTF-8. Save the file and try again.

Git:nothing added to commit but untracked files present

Please Follow this process

First of all install git bash and create a repository on git

1) Go to working directory where the file exist which you want to push on remote and create .git folder by

$ git init

2) Add the files in your new local repository.

$ git add .

Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity

3) Commit the files that you've staged in your local repository.

$ git commit -m "First commit"**

4) after this go to git repository and copy remote URL

$ git remote add origin *remote repository URL

5)

$ git remote -v

Note: this will ask for user.email and user.name just put it as per config

6)

$ git push origin master

this will push whole committed code to FILE.git on repository

And I think we done

How do you get the process ID of a program in Unix or Linux using Python?

For Windows

A Way to get all the pids of programs on your computer without downloading any modules:

import os

pids = []
a = os.popen("tasklist").readlines()
for x in a:
      try:
         pids.append(int(x[29:34]))
      except:
           pass
for each in pids:
         print(each)

If you just wanted one program or all programs with the same name and you wanted to kill the process or something:

import os, sys, win32api

tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()

print(tasklistr)

def kill(process):
     process_exists_forsure = False
     gotpid = False
     for examine in tasklistrl:
            if process == examine[0:len(process)]:
                process_exists_forsure = True
     if process_exists_forsure:
         print("That process exists.")
     else:
        print("That process does not exist.")
        raw_input()
        sys.exit()
     for getpid in tasklistrl:
         if process == getpid[0:len(process)]:
                pid = int(getpid[29:34])
                gotpid = True
                try:
                  handle = win32api.OpenProcess(1, False, pid)
                  win32api.TerminateProcess(handle, 0)
                  win32api.CloseHandle(handle)
                  print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
                except win32api.error as err:
                  print(err)
                  raw_input()
                  sys.exit()
    if not gotpid:
       print("Could not get process pid.")
       raw_input()
       sys.exit()

   raw_input()
   sys.exit()

prompt = raw_input("Which process would you like to kill? ")
kill(prompt)

That was just a paste of my process kill program I could make it a whole lot better but it is okay.

Connect Device to Mac localhost Server?

also, make sure the server is listening for ur mobile device! for example, by default jekyll only answers requests made by the host machine. this solved my problem:

Connect to a locally built Jekyll Server using mobile devices in the LAN

Unable to get spring boot to automatically create database schema

The configurations below worked for me:

spring.jpa.properties.javax.persistence.schema-generation.database.action=create
spring.jpa.properties.javax.persistence.schema-generation.create-database-schemas=true
spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.drop-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.connection=jdbc:mysql://localhost:3306/your_database

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Does MySQL foreign_key_checks affect the entire database?

In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0; does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17

"Fatal error: Cannot redeclare <function>"

I had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone. Maybe this will be helpful for someone.

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

annotation to make a private method public only for test classes

As much as I know there is no annotation like this. The best way is to use reflection as some of the others suggested. Look at this post:
How do I test a class that has private methods, fields or inner classes?

You should only watch out on testing the exception outcome of the method. For example: if u expect an IllegalArgumentException, but instead you'll get "null" (Class:java.lang.reflect.InvocationTargetException).
A colegue of mine proposed using the powermock framework for these situations, but I haven't tested it yet, so no idea what exactly it can do. Although I have used the Mockito framework that it is based upon and thats a good framework too (but I think doesn't solve the private method exception issue).

It's a great idea though having the @PublicForTests annotation.

Cheers!

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
         else:
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")


         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/Firefox.app %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/Safari.app %s")
         navigator.open_new(url)

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

How do I delete an item or object from an array using ng-click?

I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.

So, for instance, on your HTML...

<a class="btn" ng-remove-birthday="$index">Delete</a>

Then, create a directive...

angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
    return function(scope, element, attrs){
        angular.element(element.bind('click', function(){
            myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);  
        };       
    };
}])

Then in your service...

angular.module('myApp').factory('myService', [function(){
    return {
        removeBirthday: function(birthdayIndex, scope){
            scope.bdays.splice(birthdayIndex);
            scope.$apply();
        }
    };
}]);

When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.

For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.

Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)

Happy Developing!!!

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

CSS disable hover effect

To disable the hover effect, I've got two suggestions:

  • if your hover effect is triggered by JavaScript, just use $.unbind('hover');
  • if your hover style is triggered by class, then just use $.removeClass('hoverCssClass');

Using CSS !important to override CSS will make your CSS very unclean thus that method is not recommended. You can always duplicate a CSS style with different class name to keep the same styling.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I had the same problem when developing a KNIME Node/plugin in the Eclipse environment. The solution was not only to add the gson.jar as an externar JAR to the build path, it was also required to go to plugin.xml, then the Dependencies tab and add com.google.gson as a required plugin.

Search for all occurrences of a string in a mysql database

Not an elegant solution, but you could achieve it with a nested looping structure

// select tables from database and store in an array

// loop through the array
foreach table in database
{
    // select columns in the table and store in an array

    // loop through the array
    foreach column in table
    {
        // select * from table where column = url
    }
}

You could probably speed this up by checking which columns contain strings while building your column array, and also by combining all the columns per table in one giant, comma-separated WHERE clause.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

Use of alloc init instead of new

I am very late to this but I want to mention that that new is actually unsafe in the Obj-C with Swift world. Swift will only create a default init method if you do not create any other initializer. Calling new on a swift class with a custom initializer will cause a crash. If you use alloc/init then the compiler will properly complain that init does not exist.

Can I do a max(count(*)) in SQL?

     select top 1 yr,count(*)  from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = 'John Travolta'
group by yr order by 2 desc

How do I access (read, write) Google Sheets spreadsheets with Python?

Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

Sample example

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1

# Update a cell with value (just to let him know values is updated ;) )
wks.update_cell('A1', "Hey yank this numpy array")

# update the sheet with array
wks.update_cells('A2', my_nparray.to_list())

# share the sheet with your friend
sh.share("[email protected]")

See the docs here.

Author here.

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Pip - Fatal error in launcher: Unable to create process using '"'

For me it was an error in my path. You should directly call the script using the directory where it is stored.

C:\Users\YourUserName\AppData\Local\Programs\Python\Python36\Scripts\pip install requests

And for running python scripts you can do this:

C:\Users\Avanish\AppData\Local\Programs\Python\Python36\python -m pip install requests

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

How to watch and reload ts-node when TypeScript files change

add this to your package.json file

scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}

and to make this work you also need to install ts-node as dev-dependency

yarn add ts-node -D

run yarn dev to start the dev server

Get the name of a pandas DataFrame

In many situations, a custom attribute attached to a pd.DataFrame object is not necessary. In addition, note that pandas-object attributes may not serialize. So pickling will lose this data.

Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label'].

df = pd.DataFrame()

dfs = {'some_label': df}

Scroll to element on click in Angular 4

There is actually a pure javascript way to accomplish this without using setTimeout or requestAnimationFrame or jQuery.

In short, find the element in the scrollView that you want to scroll to, and use scrollIntoView.

el.scrollIntoView({behavior:"smooth"});

Here is a plunkr.

In Java how does one turn a String into a char or a char into a String?

I like to do something like this:

String oneLetter = "" + someChar;

Ruby: character to ascii from a string

puts "string".split('').map(&:ord).to_s

How to pass multiple values through command argument in Asp.net?

CommandArgument='<%#Eval("ScrapId").Tostring()+ Eval("UserId")%>
//added the comment function

How to set image to UIImage

You can't alloc UIImage, this is impossible. Proper code with UIImageView allocate:

UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;

Draw image:

CGContextDrawImage(context, rect, _image.image.CGImage);

Programmatically change the height and width of a UIImageView Xcode Swift

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)

How do I instantiate a JAXBElement<String> object?

Here is how I do it. You will need to get the namespace URL and the element name from your generated code.

new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
                new String("").getClass(),testDN);

GROUP BY having MAX date

Another way that doesn't use group by:

SELECT * FROM tblpm n 
  WHERE date_updated=(SELECT date_updated FROM tblpm n 
                        ORDER BY date_updated desc LIMIT 1)

How to get current time with jQuery

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
    function ShowLocalDate()
    {
    var dNow = new Date();
    var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
    $('#currentDate').text(localdate)
    }
</script>

</head>
<body>
    enter code here
    <h1>Get current local enter code here Date in JQuery</h1>
    <label id="currentDate">This is current local Date Time in JQuery</p>
    <button type="`enter code here button onclick="ShowLocalDate()">Show Local DateTime</button>

</body>
</html> 

you can get more information from below link

http://www.morgantechspace.com/2013/11/Get-current-Date-time-in-JQuery.html#GetLocalDateTimeinJQuery

Update .NET web service to use TLS 1.2

if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

How to uninstall with msiexec using product id guid without .msi file present

The good thing is, this one is really easily and deterministically to analyze: Either, the msi package is really not installed on the system or you're doing something wrong. Of course the correct call is:

msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

(Admin rights needed of course- With curly braces without any quotes here- quotes are only needed, if paths or values with blank are specified in the commandline.)
If the message is: "This action is only valid for products that are currently installed", then this is true. Either the package with this ProductCode is not installed or there is a typo.

To verify where the fault is:

  1. First try to right click on the (probably) installed .msi file itself. You will see (besides "Install" and "Repair") an Uninstall entry. Click on that.
    a) If that uninstall works, your msi has another ProductCode than you expect (maybe you have the wrong WiX source or your build has dynamic logging where the ProductCode changes).
    b) If that uninstall gives the same "...only valid for products already installed" the package is not installed (which is obviously a precondition to be able to uninstall it).

  2. If 1.a) was the case, you can look for the correct ProductCode of your package, if you open your msi file with Orca, Insted or another editor/tool. Just google for them. Look there in the table with the name "Property" and search for the string "ProductCode" in the first column. In the second column there is the correct value.

There are no other possibilities.

Just a suggestion for the used commandline: I would add at least the "/qb" for a simple progress bar or "/qn" parameter (the latter for complete silent uninstall, but makes only sense if you are sure it works).

How to log out user from web site using BASIC authentication?

Have the user click on a link to https://log:[email protected]/. That will overwrite existing credentials with invalid ones; logging them out.

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

Combining C++ and C - how does #ifdef __cplusplus work?

extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.

extern "C" blocks nest nicely. There's also extern "C++" if you find yourself hopelessly trapped inside of extern "C" regions, but it isn't such a good idea from a cleanliness perspective.

Now, specifically regarding your numbered questions:

Regarding #1: __cplusplus will stay defined inside of extern "C" blocks. This doesn't matter, though, since the blocks should nest neatly.

Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C -- hence the #ifdef __cplusplus checking.

To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C" block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.

For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C" the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic when you were looking for void h(int, char)

5: This sort of mixing is a common reason to use extern "C", and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

Tools for creating Class Diagrams

Some time ago I used DIA - free and platform-independent. It was ok. Now I use Enterprise Architect but it's not free.

.htaccess not working on localhost with XAMPP

Without seeing your system it's hard to tell what's wrong but try the following (comment answer if these didn't work WITH log error messages)

[STOP your Apache server instance. Ensure it's not running!]

1) move apache server/install to a folder that has no long file names and spaces

2) check httpd.conf in install\conf folder and look for AccessFileName. If it's .htaccess change it to a file name windows accepts (e.g. conf.htaccess)

3) double-check that your htaccess file gets read: add some uninterpretable garbage to it and start server: you should get an Error 500. If you don't, file is not getting read, re-visit httpd.conf file (if that looks OK, check if this is the only file which defines htaccess and it's location and it does at one place -within the file- only; also check if both httpd.conf and htaccess files are accessible: not encrypted, file access rights are not limited, drive/path available -and no long folder path and file names-)
STOP Apache again, then go on:
4) If you have IIS too on your system, stop it (uninstall it too if you can) from services.msc

5) Add the following to the top of your valid htaccess file:
RewriteEngine On
RewriteLog "/path/logs/rewrite.log" #make sure path is there!
RewriteLogLevel 9

6) Empty your [apache]\logs folder (if you use another folder, then that one :)

7) Check the following entries are set and correct:
Action application/x-httpd-php "c:/your-php5-path/php-cgi.exe"
LoadModule php5_module "c:/your-php5-path/php5apache2.dll"
LoadModule rewrite_module modules/mod_rewrite.so
Avoid long path names and spaces in folder names for phpX install too!

8) START apache server

You can do all the steps above or go one-by-one, your call. But at the end of the day make sure you tried everything above!
If system still blows up and you can't fix it, copy&paste error message(s) from log folder for further assistance

Code signing is required for product type 'Application' in SDK 'iOS5.1'

This error was caused, for me, by different circumstances. A downloaded project tutorial had a default setting of [Project]>Targets>Build Settings>Architectures>Build Active Architecture Only>Release = "Yes." I wasn't intending to build a release, so the solution was to set Release (which presumably requires not just a developer profile but distribution profile) to "No."

pandas dataframe groupby datetime month

One solution which avoids MultiIndex is to create a new datetime column setting day = 1. Then group by this column.

Normalise day of month

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

Then use groupby as normal:

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

Comparison with pd.Grouper

The subtle benefit of this solution is, unlike pd.Grouper, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group:

some_group = g.get_group('2017-10-01')

Calculating the last day of October is slightly more cumbersome. pd.Grouper, as of v0.23, does support a convention parameter, but this is only applicable for a PeriodIndex grouper.

Comparison with string conversion

An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX to string '2017-10'. However, this is not recommended since you lose all the efficiency benefits of a datetime series (stored internally as numerical data in a contiguous memory block) versus an object series of strings (stored as an array of pointers).

H2 in-memory database. Table not found

Had the exact same issue, tried all the above, but without success. The rather funny cause of the error was that the JVM started too fast, before the DB table was created (using a data.sql file in src.main.resources). So I've put a Thread.sleep(1000) timer to wait for just a second before calling "select * from person". Working flawlessly now.

application.properties:

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

data.sql:

create table person
(
id integer not null,
name varchar(255) not null,
location varchar(255),
birth_date timestamp,
primary key(id)
);

insert into person values (
10001, 'Tofu', 'home', sysdate()
);

PersonJdbcDAO.java:

    public List<Person> findAllPersons(){
    return jdbcTemplate.query("select * from person", 
        new BeanPropertyRowMapper<Person>(Person.class));
}

main class:

Thread.sleep(1000);
logger.info("All users -> {}", dao.findAllPersons());

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

jQuery SVG, why can't I addClass?

Just add the missing prototype constructor to all SVG nodes:

SVGElement.prototype.hasClass = function (className) {
  return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
};

SVGElement.prototype.addClass = function (className) { 
  if (!this.hasClass(className)) {
    this.setAttribute('class', this.getAttribute('class') + ' ' + className);
  }
};

SVGElement.prototype.removeClass = function (className) {
  var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
  if (this.hasClass(className)) {
    this.setAttribute('class', removedClass);
  }
};

You can then use it this way without requiring jQuery:

this.addClass('clicked');

this.removeClass('clicked');

All credit goes to Todd Moto.

How to safely call an async method in C# without await

If you really wants to do this. Just to address "Call an async method in C# without await", you can execute the async method inside a Task.Run. This approach will wait until MyAsyncMethod finish.

public string GetStringData()
{
    Task.Run(()=> MyAsyncMethod()).Result;
    return "hello world";
}

await asynchronously unwraps the Result of your task, whereas just using Result would block until the task had completed.

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

How to create materialized views in SQL Server?

You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.

An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.

In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.

First, a view. This should be easy for most since views are quite common in any database Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data. Then, a procedure that truncates the table, and reloads it based on the current data in the view. Finally, a job that triggers the procedure to start it's work.

Everything else is experimentation.

Best GUI designer for eclipse?

Another good GUI designer for Eclipse is Window Builder Pro. Like Jigloo, it's not free for commercial use.

It allows you to design user interfaces for Swing, SWT and even the Google Web Toolkit (GWT).

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

Set Colorbar Range in matplotlib

Using figure environment and .set_clim()

Could be easier and safer this alternative if you have multiple plots:

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))

fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end

plt.show()

enter image description here

A single colorbar

The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.

fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
                    wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)

enter image description here

P.S.

I would suggest using pcolormesh instead of pcolor because it is faster (more infos here ).

In Git, how do I figure out what my current revision is?

This gives you just the revision.

git rev-parse HEAD

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you are just visiting a webpage that you trust and you want to move forward fast, just:

1- Click the shield icon in the far right of the address bar.

Allow mixed content in Google Chrome

2- In the pop-up window, click "Load anyway" or "Load unsafe script" (depending on your Chrome version).


If you want to set your Chrome browser to ALWAYS(in all webpages) allow mixed content:

1- In an open Chrome browser, press Ctrl+Shift+Q on your keyboard to force close Chrome. Chrome must be fully closed before the next steps.

2- Right-click the Google Chrome desktop icon (or Start Menu link). Select Properties.

3- At the end of the existing information in the Target field, add: " --allow-running-insecure-content" (There is a space before the first dash.)

4- Click OK.

5- Open Chrome and try to launch the content that was blocked earlier. It should work now.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

It works for me...

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
    {
    $certCallback = @"
        using System;
        using System.Net;
        using System.Net.Security;
        using System.Security.Cryptography.X509Certificates;
        public class ServerCertificateValidationCallback
        {
            public static void Ignore()
            {
                if(ServicePointManager.ServerCertificateValidationCallback ==null)
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        }
    "@
        Add-Type $certCallback
     }
    [ServerCertificateValidationCallback]::Ignore()

Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

How to add jQuery code into HTML Page

I would recommend to call the script like this

...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>

The js and css files must be treat differently

Put jquery as the first before other JS scripts at the bottom of <BODY> tag

  • The problem caused is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname.
  • So select 2 (two) most important scripts on your page like analytic and pixel script on the <head> tags and let the rest including the jquery to be called on the bottom <body> tag.

Put CSS style on top of <HEAD> tag after the other more priority tags

  • Moving style sheets to the document HEAD makes pages appear to be loading faster. This is because putting style sheets in the HEAD allows the page to render progressively.
  • So for css sheets, it is better to put them all on the <head> tag but let the style that shall be immediately rendered to be put in <style> tags inside <HEAD> and the rest in <body>.

You may also find other suggestion when you test your page like on Google PageSpeed Insight

HTTP Request in Kotlin

I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

val url = "https://example.com/endpoint"

val client = OkHttpClient()

val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
        .addHeader("Authorization", "Bearer $token")
        .url(url)
        .post(body)
        .build()

val  response = client . newCall (request).execute()

println(response.request())
println(response.body()!!.string())

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

UPDATE: January 25th, 2021 Everything is okay with the most updated versions.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.12.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

Get Method

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
            .url(url)
            .get()
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}

POST Method

fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val body = jacksonString.toRequestBody(mediaType)

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}

How to "test" NoneType in python?

As pointed out by Aaron Hall's comment:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))

Django TemplateDoesNotExist?

It works now after I tried

chown -R www-data:www-data /usr/lib/python2.5/site-packages/projectname/*

It's strange. I dont need to do this on the remote server to make it work.

Also, I have to run the following command on local machine to make all static files accessable but on remote server they are all "root:root".

chown -R www-data:www-data /var/www/projectname/*

Local machine runs on Ubuntu 8.04 desktop edition. Remote server is on Ubuntu 9.04 server edition.

Anybody knows why?

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Get root password for Google Cloud Engine VM

I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.

So here are steps.

  1. Go to IAM & Admin
  2. Select IAM
  3. Find your user name service account (basically your google account) and click Edit-member
  4. Add another role --> select 'Compute Engine' - 'Compute Admin'
  5. Restart your Compute VM
  6. open SSH shell and run the command 'sudo passwd'
  7. enter a brand new password. Voilà!

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

String replace method is not replacing characters

You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

sentence = sentence.replace("and", " ");

A String is immutable in java. Methods like replace return a new String.

Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

How can I check if a MySQL table exists with PHP?

mysql_query("SHOW TABLES FROM yourDB");
//> loop thru results and see if it exists
//> in this way with only one query one can check easly more table 

or mysql_query("SHOW TABLES LIKE 'tblname'");

Don't use mysql_list_tables(); because it's deprecated

JQuery - File attributes

Just try

var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

It worked for me

CSS3 selector :first-of-type with class name?

You can do this by selecting every element of the class that is the sibling of the same class and inverting it, which will select pretty much every element on the page, so then you have to select by the class again.

eg:

<style>
    :not(.bar ~ .bar).bar {
        color: red;
    }
<div>
    <div class="foo"></div>
    <div class="bar"></div> <!-- Only this will be selected -->
    <div class="foo"></div>
    <div class="bar"></div>
    <div class="foo"></div>
    <div class="bar"></div>
</div>

.htaccess mod_rewrite - how to exclude directory from rewrite rule

If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]

The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .

To exclude all existent directries, you will need to use the following condition above your rule :

RewriteCond %{REQUEST_FILENAME} !-d

the following rule

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]

rewrites everything (except directries) to /index.php .

How do I convert Long to byte[] and back in java

If you are already using an OutputStream to write to the socket, then DataOutputStream might be a good fit. Here is an example:

// Assumes you are currently working with a SocketOutputStream.

SocketOutputStream outputStream = ...
long longValue = ...

DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

dataOutputStream.writeLong(longValue);
dataOutputStream.flush();

There are similar methods for short, int, float, etc. You can then use DataInputStream on the receiving side.

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

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

Loop in react-native

You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.

_x000D_
_x000D_
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
  console.log(guest);_x000D_
});
_x000D_
_x000D_
_x000D_

Example:

renderPayments(noGuest) {
  return Array(noGuest).fill(noGuest).map((guess, index) => {
    return(
      <View key={index}>
        <View><TextInput /></View>
        <View><TextInput /></View>
        <View><TextInput /></View>
      </View>
    );
  }
}

Then use it where you want it

render() {
  return(
     const { guest } = this.state;
     ...
     {this.renderPayments(guest)}
  );
}

Hope you got the idea.

If you want to understand this in simple Javascript check Array.prototype.fill()

How to delete mysql database through shell command

No need for mysqladmin:

just use mysql command line

mysql -u [username] -p[password] -e 'drop database db-name;'

This will send the drop command although I wouldn't pass the password this way as it'll be exposed to other users of the system via ps aux

Generating unique random numbers (integers) between 0 and 'x'

Math.floor(Math.random() * (limit+1))

Math.random() generates a floating point number between 0 and 1, Math.floor() rounds it down to an integer.

By multiplying it by a number, you effectively make the range 0..number-1. If you wish to generate it in range from num1 to num2, do:

Math.floor(Math.random() * (num2-num1 + 1) + num1)

To generate more numbers, just use a for loop and put results into an array or write them into the document directly.

Material Design not styling alert dialogs

For some reason the android:textColor only seems to update the title color. You can change the message text color by using a

SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));

AlertDialog dialog = builder.create();
                Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
                wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                dialog.setMessage(wordtoSpan);
                dialog.show();

Evaluate list.contains string in JSTL

${fn:contains({1,2,4,8}, 2)}

OR

  <c:if test = "${fn:contains(theString, 'test')}">
     <p>Found test string<p>
  </c:if>

  <c:if test = "${fn:contains(theString, 'TEST')}">
     <p>Found TEST string<p>
  </c:if>

Generating Unique Random Numbers in Java

I have made this like that.

    Random random = new Random();
    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    while (arrayList.size() < 6) { // how many numbers u need - it will 6
        int a = random.nextInt(49)+1; // this will give numbers between 1 and 50.

        if (!arrayList.contains(a)) {
            arrayList.add(a);
        }
    }

How to find the Target *.exe file of *.appref-ms

The app is stored in %LocalAppData% in your %UserProfile%. So the full path could be:

C:\Users\username\AppData\Local\GitHub

How to set input type date's default value to today?

HTML

<input type="date" id="theDate">

JS

$(document).ready(function() {
    var date = new Date();

    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    var today = year + "-" + month + "-" + day;       
    $("#theDate").attr("value", today);
});

demo

If you don't want to use jQuery you can do something like this

HTML

<input type="date" id="theDate">

JS

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;       
document.getElementById("theDate").value = today;

demo

How can I change IIS Express port for a site

If you just want to change the port because it is already in use. Follow the following steps.

In Visual studio

  1. Right-click on Project Node and Unload Project
  2. Right-click on Project Node and Edit .csproj file.
  3. Search for the following tags and remove them
<DevelopmentServerPort>62140</DevelopmentServerPort>
<DevelopmentServerVPath></DevelopmentServerVPath>
<IISUrl>http://localhost:62116/</IISUrl>
  1. press Ctrl + S to save the document
  2. Right-click on Project Node and load Project

It will work by selecting another port randomly.

For further information. please click

How to export the Html Tables data into PDF using Jspdf

"How to properly use jsPDF library" might give you a little more of what you need. The table won't render correctly (no css, per this answer), but you could do some parsing of the html table with jquery and manually style it yourself.

Another option would be to use screenshots of the HTML with HTML2Canvas or Casper.js.

EDIT

Here's a basic example using the jspdf cell plugin. It uses jquery and the tableToJson() function from HTML Table to JSON.

Be sure to include the Deflate lib (two js files) and jspdf.plugin.cell.js.

var table = tableToJson($('#table-id').get(0))
var doc = new jsPDF('p', 'pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
  $.each(row, function (j, cell){
    doc.cell(10, 200, 100, 20, cell, i);
  })
})
doc.save()

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Java Singleton and Synchronization

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

What is sharding and why is it important?

Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.

Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)

"Couldn't read dependencies" error with npm

I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install resolved my issue.

Can I get image from canvas element and use it in img src tag?

canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images. Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.

How to solve privileges issues when restore PostgreSQL Database

For people using AWS, the COMMENT ON EXTENSION is possible only as superuser, and as we know by the docs, RDS instances are managed by Amazon. As such, to prevent you from breaking things like replication, your users - even the root user you set up when you create the instance - will not have full superuser privileges:

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

When you create a DB instance, the master user system account that you create is assigned to the rds_superuser role. The rds_superuser role is a pre-defined Amazon RDS role similar to the PostgreSQL superuser role (customarily named postgres in local instances), but with some restrictions. As with the PostgreSQL superuser role, the rds_superuser role has the most privileges on your DB instance and you should not assign this role to users unless they need the most access to the DB instance.

In order to fix this error, just use -- to comment out the lines of SQL that contains COMMENT ON EXTENSION

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

I like the answer from 30thh using Iterators from Guava. However, from some frameworks I get null instead of an empty array, and Iterators.forArray(array) does not handle that well. So I came up with this helper method, which you can call with Iterator<String> it = emptyIfNull(array);

public static <F> UnmodifiableIterator<F> emptyIfNull(F[] array) {
    if (array != null) {
        return Iterators.forArray(array);
    }
    return new UnmodifiableIterator<F>() {
        public boolean hasNext() {
            return false;
        }

        public F next() {
            return null;
        }
    };
}

Is it possible to reference one CSS rule within another?

You can easily do so with SASS pre-processor by using @extend.

someDiv {
    @extend .opacity;
    @extend .radius;
}

Ohterwise, you could use JavaScript (jQuery) as well:

$('someDiv').addClass('opacity radius')

The easiest is of course to add multiple classes right in the HTML

<div class="opacity radius">

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

I had the same issue but I can solve this issue by cleaning the cookies and cache from my browser (ctrl+shift+R). Also, you must ensure that your access token is active.

Hope this will help you to solve your problem.

How to download a branch with git?

Create a new directory, and do a clone instead.

git clone (address of origin) (name of branch)

Microsoft.Office.Core Reference Missing

Open the properties of the solution and click publish. Then, reclick application files. Change prerequisite to include.

Create Excel files from C# without office

Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.

jQuery multiple events to trigger the same function

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

Generate list of all possible permutations of a string

permute (ABC) -> A.perm(BC) -> A.perm[B.perm(C)] -> A.perm[(*BC), (CB*)] -> [(*ABC), (BAC), (BCA*), (*ACB), (CAB), (CBA*)] To remove duplicates when inserting each alphabet check to see if previous string ends with the same alphabet (why? -exercise)

public static void main(String[] args) {

    for (String str : permStr("ABBB")){
        System.out.println(str);
    }
}

static Vector<String> permStr(String str){

    if (str.length() == 1){
        Vector<String> ret = new Vector<String>();
        ret.add(str);
        return ret;
    }

    char start = str.charAt(0);
    Vector<String> endStrs = permStr(str.substring(1));
    Vector<String> newEndStrs = new Vector<String>();
    for (String endStr : endStrs){
        for (int j = 0; j <= endStr.length(); j++){
            if (endStr.substring(0, j).endsWith(String.valueOf(start)))
                break;
            newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));
        }
    }
    return newEndStrs;
}

Prints all permutations sans duplicates

Javascript "Uncaught TypeError: object is not a function" associativity question

I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.

My input (type=button) had an attribute name that was identical to a function name that was being called by the onClick event. Once I changed the attribute name everything worked.

<input type="button" name="clearEmployer" onClick="clearEmployer();">

changed to:

<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

How can I use pointers in Java?

All objects in Java are references and you can use them like pointers.

abstract class Animal
{...
}

class Lion extends Animal
{...
}

class Tiger extends Animal
{   
public Tiger() {...}
public void growl(){...}
}

Tiger first = null;
Tiger second = new Tiger();
Tiger third;

Dereferencing a null:

first.growl();  // ERROR, first is null.    
third.growl(); // ERROR, third has not been initialized.

Aliasing Problem:

third = new Tiger();
first = third;

Losing Cells:

second = third; // Possible ERROR. The old value of second is lost.    

You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.

first = second;
second = third; //OK

Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.

The Java system will throw an exception (OutOfMemoryError) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.

Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.

Novices often make the following error.

Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed. 

What you probably meant to say was:

Tiger tony = null;
tony = third; // OK.

Improper Casting:

Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler. 

Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.

Pointers in C:

void main() {   
    int*    x;  // Allocate the pointers x and y
    int*    y;  // (but not the pointees)

    x = malloc(sizeof(int));    // Allocate an int pointee,
                                // and set x to point to it

    *x = 42;    // Dereference x to store 42 in its pointee

    *y = 13;    // CRASH -- y does not have a pointee yet

    y = x;      // Pointer assignment sets y to point to x's pointee

    *y = 13;    // Dereference y to store 13 in its (shared) pointee
}

Pointers in Java:

class IntObj {
    public int value;
}

public class Binky() {
    public static void main(String[] args) {
        IntObj  x;  // Allocate the pointers x and y
        IntObj  y;  // (but not the IntObj pointees)

        x = new IntObj();   // Allocate an IntObj pointee
                            // and set x to point to it

        x.value = 42;   // Dereference x to store 42 in its pointee

        y.value = 13;   // CRASH -- y does not have a pointee yet

        y = x;  // Pointer assignment sets y to point to x's pointee

        y.value = 13;   // Deference y to store 13 in its (shared) pointee
    }
} 

UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.

proper way to sudo over ssh

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

clear form values after submission ajax

$('.contactForm').submit(function(){
    var that = this;

    //...more form stuff...

    $.post('mail.php',{...params...},function(data){

        //...more success stuff...

        that.reset();
    });
});

How do I type a TAB character in PowerShell?

In the Windows command prompt you can disable tab completion, by launching it thusly:

cmd.exe /f:off

Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.

The cmd.exe help page explains it:

You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar

    and/or

HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar

with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.

If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.

How do you sort an array on multiple columns?

Sourced from GitHub

_x000D_
_x000D_
function sortMethodAsc(a, b) {_x000D_
    return a == b ? 0 : a > b ? 1 : -1;_x000D_
}_x000D_
_x000D_
function sortMethodWithDirection(direction) { _x000D_
    if (direction === undefined || direction == "asc") {_x000D_
        return sortMethodAsc;_x000D_
    } else {_x000D_
        return function(a, b) {_x000D_
            return -sortMethodAsc(a, b);_x000D_
        } _x000D_
    }_x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionByColumn(columnName, direction){   _x000D_
    const sortMethod = sortMethodWithDirection(direction)_x000D_
    return function(a, b){_x000D_
        return sortMethod(a[columnName], b[columnName]);_x000D_
    } _x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionMultiColumn(sortArray) {_x000D_
    //sample of sortArray_x000D_
    // sortArray = [_x000D_
    //     { column: "column5", direction: "asc" },_x000D_
    //     { column: "column3", direction: "desc" }_x000D_
    // ]_x000D_
    const sortMethodsForColumn = (sortArray || []).map( item => sortMethodWithDirectionByColumn(item.column, item.direction) );_x000D_
    return function(a,b) {_x000D_
        let sorted = 0;_x000D_
        let index = 0;_x000D_
        while (sorted === 0 && index < sortMethodsForColumn.length) {_x000D_
            sorted = sortMethodsForColumn[index++](a,b);_x000D_
        }_x000D_
        return sorted;_x000D_
    }_x000D_
} _x000D_
_x000D_
//=============================================_x000D_
//=============================================_x000D_
//=============================================_x000D_
//test_x000D_
_x000D_
var data = [_x000D_
    {"CountryName":"Aruba","CountryCode":"ABW","GNI":280},{_x000D_
        "CountryName":"Afghanistan","CountryCode":"ABW","GNI":280},{"CountryName":"Angola","CountryCode":"AGO","GNI":280},{"CountryName":"Albania","CountryCode":"ALB","GNI":4320},_x000D_
        {"CountryName":"Arab World","CountryCode":"ARB","GNI":280},{"CountryName":"United Arab Emirates","CountryCode":"ARE","GNI":39130},_x000D_
        {"CountryName":"Argentina","CountryCode":"ARG","GNI":13030},{"CountryName":"Armenia","CountryCode":"ARM","GNI":3990},{"CountryName":"American Samoa","CountryCode":"ASM","GNI":280},_x000D_
        {"CountryName":"Antigua and Barbuda","CountryCode":"ATG","GNI":13810},{"CountryName":"Australia","CountryCode":"AUS","GNI":51360},_x000D_
        {"CountryName":"Austria","CountryCode":"AUT","GNI":45440},{"CountryName":"Azerbaijan","CountryCode":"AZE","GNI":4080},{"CountryName":"Burundi","CountryCode":"BDI","GNI":280},_x000D_
        {"CountryName":"Belgium","CountryCode":"BEL","GNI":41790},{"CountryName":"Benin","CountryCode":"BEN","GNI":800},{"CountryName":"Burkina Faso","CountryCode":"BFA","GNI":590},_x000D_
        {"CountryName":"Bangladesh","CountryCode":"BGD","GNI":1470},{"CountryName":"Bulgaria","CountryCode":"BGR","GNI":7860},{"CountryName":"Bahrain","CountryCode":"BHR","GNI":21150},_x000D_
        {"CountryName":"Bosnia and Herzegovina","CountryCode":"BIH","GNI":4910},{"CountryName":"Belarus","CountryCode":"BLR","GNI":5280},_x000D_
        {"CountryName":"Belize","CountryCode":"BLZ","GNI":4390},{"CountryName":"Bolivia","CountryCode":"BOL","GNI":3130},{"CountryName":"Brazil","CountryCode":"BRA","GNI":8600},_x000D_
        {"CountryName":"Barbados","CountryCode":"BRB","GNI":15270},{"CountryName":"Brunei Darussalam","CountryCode":"BRN","GNI":29600},_x000D_
        {"CountryName":"Bhutan","CountryCode":"BTN","GNI":2660},{"CountryName":"Botswana","CountryCode":"BWA","GNI":6730},_x000D_
        {"CountryName":"Central African Republic","CountryCode":"CAF","GNI":390},{"CountryName":"Canada","CountryCode":"CAN","GNI":42870},_x000D_
        {"CountryName":"Central Europe and the Baltics","CountryCode":"CEB","GNI":13009},{"CountryName":"Switzerland","CountryCode":"CHE","GNI":80560},_x000D_
        {"CountryName":"Chile","CountryCode":"CHL","GNI":13610},{"CountryName":"China","CountryCode":"CHN","GNI":8690},{"CountryName":"Cote d'Ivoire","CountryCode":"CIV","GNI":1580},_x000D_
        {"CountryName":"Cameroon","CountryCode":"CMR","GNI":1370},{"CountryName":"Colombia","CountryCode":"COL","GNI":5890},{"CountryName":"Comoros","CountryCode":"COM","GNI":1280},_x000D_
        {"CountryName":"Cabo Verde","CountryCode":"CPV","GNI":3030},{"CountryName":"Costa Rica","CountryCode":"CRI","GNI":11120},_x000D_
        {"CountryName":"Caribbean small states","CountryCode":"CSS","GNI":8909},{"CountryName":"Cyprus","CountryCode":"CYP","GNI":23720},_x000D_
        {"CountryName":"Czech Republic","CountryCode":"CZE","GNI":18160},{"CountryName":"Germany","CountryCode":"DEU","GNI":43490},_x000D_
        {"CountryName":"Djibouti","CountryCode":"DJI","GNI":1880},{"CountryName":"Dominica","CountryCode":"DMA","GNI":6590},{"CountryName":"Denmark","CountryCode":"DNK","GNI":55220},_x000D_
        {"CountryName":"Dominican Republic","CountryCode":"DOM","GNI":6630},{"CountryName":"Algeria","CountryCode":"DZA","GNI":3940},_x000D_
        {"CountryName":"East Asia & Pacific (excluding high income)","CountryCode":"EAP","GNI":6987},{"CountryName":"Early-demographic dividend","CountryCode":"EAR","GNI":3352},_x000D_
        {"CountryName":"East Asia & Pacific","CountryCode":"EAS","GNI":10171},{"CountryName":"Europe & Central Asia (excluding high income)","CountryCode":"ECA","GNI":7375},_x000D_
        {"CountryName":"Europe & Central Asia","CountryCode":"ECS","GNI":22656},{"CountryName":"Ecuador","CountryCode":"ECU","GNI":5920},_x000D_
        {"CountryName":"Euro area","CountryCode":"EMU","GNI":35645},{"CountryName":"Spain","CountryCode":"ESP","GNI":27180},{"CountryName":"Estonia","CountryCode":"EST","GNI":18190},_x000D_
        {"CountryName":"Ethiopia","CountryCode":"ETH","GNI":740},{"CountryName":"European Union","CountryCode":"EUU","GNI":32784},_x000D_
        {"CountryName":"Fragile and conflict affected situations","CountryCode":"FCS","GNI":1510},{"CountryName":"Finland","CountryCode":"FIN","GNI":44580},_x000D_
        {"CountryName":"Fiji","CountryCode":"FJI","GNI":4970},{"CountryName":"France","CountryCode":"FRA","GNI":37970},{"CountryName":"Gabon","CountryCode":"GAB","GNI":6650},_x000D_
        {"CountryName":"United Kingdom","CountryCode":"GBR","GNI":40530},{"CountryName":"Georgia","CountryCode":"GEO","GNI":3780},{"CountryName":"Ghana","CountryCode":"GHA","GNI":1880},_x000D_
        {"CountryName":"Guinea","CountryCode":"GIN","GNI":790},{"CountryName":"Guinea-Bissau","CountryCode":"GNB","GNI":660},_x000D_
        {"CountryName":"Equatorial Guinea","CountryCode":"GNQ","GNI":7050},{"CountryName":"Greece","CountryCode":"GRC","GNI":18090},_x000D_
        {"CountryName":"Grenada","CountryCode":"GRD","GNI":9180},{"CountryName":"Guatemala","CountryCode":"GTM","GNI":4060},{"CountryName":"Guyana","CountryCode":"GUY","GNI":4500},_x000D_
        {"CountryName":"High income","CountryCode":"HIC","GNI":40142},{"CountryName":"Honduras","CountryCode":"HND","GNI":2250},{"CountryName":"Heavily indebted poor countries (HIPC)","CountryCode":"HPC","GNI":904},{"CountryName":"Croatia","CountryCode":"HRV","GNI":12570},{"CountryName":"Haiti","CountryCode":"HTI","GNI":760},{"CountryName":"Hungary","CountryCode":"HUN","GNI":12870},{"CountryName":"IBRD only","CountryCode":"IBD","GNI":5745},{"CountryName":"IDA & IBRD total","CountryCode":"IBT","GNI":4620},{"CountryName":"IDA total","CountryCode":"IDA","GNI":1313},{"CountryName":"IDA blend","CountryCode":"IDB","GNI":1791},_x000D_
        {"CountryName":"Indonesia","CountryCode":"IDN","GNI":3540},{"CountryName":"IDA only","CountryCode":"IDX","GNI":1074},{"CountryName":"India","CountryCode":"IND","GNI":1800},{"CountryName":"Ireland","CountryCode":"IRL","GNI":55290},{"CountryName":"Iraq","CountryCode":"IRQ","GNI":4630},{"CountryName":"Iceland","CountryCode":"ISL","GNI":60830},{"CountryName":"Israel","CountryCode":"ISR","GNI":37270},{"CountryName":"Italy","CountryCode":"ITA","GNI":31020},{"CountryName":"Jamaica","CountryCode":"JAM","GNI":4760},{"CountryName":"Jordan","CountryCode":"JOR","GNI":3980},{"CountryName":"Japan","CountryCode":"JPN","GNI":38550},{"CountryName":"Kazakhstan","CountryCode":"KAZ","GNI":7970},{"CountryName":"Kenya","CountryCode":"KEN","GNI":1460},{"CountryName":"Kyrgyz Republic","CountryCode":"KGZ","GNI":1130},_x000D_
        {"CountryName":"Cambodia","CountryCode":"KHM","GNI":1230},{"CountryName":"Kiribati","CountryCode":"KIR","GNI":3010},{"CountryName":"St. Kitts and Nevis","CountryCode":"KNA","GNI":16240},{"CountryName":"Kuwait","CountryCode":"KWT","GNI":31430},{"CountryName":"Latin America & Caribbean (excluding high income)","CountryCode":"LAC","GNI":7470},{"CountryName":"Lao PDR","CountryCode":"LAO","GNI":2270},{"CountryName":"Lebanon","CountryCode":"LBN","GNI":8400},{"CountryName":"Liberia","CountryCode":"LBR","GNI":620},{"CountryName":"Libya","CountryCode":"LBY","GNI":5500},{"CountryName":"St. Lucia","CountryCode":"LCA","GNI":8830},{"CountryName":"Latin America & Caribbean","CountryCode":"LCN","GNI":8251},{"CountryName":"Least developed countries: UN classification","CountryCode":"LDC","GNI":1011},{"CountryName":"Low income","CountryCode":"LIC","GNI":774},{"CountryName":"Sri Lanka","CountryCode":"LKA","GNI":3850},{"CountryName":"Lower middle income","CountryCode":"LMC","GNI":2118},{"CountryName":"Low & middle income","CountryCode":"LMY","GNI":4455},{"CountryName":"Lesotho","CountryCode":"LSO","GNI":1210},{"CountryName":"Late-demographic dividend","CountryCode":"LTE","GNI":8518},{"CountryName":"Lithuania","CountryCode":"LTU","GNI":15200},{"CountryName":"Luxembourg","CountryCode":"LUX","GNI":70260},{"CountryName":"Latvia","CountryCode":"LVA","GNI":14740},{"CountryName":"Morocco","CountryCode":"MAR","GNI":2860},{"CountryName":"Moldova","CountryCode":"MDA","GNI":2200},{"CountryName":"Madagascar","CountryCode":"MDG","GNI":400},{"CountryName":"Maldives","CountryCode":"MDV","GNI":9760},_x000D_
        {"CountryName":"Middle East & North Africa","CountryCode":"MEA","GNI":7236},{"CountryName":"Mexico","CountryCode":"MEX","GNI":8610},{"CountryName":"Marshall Islands","CountryCode":"MHL","GNI":4840},{"CountryName":"Middle income","CountryCode":"MIC","GNI":4942},{"CountryName":"Mali","CountryCode":"MLI","GNI":770},_x000D_
        {"CountryName":"Malta","CountryCode":"MLT","GNI":24080},{"CountryName":"Myanmar","CountryCode":"MMR","GNI":1210},{"CountryName":"Middle East & North Africa (excluding high income)","CountryCode":"MNA","GNI":3832},{"CountryName":"Montenegro","CountryCode":"MNE","GNI":7400},{"CountryName":"Mongolia","CountryCode":"MNG","GNI":3270},{"CountryName":"Mozambique","CountryCode":"MOZ","GNI":420},{"CountryName":"Mauritania","CountryCode":"MRT","GNI":1100},{"CountryName":"Mauritius","CountryCode":"MUS","GNI":10130},{"CountryName":"Malawi","CountryCode":"MWI","GNI":320},{"CountryName":"Malaysia","CountryCode":"MYS","GNI":9650},{"CountryName":"North America","CountryCode":"NAC","GNI":56721},{"CountryName":"Namibia","CountryCode":"NAM","GNI":4570},{"CountryName":"Niger","CountryCode":"NER","GNI":360},{"CountryName":"Nigeria","CountryCode":"NGA","GNI":2100},_x000D_
        {"CountryName":"Nicaragua","CountryCode":"NIC","GNI":2130},{"CountryName":"Netherlands","CountryCode":"NLD","GNI":46180},{"CountryName":"Norway","CountryCode":"NOR","GNI":75990},{"CountryName":"Nepal","CountryCode":"NPL","GNI":800},{"CountryName":"Nauru","CountryCode":"NRU","GNI":10220},{"CountryName":"New Zealand","CountryCode":"NZL","GNI":38970},{"CountryName":"OECD members","CountryCode":"OED","GNI":37273},{"CountryName":"Oman","CountryCode":"OMN","GNI":14440},{"CountryName":"Other small states","CountryCode":"OSS","GNI":12199},{"CountryName":"Pakistan","CountryCode":"PAK","GNI":1580},{"CountryName":"Panama","CountryCode":"PAN","GNI":13280},{"CountryName":"Peru","CountryCode":"PER","GNI":5960},{"CountryName":"Philippines","CountryCode":"PHL","GNI":3660},{"CountryName":"Palau","CountryCode":"PLW","GNI":12700},{"CountryName":"Papua New Guinea","CountryCode":"PNG","GNI":2340},{"CountryName":"Poland","CountryCode":"POL","GNI":12730},{"CountryName":"Pre-demographic dividend","CountryCode":"PRE","GNI":1379},{"CountryName":"Portugal","CountryCode":"PRT","GNI":19820},{"CountryName":"Paraguay","CountryCode":"PRY","GNI":5470},{"CountryName":"West Bank and Gaza","CountryCode":"PSE","GNI":3180},{"CountryName":"Pacific island small states","CountryCode":"PSS","GNI":3793},{"CountryName":"Post-demographic dividend","CountryCode":"PST","GNI":41609},{"CountryName":"Qatar","CountryCode":"QAT","GNI":60510},{"CountryName":"Romania","CountryCode":"ROU","GNI":10000},{"CountryName":"Russian Federation","CountryCode":"RUS","GNI":9230},{"CountryName":"Rwanda","CountryCode":"RWA","GNI":720},{"CountryName":"South Asia","CountryCode":"SAS","GNI":1729},{"CountryName":"Saudi Arabia","CountryCode":"SAU","GNI":20090},{"CountryName":"Sudan","CountryCode":"SDN","GNI":2380},{"CountryName":"Senegal","CountryCode":"SEN","GNI":1240},{"CountryName":"Singapore","CountryCode":"SGP","GNI":54530},{"CountryName":"Solomon Islands","CountryCode":"SLB","GNI":1920},{"CountryName":"Sierra Leone","CountryCode":"SLE","GNI":510},{"CountryName":"El Salvador","CountryCode":"SLV","GNI":3560},{"CountryName":"Serbia","CountryCode":"SRB","GNI":5180},{"CountryName":"Sub-Saharan Africa (excluding high income)","CountryCode":"SSA","GNI":1485},{"CountryName":"Sub-Saharan Africa","CountryCode":"SSF","GNI":1486},{"CountryName":"Small states","CountryCode":"SST","GNI":11099},{"CountryName":"Sao Tome and Principe","CountryCode":"STP","GNI":1770},{"CountryName":"Suriname","CountryCode":"SUR","GNI":5150},{"CountryName":"Slovak Republic","CountryCode":"SVK","GNI":16610},{"CountryName":"Slovenia","CountryCode":"SVN","GNI":22000},{"CountryName":"Sweden","CountryCode":"SWE","GNI":52590},{"CountryName":"Eswatini","CountryCode":"SWZ","GNI":2950},{"CountryName":"Seychelles","CountryCode":"SYC","GNI":14170},{"CountryName":"Chad","CountryCode":"TCD","GNI":640},{"CountryName":"East Asia & Pacific (IDA & IBRD countries)","CountryCode":"TEA","GNI":7061},_x000D_
        {"CountryName":"Europe & Central Asia (IDA & IBRD countries)","CountryCode":"TEC","GNI":7866},{"CountryName":"Togo","CountryCode":"TGO","GNI":610},{"CountryName":"Thailand","CountryCode":"THA","GNI":5950},{"CountryName":"Tajikistan","CountryCode":"TJK","GNI":990},{"CountryName":"Turkmenistan","CountryCode":"TKM","GNI":6380},{"CountryName":"Latin America & the Caribbean (IDA & IBRD countries)","CountryCode":"TLA","GNI":8179},{"CountryName":"Timor-Leste","CountryCode":"TLS","GNI":1790},{"CountryName":"Middle East & North Africa (IDA & IBRD countries)","CountryCode":"TMN","GNI":3839},{"CountryName":"Tonga","CountryCode":"TON","GNI":4010},{"CountryName":"South Asia (IDA & IBRD)","CountryCode":"TSA","GNI":1729},_x000D_
        {"CountryName":"Sub-Saharan Africa (IDA & IBRD countries)","CountryCode":"TSS","GNI":1486},{"CountryName":"Trinidad and Tobago","CountryCode":"TTO","GNI":15340},{"CountryName":"Tunisia","CountryCode":"TUN","GNI":3490},{"CountryName":"Turkey","CountryCode":"TUR","GNI":10940},{"CountryName":"Tuvalu","CountryCode":"TUV","GNI":4970},{"CountryName":"Tanzania","CountryCode":"TZA","GNI":910},{"CountryName":"Uganda","CountryCode":"UGA","GNI":600},{"CountryName":"Ukraine","CountryCode":"UKR","GNI":2390},{"CountryName":"Upper middle income","CountryCode":"UMC","GNI":8197},{"CountryName":"Uruguay","CountryCode":"URY","GNI":15250},{"CountryName":"United States","CountryCode":"USA","GNI":58270},{"CountryName":"Uzbekistan","CountryCode":"UZB","GNI":2000},{"CountryName":"St. Vincent and the Grenadines","CountryCode":"VCT","GNI":7390},{"CountryName":"Vietnam","CountryCode":"VNM","GNI":2160},{"CountryName":"Vanuatu","CountryCode":"VUT","GNI":2920},{"CountryName":"World","CountryCode":"WLD","GNI":10371},{"CountryName":"Samoa","CountryCode":"WSM","GNI":4090},{"CountryName":"Kosovo","CountryCode":"XKX","GNI":3900},_x000D_
        {"CountryName":"South Africa","CountryCode":"ZAF","GNI":5430},{"CountryName":"Zambia","CountryCode":"ZMB","GNI":1290},{"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1170},_x000D_
        {"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1171}];_x000D_
_x000D_
    const sortMethod = sortMethodWithDirectionMultiColumn(_x000D_
        [_x000D_
            { column: "GNI", direction: "asc" },_x000D_
            { column: "CountryCode", direction: "desc" }_x000D_
        ]_x000D_
    );_x000D_
    let sortedData = data.sort(sortMethod);  _x000D_
    _x000D_
    _x000D_
    console.log("sorted by: 1)column:GNI-asc, 2)column:CountryCode-desc") _x000D_
    console.table(sortedData);_x000D_
    console.log(sortedData);_x000D_
    
_x000D_
_x000D_
_x000D_

How to get selected path and name of the file opened with file dialog?

From office 2010, we won't be able to use the common dialog box control, so it's nice to use the Application object to get the desired results.

Here I got a text box and Command button - paste the following code under the command button click event, which will open the file dialog box and add the File name to the Text box.

Dim sFileName  As String

sFileName = Application.GetOpenFilename("MS Excel (*.xlsx), *.xls")

TextBox1.Text = sFileName

How do I set up NSZombieEnabled in Xcode 4?

On In Xcode 7

?<

or select Edit Scheme from Product > Scheme Menu

select Enable Zombie Objects form the Diagnostics tab

xcode 7 zombie flag

As alternative, if you prefer .xcconfig files you can read this article https://therealbnut.wordpress.com/2012/01/01/setting-xcode-4-0-environment-variables-from-a-script/

How to force Docker for a clean build of an image

In some extreme cases, your only way around recurring build failures is by running:

docker system prune

The command will ask you for your confirmation:

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all networks not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N]

This is of course not a direct answer to the question, but might save some lives... It did save mine.

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

When you run mysql -u bill -p, localhost is resolved to your ip, since it is 127.0.0.1 and in your /etc/hosts file, as default 127.0.0.1 localhost exists. So, mysql interprets you as bill@localhost which is not granted with bill@'%' . This is why there are 2 different records for root user in result of select host, user from mysql.user; query.

There are two ways to handle this issue.

One is specifying an ip which is not reversely resolved by /etc/hosts file when you try to login. For example, the ip of server is 10.0.0.2. When you run the command mysql -u bill -p -h 10.0.0.2, you will be able to login. If you type select user();, you will get [email protected]. Of course, any domain name should not be resolved to this ip in your /etc/hosts file.

Secondly, you need grant access for this specific domain name. For bill@localhost, you should call command grant all privileges on *.* to bill@localhost identified by 'billpass'; . In this case, you will be able to login with command mysql -u bill -p. Once logined, select user(); command returns bill@localhost.

But this is only for that you try to login a mysql server in the same host. From remote hosts, mysql behaves expectedly, '%' will grant you to login.

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

If WorkSheet("wsName") Exists

also a slightly different version. i just did a appllication.sheets.count to know how many worksheets i have additionallyl. well and put a little rename in aswell

Sub insertworksheet()
    Dim worksh As Integer
    Dim worksheetexists As Boolean
    worksh = Application.Sheets.Count
    worksheetexists = False
    For x = 1 To worksh
        If Worksheets(x).Name = "ENTERWROKSHEETNAME" Then
            worksheetexists = True
            'Debug.Print worksheetexists
            Exit For
        End If
    Next x
    If worksheetexists = False Then
        Debug.Print "transformed exists"
        Worksheets.Add after:=Worksheets(Worksheets.Count)
        ActiveSheet.Name = "ENTERNAMEUWANTTHENEWONE"
    End If
End Sub

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How do I install a pip package globally instead of locally?

Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

Maximum size of a varchar(max) variable

EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect.

I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful.

declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)