Programs & Examples On #Devel cover

Devel::Cover - Code coverage metrics for Perl

Angular-cli from css to scss

CSS Preprocessor integration for Angular CLI: 6.0.3

When generating a new project you can also define which extension you want for style files:

ng new sassy-project --style=sass

Or set the default style on an existing project:

ng config schematics.@schematics/angular:component.styleext scss

Angular CLI Documentation for all major CSS preprocessors

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Dynamically add script tag with src that may include document.write

I tried it by recursively appending each script

Note If your scripts are dependent one after other, then position will need to be in sync.

Major Dependency should be in last in array so that initial scripts can use it

_x000D_
_x000D_
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
  _x000D_
 const recursivelyAddScript = (script, cb) => {_x000D_
  const el = document.createElement('script')_x000D_
  el.src = script_x000D_
  if(count < scripts.length) {_x000D_
    count ++_x000D_
    el.onload = recursivelyAddScript(scripts[count])_x000D_
    document.body.appendChild(el)_x000D_
  } else {_x000D_
    console.log('All script loaded')_x000D_
    return_x000D_
  }_x000D_
}_x000D_
 _x000D_
  recursivelyAddScript(scripts[count])
_x000D_
_x000D_
_x000D_

CMake does not find Visual C++ compiler

Here is the solution that worked for me:

  1. Open Visual Studio command prompt tool (as an administrator). On windows 10 it might be called 'Developer command prompt'.
  2. Navigate to where you have the CMake executable
  3. Run Cmake.exe
  4. Proceed as usual to select build and source folder
  5. Select the appropriate Visual Studio compiler and hit the configure button

Hopefully it should run without problems.

Differences between ConstraintLayout and RelativeLayout

The real question to ask is, is there any reason to use any layout other than a constraint layout? I believe the answer might be no.

To those insisting they are aimed at novice programmers or the like, they should provide some reason for them to be inferior to any other layout.

Constraints layouts are better in every way (They do cost like 150k in APK size.). They are faster, they are easier, they are more flexible, they react better to changes, they fix the problems when items go away, they conform better to radically different screen types and they don't use a bunch of nested loop with that long drawn out tree structure for everything. You can put anything anywhere, with respect to anything, anywhere.

They were a bit screwy back in mid 2016, where the visual layout editor just wasn't good enough, but they are to the point that if you are having a layout at all, you might want to seriously consider using a constraint layout, even when it does the same thing as a RelativeLayout, or even a simple LinearLayout. FrameLayouts clearly still have their purpose. But, I can't see building anything else at this point. If they started with this they wouldn't have added anything else.

How to change value of ArrayList element in java

You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:

x = Integer.valueOf(9);

Additionally, Integer is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator (without adding your own layer of boxing). Do the following instead:

a.set(0, 9);

Ordering by specific field value first

This works for me using Postgres 9+:

SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC

How to make a machine trust a self-signed Java application

Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*

Spring Security redirect to previous page after successful login

I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.

Here is an example:

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Difference between e.target and e.currentTarget

target  is the element that triggered the event (e.g., the user clicked on)

currenttarget is the element that the event listener is attached to.

How do I lowercase a string in C?

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

How to check if a specific key is present in a hash or not?

It is very late but preferably symbols should be used as key:

my_hash = {}
my_hash[:my_key] = 'value'

my_hash.has_key?("my_key")
 => false 
my_hash.has_key?("my_key".to_sym)
 => true 

my_hash2 = {}
my_hash2['my_key'] = 'value'

my_hash2.has_key?("my_key")
 => true 
my_hash2.has_key?("my_key".to_sym)
 => false 

But when creating hash if you pass string as key then it will search for the string in keys.

But when creating hash you pass symbol as key then has_key? will search the keys by using symbol.


If you are using Rails, you can use Hash#with_indifferent_access to avoid this; both hash[:my_key] and hash["my_key"] will point to the same record

Convert Char to String in C

You could do many of the given answers, but if you just want to do it to be able to use it with strcpy, then you could do the following:

...
    strcpy( ... , (char[2]) { (char) c, '\0' } );
...

The (char[2]) { (char) c, '\0' } part will temporarily generate null-terminated string out of a character c.

This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.

How to convert JSON to a Ruby hash

Have you tried: http://flori.github.com/json/?

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.

server error:405 - HTTP verb used to access this page is not allowed

Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb

the solution would be to rename the page into .php or .aspx and you should be good to go :)

How to pass password to scp?

I found this really helpful answer here.

rsync -r -v --progress -e ssh user@remote-system:/address/to/remote/file /home/user/

Not only you can pass there the password, but also it will show the progress bar when copying. Really awesome.

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

How to get a Static property with Reflection

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

As in Swift 3.x for upload image with parameter we can use below alamofire upload method-

static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {

        let imageData = UIImageJPEGRepresentation(imageFile , 0.5)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")

            for key in parameters.keys{
                let name = String(key)
                if let val = parameters[name!] as? String{
                    multipartFormData.append(val.data(using: .utf8)!, withName: name!)
                }
            }
        }, to:inputUrl)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                })

                upload.responseJSON { response in

                    if let JSON = response.result.value {
                        completion(JSON)
                    }else{
                        completion(nilValue)
                    }
                }

            case .failure(let encodingError):
                completion(nilValue)
            }

        }

    }

Note: Additionally if our parameter is array of key-pairs then we can use

 var arrayOfKeyPairs = [[String:Any]]()
 let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
 let jsonPresentation = String(data: json!, encoding: .utf8)

Safest way to get last record ID from a table

SELECT IDENT_CURRENT('Table')

You can use one of these examples:

SELECT * FROM Table 
WHERE ID = (
    SELECT IDENT_CURRENT('Table'))

SELECT * FROM Table
WHERE ID = (
    SELECT MAX(ID) FROM Table)

SELECT TOP 1 * FROM Table
ORDER BY ID DESC

But the first one will be more efficient because no index scan is needed (if you have index on Id column).

The second one solution is equivalent to the third (both of them need to scan table to get max id).

Get raw POST body in Python Flask regardless of Content-Type header

request.stream is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data() instead.

data = request.stream.read()

The stream will be empty if it was previously read by request.data or another attribute.

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

Set background image in CSS using jquery

try this

 $(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");

Calculating the sum of two variables in a batch script

You need to use the property /a on the set command.

For example,

set /a "c=%a%+%b%"

This allows you to use arithmetic expressions in the set command, rather than simple concatenation.

Your code would then be:

@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%

and would output:

7
8

How to control size of list-style-type disc in CSS?

Apart from using custom images for bullets, you can also style the ul or li elements one way and then style the contents differently, as seen here.

The benefit is the lack of images for one thing, and also the added control. The disadvantage is that it tends to involve non-semantic markup, except in this case where the anchors are required already.

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

When do you use map vs flatMap in RxJava?

Here is a simple thumb-rule that I use help me decide as when to use flatMap() over map() in Rx's Observable.

Once you come to a decision that you're going to employ a map transformation, you'd write your transformation code to return some Object right?

If what you're returning as end result of your transformation is:

  • a non-observable object then you'd use just map(). And map() wraps that object in an Observable and emits it.

  • an Observable object, then you'd use flatMap(). And flatMap() unwraps the Observable, picks the returned object, wraps it with its own Observable and emits it.

Say for example we've a method titleCase(String inputParam) that returns Titled Cased String object of the input param. The return type of this method can be String or Observable<String>.

  • If the return type of titleCase(..) were to be mere String, then you'd use map(s -> titleCase(s))

  • If the return type of titleCase(..) were to be Observable<String>, then you'd use flatMap(s -> titleCase(s))

Hope that clarifies.

Json.NET serialize object with root name

Well, you can at least tell Json.NET to include the type name: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm . Newtonsoft.Json.JsonSerializer jser = new Newtonsoft.Json.JsonSerializer(); jser.TypeNameHandling = TypeNameHandling.Objects;

The type will be included at the beginning in the "$type" property of the object.

This is not exactly what you are looking for, but it was good enough for me when facing a similiar problem.

Spring MVC Controller redirect using URL parameters instead of in response

http://jira.springframework.org/browse/SPR-6464 provided me with what I needed to get things working until Spring MVC offers the functionality (potentially in the 3.0.2 release). Although I simply implemented the classes they have temporarily and added the filter to my web application context. Works great!

How can I submit a POST form using the <a href="..."> tag?

You need to use javascript for this.

<form id="form1" action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

fetch gives an empty response body

Try to use response.json():

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
}).then((response) => {
  console.log(response.json()); // null
  return dispatch({
    type: "GET_CALL",
    response: response.json()
  });
})
.catch(error => { console.log('request failed', error); });

Are HTTPS headers encrypted?

HTTP version 1.1 added a special HTTP method, CONNECT - intended to create the SSL tunnel, including the necessary protocol handshake and cryptographic setup.
The regular requests thereafter all get sent wrapped in the SSL tunnel, headers and body inclusive.

Android device is not connected to USB for debugging (Android studio)

This solution works for every unrecognized android device... mostly general brands don´t come with usb debugging drivers...

  • go to settings
  • control panel
  • hardware and sound
  • device manager
  • And look for any devices showing an error. Many androids will show as an unknown USB device or just Android

First thing you need will be your device IDs. You can get them opening up the device manager and finding the "Unknown Device" with a yellow exclamation point. Right click on it and select 'Properties', and then go to the 'Details' tab. Under the 'Property' drop down menu, select hardware IDs. There should be two strings:

USB\VID_2207&PID_0011&REV_0222&MI_01
USB\VID_2207&PID_0011&MI_01

Copy those strings somewhere and then navigate to where you downloaded the Google USB driver. Then you need to open up the file 'android_winusb.inf' in a text editor. I would recommend using Notepad++.

android_winusb.inf

First, create a sub-section for your device. I called mine ';RCA 6378W2' but it doesn't really matter what you call it. Then, under the sub-section you created paste the Device ID strings you copied from the Device Manager, preceded by '%SingleAdbInterface%'. If you need help, look at this screenshot.

NOTE:

If you are using Windows 8 or 8.1, you will need to disable device driver signature checks before you'll be able to install the modified driver. Here's a quick video on how to disable device driver checks http://www.youtube.com/watch?v=NM1MN8QZhnk. Ignore the part at the beginning about 64 bit, your computer architecture doesn't matter.

Please look at this article, for more information and MacOS instructions.

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

Styling the last td in a table with css

If you are already using javascript take a look at jQuery. It supports a browser independent "last-child" selector and you can do something like this.

$("td:last-child").css({border:"none"})

Build an iOS app without owning a mac?

You can use Phonegap (Cordova) to develop iOS Apps without a Mac, but yout would still need a Mac to submit your application to the App Store. We developed a cloud application which also can publish your app without a Mac https://www.wenz.io/ApplicationLoader. Currently we are in beta and you can use the service for free.

Best regards, Steffen Wenz

(I'm the creator of the site)

How to delete mysql database through shell command

MySQL has discontinued drop database command from mysql client shell. Need to use mysqladmin to drop a database.

app-release-unsigned.apk is not signed

adding below lines of code in build.gradel file worked for me, add them under buildTypes block below release as shown

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        applicationIdSuffix ".debug"
        debuggable true
    }

HTML - how can I show tooltip ONLY when ellipsis is activated

This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:

$.when($('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
})).done(function(){ 
   setupTooltip();
});

If you didn't want to check for ellipsis css, you could simplify like:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
})).done(function(){ 
   setupTooltip();
});

I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.

If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:

$('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
});

Or without check for ellipsis:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
});

How do I install Python 3 on an AWS EC2 instance?

Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).

Note, you'll probably want to do sudo yum groupinstall 'Development Tools' before doing this otherwise pip won't install.

wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

I can not use the "int length" constructor for StringBuilder since the length of my CLOB is longer than a int and needs a long value.

If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.

If the actual length of the CLOB is smaller than Integer.MAX_VALUE, just force the long to int by putting (int) in front of it.

How can I check if a string is a number?

Use int.TryParse():

string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);

result will be true if it was.

Prevent scroll-bar from adding-up to the Width of page on Chrome

I had the same issue on Chrome. It only happened for me when the scroll bar is always visible. (found in the general settings) I have a modal and when I open the modal I noticed that...

body {
    padding-left: 15px;
}

is added to the body. To stop this from happening I added

body {
    padding-left: 0px !important;
}

forEach loop Java 8 for Map entry set

Stream API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}

IF statement: how to leave cell blank if condition is false ("" does not work)

Here is what I do

=IF(OR(ISBLANK(AH38),AH38=""),"",IF(AI38=0,0,AH38/AI38))

Use the OR condition OR(ISBLANK(cell), cell="")

What is a practical use for a closure in JavaScript?

JavaScript closures can be used to implement throttle and debounce functionality in your application.

Throttling

Throttling puts a limit on as a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."

Code:

const throttle = (func, limit) => {
  let isThrottling
  return function() {
    const args = arguments
    const context = this
    if (!isThrottling) {
      func.apply(context, args)
      isThrottling = true
      setTimeout(() => isThrottling = false, limit)
    }
  }
}

Debouncing

Debouncing puts a limit on a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."

Code:

const debounce = (func, delay) => {
  let debouncing
  return function() {
    const context = this
    const args = arguments
    clearTimeout(debouncing)
    debouncing = setTimeout(() => func.apply(context, args), delay)
  }
}

As you can see closures helped in implementing two beautiful features which every web application should have to provide smooth UI experience functionality.

Remove a folder from git tracking

I know this is an old thread but I just wanted to add a little as the marked solution didn't solve the problem for me (although I tried many times).

The only way I could actually stop git form tracking the folder was to do the following:

  1. Make a backup of the local folder and put in a safe place.
  2. Delete the folder from your local repo
  3. Make sure cache is cleared git rm -r --cached your_folder/
  4. Add your_folder/ to .gitignore
  5. Commit changes
  6. Add the backup back into your repo

You should now see that the folder is no longer tracked.

Don't ask me why just clearing the cache didn't work for me, I am not a Git super wizard but this is how I solved the issue.

Selecting distinct values from a JSON

Underscore.js is great for this kind of thing. You can use _.countBy() to get the counts per name:

data = [{"id":11,"name":"ajax","subject":"OR","mark":63},
        {"id":12,"name":"javascript","subject":"OR","mark":63},
        {"id":13,"name":"jquery","subject":"OR","mark":63},
        {"id":14,"name":"ajax","subject":"OR","mark":63},
        {"id":15,"name":"jquery","subject":"OR","mark":63},
        {"id":16,"name":"ajax","subject":"OR","mark":63},
        {"id":20,"name":"ajax","subject":"OR","mark":63}]

_.countBy(data, function(data) { return data.name; });

Gives:

{ajax: 4, javascript: 1, jquery: 2} 

For an array of the keys just use _.keys()

_.keys(_.countBy(data, function(data) { return data.name; }));

Gives:

["ajax", "javascript", "jquery"]

Split / Explode a column of dictionaries into separate columns with pandas

To convert the string to an actual dict, you can do df['Pollutant Levels'].map(eval). Afterwards, the solution below can be used to convert the dict to different columns.


Using a small example, you can use .apply(pd.Series):

In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

In [3]: df
Out[3]:
   a                   b
0  1           {u'c': 1}
1  2           {u'd': 3}
2  3  {u'c': 5, u'd': 6}

In [4]: df['b'].apply(pd.Series)
Out[4]:
     c    d
0  1.0  NaN
1  NaN  3.0
2  5.0  6.0

To combine it with the rest of the dataframe, you can concat the other columns with the above result:

In [7]: pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)
Out[7]:
   a    c    d
0  1  1.0  NaN
1  2  NaN  3.0
2  3  5.0  6.0

Using your code, this also works if I leave out the iloc part:

In [15]: pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
Out[15]:
   a    c    d
0  1  1.0  NaN
1  2  NaN  3.0
2  3  5.0  6.0

Recyclerview inside ScrollView not scrolling smoothly

Every answer is same here. and i already used what everyone is suggested. Then i found that NestedScrollView is faster then ScrollView so

use

<androidx.core.widget.NestedScrollView

Instead of

<ScrollView

And use this as usual

recycleView.setNestedScrollingEnabled(false);

Have Excel formulas that return 0, make the result blank

The normal way would be the IF statement, though simpler than your example:

=IF(INDEX(a,b,c),INDEX(a,b,c),"")

No need to do gyrations with the formula, since zero values trigger the false condition.

JQuery datepicker language

You need to do something like this,

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '<Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

for sv data follow the following link

http://code.google.com/p/logicss/source/browse/trunk/media/jquery/jquery.ui.i18n.all.min.js?r=41

How can I add a box-shadow on one side of an element?

This site helped me: https://gist.github.com/ocean90/1268328 (Note that on that site the left and right are reversed as of the date of this post... but they work as expected). They are corrected in the code below.

<!DOCTYPE html>
<html>
    <head>
        <title>Box Shadow</title>

        <style>
            .box {
                height: 150px;
                width: 300px;
                margin: 20px;
                border: 1px solid #ccc;
            }

            .top {
                box-shadow: 0 -5px 5px -5px #333;
            }

            .right {
                box-shadow: 5px 0 5px -5px #333;
            }

            .bottom {
                box-shadow: 0 5px 5px -5px #333;
            }

            .left {
                box-shadow: -5px 0 5px -5px #333;
            }

            .all {
                box-shadow: 0 0 5px #333;
            }
        </style>
    </head>
    <body>
        <div class="box top"></div>
        <div class="box right"></div>
        <div class="box bottom"></div>
        <div class="box left"></div>
        <div class="box all"></div>
    </body>
</html>

Open a webpage in the default browser

Here is a little sub that may just interest some people who need to specify the browser. (but its not as good as a 12" pizza sub!) :P

Private Sub NavigateWebURL(ByVal URL As String, Optional browser As String = "default")

    If Not (browser = "default") Then
        Try
            '// try set browser if there was an error (browser not installed)
            Process.Start(browser, URL)
        Catch ex As Exception
            '// use default browser
            Process.Start(URL)
        End Try

    Else
        '// use default browser
        Process.Start(URL)

    End If

End Sub

Call: will open www.google.com in Firefox if it is installed on that PC.

NavigateWebURL("http://www.google.com", "Firefox") '// safari Firefox chrome etc

Call: will open www.google.com in default browser.

NavigateWebURL("http://www.google.com", "default")

OR

NavigateWebURL("http://www.google.com")

How do you round a number to two decimal places in C#?

Here's some examples:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

You might also want to look at bankers rounding / round-to-even with the following overload:

Math.Round(a, 2, MidpointRounding.ToEven);

There's more information on it here.

Two dimensional array list

Here's how to make and print a 2D Multi-Dimensional Array using the ArrayList Object.

import java.util.ArrayList;

public class TwoD_ArrayListExample {
    static public ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();

    public static void main(String[] args) {
        insertObjects();
        printTable(gameBoard);
    }

    public static void insertObjects() {
        for (int rowNum = 0; rowNum != 8; rowNum++) {
            ArrayList<String> oneRow = new ArrayList<String>();
            gameBoard.add(rowNum, oneRow);

            for (int columnNum = 0; columnNum != 8; columnNum++) {
                String description= "Description of Objects: row= "+ rowNum + ", column= "+ columnNum;
                    oneRow.add(columnNum, description);
            }
        }
    }

    // The printTable method prints the table to the console
    private static void printTable(ArrayList<ArrayList<String>> table) {
        for (int row = 0; row != 8; row++) {
            for (int col = 0; col != 8; col++) {
                System.out.println("Printing:               row= "+ row+ ", column= "+ col);
                System.out.println(table.get(row).get(col).toString());
            }
        }
        System.out.println("\n");
    }
}

PHP Adding 15 minutes to Time value

Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.

// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');

Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:

!g:i:s 12-hour format without leading zeroes on hour

!G:i:s 12-hour format with leading zeroes

Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

How to make external HTTP requests with Node.js

I would combine node-http-proxy and express.

node-http-proxy will support a proxy inside your node.js web server via RoutingProxy (see the example called Proxy requests within another http server).

Inside your custom server logic you can do authentication using express. See the auth sample here for an example.

Combining those two examples should give you what you want.

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

How can I convert integer into float in Java?

You just need to cast at least one of the operands to a float:

float z = (float) x / y;

or

float z = x / (float) y;

or (unnecessary)

float z = (float) x / (float) y;

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

jQuery - setting the selected value of a select control via its text description

I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.

I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.

$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 

AlertDialog styling - how to change style (color) of title, message, etc

It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941

enter image description here enter image description here enter image description here enter image description here

Determining the current foreground application from a background task or service

This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur

ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
                PackageManager pm = context.getPackageManager();
                List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
                for(RunningAppProcessInfo appProcess : appProcesses) {              
                    if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
                        Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
                    }               
                }

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

Try this, It worked for me

SELECT * FROM (
            SELECT
                [Code],
                [Name],
                [CategoryCode],
                [CreatedDate],
                [ModifiedDate],
                [CreatedBy],
                [ModifiedBy],
                [IsActive],
                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

Error message "Strict standards: Only variables should be passed by reference"

Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.

$monthly_index = @array_shift(unpack('H*', date('m/Y')));

It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.

As result, I am sure your friend 'system administrator' will be pleased with a less polluted error.log.

How to add an image to the emulator gallery in android studio?

I'd like to complement Mithilesh Izardar's answer:

Indeed the best approach is simply to "Drag and Drop", which afterwards you can find the files in the emulator at Settings ? Storage ? Internal Storage ? Explore ? Download (API 25). The problem for me was that after following these steps the pics weren't appearing neither in the "Gallery" nor in the "Downloads" (by simply clicking the "Downloads" icon).

The reason for this is because by default everything in the emulator has no permissions...so all you gotta do is give the "Gallery" storage permission: Settings ? Apps ? Gallery ? Permissions (API 25)

Ps: If you just copied the pictures, the new ones won't show up right away. You should either restart the emulator, or remount the sdcard (at Settings ? Storage unmount the sdcard by clicking the eject icon then remount it)

How to pass multiple parameters to a get method in ASP.NET Core

You also can use this:

// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
    return $"{firstName}:{lastName}:{address}";
}

Note: Please refer to metalheart's and metalheart and Mark Hughes for a possibly better approach.

Xcode swift am/pm time to 24 hour format

I am using a function here in my case by which I am updating a label with the normal time format and after that I am storing the selected time's 24hr format to do some another tasks..

Here is my code...

func timeUpdate(sender: NSDate)
{
    let timeSave = NSDateFormatter() //Creating first object to update time label as 12hr format with AM/PM
    timeSave.timeStyle = NSDateFormatterStyle.ShortStyle //Setting the style for the time selection.
    self.TimeShowOutlet.text = timeSave.stringFromDate(sender) // Getting the string from the selected time and updating the label as 1:40 PM
    let timeCheck = NSDateFormatter() //Creating another object to store time in 24hr format.
    timeCheck.dateFormat = "HH:mm:ss" //Setting the format for the time save.
    let time = timeCheck.stringFromDate(sender) //Getting the time string as 13:40:00
    self.timeSelectedForCheckAvailability = time //At last saving the 24hr format time for further task.
}

After writing this function you can call this where you are choosing the time from date/time picker.

Thanks, Hope this helped.

How to select the last record of a table in SQL?

to get the last row of a SQL-Database use this sql string:

SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);

Output:

Last Line of your db!

Oracle - How to create a readonly user

Execute the following procedure for example as user system.

Set p_owner to the schema owner and p_readonly to the name of the readonly user.

create or replace
procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2) 
AUTHID CURRENT_USER is
BEGIN
    execute immediate 'create user '||p_readonly||' identified by '||p_readonly;
    execute immediate 'grant create session to '||p_readonly;
    execute immediate 'grant select any dictionary to '||p_readonly;
    execute immediate 'grant create synonym to '||p_readonly;

   FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
      execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly;
   END LOOP;
   FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
      execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly;
   END LOOP;
   FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
      EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
   END LOOP;
   FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
      execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
   END LOOP;
END;

Good NumericUpDown equivalent in WPF?

If commercial solutions are ok, you may consider this control set: WPF Elements by Mindscape

It contains such a spin control and alternatively (my personal preference) a spin-decorator, that can decorate various numeric controls (like IntegerTextBox, NumericTextBox, also part of the control set) in XAML like this:

<WpfElements:SpinDecorator>
   <WpfElements:IntegerTextBox Text="{Binding Foo}" />
</WpfElements:SpinDecorator>

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

How to replace NaN value with zero in a huge data frame?

The following should do what you want:

x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)

Email address validation in C# MVC 4 application: with or without using Regex

It is surprising the question of validating an email address continually comes up on SO!

You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.

Excerpt:

The virtue of my regular expression above is that it matches 99% of the email addresses in use today. All the email address it matches can be handled by 99% of all email software out there. If you're looking for a quick solution, you only need to read the next paragraph. If you want to know all the trade-offs and get plenty of alternatives to choose from, read on.

See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:

To all the complainers: after 3 hours experimenting all the solutions offered in this gigantic discussion, this is THE ONLY good java regex solution I can find. None of the rfc5322 stuff works on java regex.

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

string test = "He said to me, \"Hello World\" . How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.

Define css class in django Forms

Here is another solution for adding class definitions to the widgets after declaring the fields in the class.

def __init__(self, *args, **kwargs):
    super(SampleClass, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs['class'] = 'my_class'

Checking if sys.argv[x] is defined

It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.

if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]
else:
  startingpoint = 'blah'

How to parse a CSV file using PHP

Just discovered a handy way to get an index while parsing. My mind was blown.

$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
    // Do something will $row array
}
fclose($handle);

Source: link

How to Automatically Start a Download in PHP?

Here is an example of sending back a pdf.

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);

@Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?

Also in the PHP manual Hayley Watson posted:

If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).

Also according IANA there is no registered application/force-download type.

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

How to use export with Python on Linux

export is a command that you give directly to the shell (e.g. bash), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.

Here's what's happening when you try os.system('export MY_DATA="my_export"')...

/bin/bash process, command `python yourscript.py` forks python subprocess
 |_
   /usr/bin/python process, command `os.system()` forks /bin/sh subprocess
    |_
      /bin/sh process, command `export ...` changes its local environment

When the bottom-most /bin/sh subprocess finishes running your export ... command, then it's discarded, along with the environment that you have just changed.

Is #pragma once a safe include guard?

The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.

That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.

Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.

In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.

#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once

#include "Thing.h"

namespace MyApp
{
 // ...
}

#endif

That way you get the best of both (cross-platform and help compilation speed).

As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).

Regex doesn't work in String.matches()

java's implementation of regexes try to match the whole string

that's different from perl regexes, which try to find a matching part

if you want to find a string with nothing but lower case characters, use the pattern [a-z]+

if you want to find a string containing at least one lower case character, use the pattern .*[a-z].*

Fatal Error :1:1: Content is not allowed in prolog

There are certainly some weird characters (e.g. BOM) or some whitespace before the XML preamble (<?xml ...?>)?

Correct way to find max in an Array in Swift

In Swift 2.0, the minElement and maxElement become methods of SequenceType protocol, you should call them like:

let a = [1, 2, 3]
print(a.maxElement()) //3
print(a.minElement()) //1

Using maxElement as a function like maxElement(a) is unavailable now.

The syntax of Swift is in flux, so I can just confirm this in Xcode version7 beta6.

It may be modified in the future, so I suggest that you'd better check the doc before you use these methods.

jQuery and AJAX response header

If this is a CORS request, you may see all headers in debug tools (such as Chrome->Inspect Element->Network), but the xHR object will only retrieve the header (via xhr.getResponseHeader('Header')) if such a header is a simple response header:

  • Content-Type
  • Last-modified
  • Content-Language
  • Cache-Control
  • Expires
  • Pragma

If it is not in this set, it must be present in the Access-Control-Expose-Headers header returned by the server.

About the case in question, if it is a CORS request, one will only be able to retrieve the Location header through the XMLHttpRequest object if, and only if, the header below is also present:

Access-Control-Expose-Headers: Location

If its not a CORS request, XMLHttpRequest will have no problem retrieving it.

Difference between Dictionary and Hashtable

Simply, Dictionary<TKey,TValue> is a generic type, allowing:

  • static typing (and compile-time verification)
  • use without boxing

If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

Position a div container on the right side

if you don't want to use float

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

make a phone call click on a button

Have you given the permission in the manifest file

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

and inside your activity

  Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:123456789"));
    startActivity(callIntent);

Let me know if you find any issue.

Class not registered Error

I had this problem and I solved it when I understood that it was looking for the Windows Registry specified in the brackets.

Since the error was happening only in one computer, what I had to do was export the registry from the computer that it was working and install it on the computer that was missing it.

How to open google chrome from terminal?

on mac terminal (at least in ZSH): open stackoverflow.com (opens site in new tab in your chrome default browser)

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

Comparing mongoose _id and strings

I faced exactly the same problem and i simply resolved the issue with the help of JSON.stringify() as follow:-

if (JSON.stringify(results.userId) === JSON.stringify(AnotherMongoDocument._id)) {
        console.log('This is never true');
}

CSS: borders between table columns only

Take a table with class name column-bordered-table then add this below css.This will work with bootstrap table too

.column-bordered-table thead td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table tfoot tr {
    border-top: 1px solid #c3c3c3;
    border-bottom: 1px solid #c3c3c3;
}

see the output below
N:B You have to add table header backgorund color as per you requirement

enter image description here

Moment.js with ReactJS (ES6)

If you are working with API, then you can use it as:

import moment from 'moment'
...

        this.state = {
            List: []
        };
    }


    componentDidMount() {
        this.getData();
    }
    // Show List
    getData() {
        fetch('url')
            .then((response) => {
                response.json()
                    .then((result) => {
                        this.setState({ List: result })
                    })
            })
    }
this.state.List = 
this.state.List.map(row => ({...row, dob: moment(row.dob).format("YYYY/MM/DD")}))

...

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

What is a Question Mark "?" and Colon ":" Operator Used for?

Thats an if/else statement equilavent to

if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

While creating setup for www.spotdekho.com in new windows10 machine, I was unable to run command "nodemon web.js" due same error

"Error: Cannot find module '../build/Release/bson'"

Got it fixed by below steps :

  1. Create folder "Release" inside "node_modules\bson\build\" location
  2. Copy bson.js from "node_modules\bson\browser_build\"
  3. Paste bson.js inside "node_modules\bson\build\Release" folder.

This will resolve the issue.

PS : I am using mongoose version 4.8.8 .

Thanks :) , hope it helps someone .

How to get the first and last date of the current year?

SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())

Closing a file after File.Create

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

What is a practical, real world example of the Linked List?

A linked list is like a conga line. Everyone holds the hips of the person in front of them and their hips are held in turn by the person to their rear, excepting only those in the front and the back. The only way to add people to the line is to find the right spot and decouple that connection, then insert the new person or people.

Root password inside a Docker container

I am able to get it working with the below command.

root@gitnew:# docker exec -it --user $(username) $(containername) /bin/bash

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How can I add new dimensions to a Numpy array?

Alternatively to

image = image[..., np.newaxis]

in @dbliss' answer, you can also use numpy.expand_dims like

image = np.expand_dims(image, <your desired dimension>)

For example (taken from the link above):

x = np.array([1, 2])

print(x.shape)  # prints (2,)

Then

y = np.expand_dims(x, axis=0)

yields

array([[1, 2]])

and

y.shape

gives

(1, 2)

How to declare a vector of zeros in R

You can also use the matrix command, to create a matrix with n lines and m columns, filled with zeros.

matrix(0, n, m)

Finding non-numeric rows in dataframe in pandas?

You could use np.isreal to check the type of each element (applymap applies a function to each element in the DataFrame):

In [11]: df.applymap(np.isreal)
Out[11]:
          a     b
item
a      True  True
b      True  True
c      True  True
d     False  True
e      True  True

If all in the row are True then they are all numeric:

In [12]: df.applymap(np.isreal).all(1)
Out[12]:
item
a        True
b        True
c        True
d       False
e        True
dtype: bool

So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):

In [13]: df[~df.applymap(np.isreal).all(1)]
Out[13]:
        a    b
item
d     bad  0.4

You could also find the location of the first offender you could use argmin:

In [14]: np.argmin(df.applymap(np.isreal).all(1))
Out[14]: 'd'

As @CTZhu points out, it may be slightly faster to check whether it's an instance of either int or float (there is some additional overhead with np.isreal):

df.applymap(lambda x: isinstance(x, (int, float)))

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

Important points in my experience:

  • every resource accessed by the server must be in an executable and readable directory, hence the xx5 in every chmod in other answers.
  • most of the time the webserver (apache in my case) is running neither as the user nor in the group that owns the directory, so again xx5 or chmod o+rx is necessary.

But the greater conclusion I reached is start from little to more.

For example, if http://myserver.com/sites/all/resources/assets/css/bootstrap.css yields a 403 error, see if http://myserver.com/ works, then sites, then sites/all, then sites/all/resources, and so on.

It will help if your server has directory indexes enable:

  • In Apache: Options +Indexes

This instruction might also be in the .htaccess of your webserver public_html folder.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Kotlin? Here we go:

android {

    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)

        kapt {
            arguments {
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }

    buildTypes {
        // ... (buildTypes, compileOptions, etc)
    }
}

//...

Don't forget about plugin:

apply plugin: 'kotlin-kapt'

For more information about kotlin annotation processor please visit: Kotlin docs

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

How do you rename a MongoDB database?

The above process is slow,you can use below method but you need to move collection by collection to another db.

use admin
db.runCommand({renameCollection: "[db_old_name].[collection_name]", to: "[db_new_name].[collection_name]"})

How to get the wsdl file from a webservice's URL

To download the wsdl from a url using Developer Command Prompt for Visual Studio, run it in Administrator mode and enter the following command:

 svcutil /t:metadata http://[your-service-url-here]

You can now consume the downloaded wsdl in your project as you see fit.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I got this error and found that I don't have my SSH port (non standard number) whitelisted in config server firewall.

Map implementation with duplicate keys

class  DuplicateMap<K, V> 
{
    enum MapType
    {
        Hash,LinkedHash
    }

    int HashCode = 0;
    Map<Key<K>,V> map = null;

    DuplicateMap()
    {
        map = new HashMap<Key<K>,V>();
    }

    DuplicateMap( MapType maptype )
    {
        if ( maptype == MapType.Hash ) {
            map = new HashMap<Key<K>,V>();
        }
        else if ( maptype == MapType.LinkedHash ) {
            map = new LinkedHashMap<Key<K>,V>();
        }
        else
            map = new HashMap<Key<K>,V>();
    }

    V put( K key, V value  )
    {

        return map.put( new Key<K>( key , HashCode++ ), value );
    }

    void putAll( Map<K, V> map1 )
    {
        Map<Key<K>,V> map2 = new LinkedHashMap<Key<K>,V>();

        for ( Entry<K, V> entry : map1.entrySet() ) {
            map2.put( new Key<K>( entry.getKey() , HashCode++ ), entry.getValue());
        }
        map.putAll(map2);
    }

    Set<Entry<K, V>> entrySet()
    {
        Set<Entry<K, V>> entry = new LinkedHashSet<Map.Entry<K,V>>();
        for ( final Entry<Key<K>, V> entry1 : map.entrySet() ) {
            entry.add( new Entry<K, V>(){
                private K Key = entry1.getKey().Key();
                private V Value = entry1.getValue();

                @Override
                public K getKey() {
                    return Key;
                }

                @Override
                public V getValue() {
                    return Value;
                }

                @Override
                public V setValue(V value) {
                    return null;
                }});
        }

        return entry;
    }

    @Override
    public String toString() {
        StringBuilder builder = new  StringBuilder();
        builder.append("{");
        boolean FirstIteration = true;
        for ( Entry<K, V> entry : entrySet() ) {
            builder.append( ( (FirstIteration)? "" : "," ) + ((entry.getKey()==null) ? null :entry.getKey().toString() ) + "=" + ((entry.getValue()==null) ? null :entry.getValue().toString() )  );
            FirstIteration = false;
        }
        builder.append("}");
        return builder.toString();
    }

    class Key<K1>
    {
        K1 Key;
        int HashCode;

        public Key(K1 key, int hashCode) {
            super();
            Key = key;
            HashCode = hashCode;
        }

        public K1 Key() {
            return Key;
        }

        @Override
        public String toString() {
            return  Key.toString() ;
        }

        @Override
        public int hashCode() {

            return HashCode;
        }
    }

Use JAXB to create Object from XML String

If you already have the xml, and comes more than one attribute, you can handle it as follows:

String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {           
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);
    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);
    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

the method getCharacterDataFromElement is

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;

return cd.getData();
}
return "";
}

How to make a node.js application run permanently?

I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.

Iterating over every two elements in a list

for (i, k) in zip(l[::2], l[1::2]):
    print i, "+", k, "=", i+k

zip(*iterable) returns a tuple with the next element of each iterable.

l[::2] returns the 1st, the 3rd, the 5th, etc. element of the list: the first colon indicates that the slice starts at the beginning because there's no number behind it, the second colon is only needed if you want a 'step in the slice' (in this case 2).

l[1::2] does the same thing but starts in the second element of the lists so it returns the 2nd, the 4th, 6th, etc. element of the original list.

XAMPP - MySQL shutdown unexpectedly

There are a number of things I've tried. This is the 2nd time this has happened to me. On my first time, I've to reinstall my xampp. And on the third day, mysql crashed again. I've tried everything I found on the internet. Like, innodb_flush_method=normal in my.ini file and deleting ibdata1, ib_logfile1, ib_logfile0 files, and others but none of these works. So later I tried to run xampp with admin privilege and install apache and mysql as a service as it was instructed on xampp control panel itself. After starting mysql, I read error-log again and from there I came to know that one of my databases is responsible for this. That database file won't let mysql start. So I deleted everything in the data folder and then in cmd I navigated to C:/xampp/mysql/bin path and ran these commands:

mysqld --initialize

mysql_install_db

and mysql started running again. But my databases and data are lost.

Modelling an elevator using Object-Oriented Analysis and Design

Donald Knuth's The Art of Computer Programming Vol.1 has a demonstration of elevator and the data-structures. Knuth presents a very thorough discussion and program.

Knuth(1997) "Information Structures", The Art of Computer Programming Vol. 1 pp.302-308

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Add the following css to disable the default scroll:

body {
    overflow: hidden;
}

And change the #content css to this to make the scroll only on content body:

#content {
    max-height: calc(100% - 120px);
    overflow-y: scroll;
    padding: 0px 10%;
    margin-top: 60px;
}

See fiddle here.


Edit:

Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  bottom: 30px;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 50px;_x000D_
}_x000D_
footer {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

try putting username in double quote "username", somehow that fixed for me.

How to implement the ReLU function in Numpy

numpy didn't have the function of relu, but you define it by yourself as follow:

def relu(x):
    return np.maximum(0, x)

for example:

arr = np.array([[-1,2,3],[1,2,3]])

ret = relu(arr)
print(ret) # print [[0 2 3] [1 2 3]]

High Quality Image Scaling Library

Use this library: http://imageresizing.net

Have a read of this article by the library author: 20 Image Sizing Pitfalls with .NET

Pointers in JavaScript?

It just doesn't support pointers, end of story :-(.

I would like to add that, while I'm brand new and coming from a C background, from what I'm reading about the event loop and stack, you should keep whichever object as close to its caller as possible. As I'm brand new, I could have this wrong.

A lot of answers here suggest to make it global, but again if I'm reading correctly, that could possibly increase the stack hops and in a way, possibly fragment your event loop needlessly (depending on what the called object is currently doing) .

Also, any example given that mimics pointers, is just 1 in many ways to do the same thing, which will not be a pointer.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax

How to change the docker image installation directory?

Following advice from comments I utilize Docker systemd documentation to improve this answer. Below procedure doesn't require reboot and is much cleaner.

First create directory and file for custom configuration:

sudo mkdir -p /etc/systemd/system/docker.service.d
sudo $EDITOR /etc/systemd/system/docker.service.d/docker-storage.conf

For docker version before 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --graph="/mnt"

For docker after 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// --data-root="/mnt"

Alternative method through daemon.json

I recently tried above procedure with 17.09-ce on Fedora 25 and it seem to not work. Instead of that simple modification in /etc/docker/daemon.json do the trick:

{
    "graph": "/mnt",
    "storage-driver": "overlay"
}

Despite the method you have to reload configuration and restart Docker:

sudo systemctl daemon-reload
sudo systemctl restart docker

To confirm that Docker was reconfigured:

docker info|grep "loop file"

In recent version (17.03) different command is required:

docker info|grep "Docker Root Dir"

Output should look like this:

 Data loop file: /mnt/devicemapper/devicemapper/data
 Metadata loop file: /mnt/devicemapper/devicemapper/metadata

Or:

 Docker Root Dir: /mnt

Then you can safely remove old Docker storage:

rm -rf /var/lib/docker

What is attr_accessor in Ruby?

Hmmm. Lots of good answers. Here is my few cents on it.

  • attr_accessor is a simple method that helps us in cleaning(DRY-ing) up the repeating getter and setter methods.

  • So that we can focus more on writing business logic and not worry about the setters and getters.

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

How can I make PHP display the error instead of giving me 500 Internal Server Error

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

Setting "checked" for a checkbox with jQuery

In jQuery,

if($("#checkboxId").is(':checked')){
    alert("Checked");
}

or

if($("#checkboxId").attr('checked')==true){
    alert("Checked");
}

In JavaScript,

if (document.getElementById("checkboxID").checked){
    alert("Checked");
}

Fixed footer in Bootstrap

To get a footer that sticks to the bottom of your viewport, give it a fixed position like this:

footer {
    position: fixed;
    height: 100px;
    bottom: 0;
    width: 100%;
}

Bootstrap includes this CSS in the Navbar > Placement section with the class fixed-bottom. Just add this class to your footer element:

<footer class="fixed-bottom">

Bootstrap docs: https://getbootstrap.com/docs/4.4/utilities/position/#fixed-bottom

how to include js file in php?

I tried this, I've got something like

script type="text/javascript" src="createDiv.php?id=" script

AND In createDiv.php I Have

document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';

And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld php variable was formatted cut and paste from the html page

But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.

Get UTC time and local time from NSDate object

At the moment (with the latest changes to Swift), NSDate.date() is not longer available.

Instead you just need to initialize NSDate and it gets the current date and time.
To try it, in a playground:

var d = NSDate()
d

and you will get:

Oct 22, 2014, 12:20 PM"  

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Add your Maven bin path to the System variable as given below

Go to the

> Enviornment Variables > set Path=D:\apache-maven-3.2.1\bin

or if path is already set than append the path with ";"

restart command and try

"webxml attribute is required" error in Maven

failOnMissingWebXml since 2020

All other answers about might be obsolete because the default value used by the maven-war-plugin changed:

Starting with 3.1.0, this property defaults to false if the project depends on the Servlet 3.0 API or newer.

So the ONLY thing you have to do is to add

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

Example:

<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>foo</groupId>
    <artifactId>bar</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <tomcat.ignorePackaging>true</tomcat.ignorePackaging>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Simplest code for array intersection in javascript

Hope this Helps for all versions.

function diffArray(arr1, arr2) {
  var newArr = [];

  var large = arr1.length>=arr2.length?arr1:arr2;
  var small = JSON.stringify(large) == JSON.stringify(arr1)?arr2:arr1;
  for(var i=0;i<large.length;i++){
    var copyExists = false; 
    for(var j =0;j<small.length;j++){
      if(large[i]==small[j]){
        copyExists= true;
        break;
      }
    }
    if(!copyExists)
      {
        newArr.push(large[i]);
      }
  }

  for(var i=0;i<small.length;i++){
    var copyExists = false; 
    for(var j =0;j<large.length;j++){
      if(large[j]==small[i]){
        copyExists= true;
        break;
      }
    }
    if(!copyExists)
      {
        newArr.push(small[i]);
      }
  }


  return newArr;
}

How do you connect localhost in the Android emulator?

you should change the adb port with this command:

adb reverse tcp:8880 tcp:8880; adb reverse tcp:8081 tcp:8081; adb reverse tcp:8881 tcp:8881

How do I UPDATE from a SELECT in SQL Server?

The following example uses a derived table, a SELECT statement after the FROM clause, to return the old and new values for further updates:

UPDATE x
SET    x.col1 = x.newCol1,
       x.col2 = x.newCol2
FROM   (SELECT t.col1,
               t2.col1 AS newCol1,
               t.col2,
               t2.col2 AS newCol2
        FROM   [table] t
               JOIN other_table t2
                 ON t.ID = t2.ID) x

How to open a link in new tab (chrome) using Selenium WebDriver?

The original poster is asking on how to open a link on a new tab. So this is how I have done it in C#.

        IWebDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://microsoft.com");
        IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
        Actions action = new Actions(driver);
        action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform(); 

This actually performs a Control+Click on the selected element in order to open the link in a new tab.

Storing a Key Value Array into a compact JSON string

To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.

{
    "keyvaluelist": {
        "slide0001.html": "Looking Ahead",
        "slide0008.html": "Forecast",
        "slide0021.html": "Summary"
    },
    "otherdata": {
        "one": "1",
        "two": "2",
        "three": "3"
    },
    "anotherthing": "thing1",
    "onelastthing": "thing2"
}

I read this as

a JSON object with four elements
    element 1 is a map of key/value pairs named "keyvaluelist",
    element 2 is a map of key/value pairs named "otherdata",
    element 3 is a string named "anotherthing",
    element 4 is a string named "onelastthing"

The first element or second element could alternatively be described as objects themselves, of course, with three elements each.

How to export JSON from MongoDB using Robomongo

An extension to Florian Winter answer for people looking to generate ready to execute query.

drop and insertMany query using cursor:

{
    // collection name
    var collection_name = 'foo';

    // query
    var cursor = db.getCollection(collection_name).find({});

    // drop collection and insert script
    print('db.' + collection_name + '.drop();');
    print('db.' + collection_name + '.insertMany([');

    // print documents
    while(cursor.hasNext()) {
        print(tojson(cursor.next()));

        if (cursor.hasNext()) // add trailing "," if not last item
            print(',');
    }

    // end script
    print(']);');
}

Its output will be like:

db.foo.drop();
db.foo.insertMany([
{
    "_id" : ObjectId("abc"),
    "name" : "foo"
}
,
{
    "_id" : ObjectId("xyz"),
    "name" : "bar"
}
]);

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

store and retrieve a class object in shared preference

I had the same problem, here's my solution:

I have class MyClass and ArrayList< MyClass > that I want to save to Shared Preferences. At first I've added a method to MyClass that converts it to JSON object:

public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("id", this.id);
        obj.put("name", this.name);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

Then here's the method for saving object "ArrayList< MyClass > items":

SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
    SharedPreferences.Editor editor = mPrefs.edit();

    Set<String> set= new HashSet<String>();
    for (int i = 0; i < items.size(); i++) {
        set.add(items.get(i).getJSONObject().toString());
    }

    editor.putStringSet("some_name", set);
    editor.commit();

And here's the method for retrieving the object:

public static ArrayList<MyClass> loadFromStorage() {
    SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);

    ArrayList<MyClass> items = new ArrayList<MyClass>();

    Set<String> set = mPrefs.getStringSet("some_name", null);
    if (set != null) {
        for (String s : set) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                Long id = jsonObject.getLong("id"));
                String name = jsonObject.getString("name");
                MyClass myclass = new MyClass(id, name);

                items.add(myclass);

            } catch (JSONException e) {
                e.printStackTrace();
         }
    }
    return items;
}

Note that StringSet in Shared Preferences is available since API 11.

Where does Android app package gets installed on phone

The package it-self is located under /data/app/com.company.appname-xxx.apk.

/data/app/com.company.appname is only a directory created to store files like native libs, cache, ecc...

You can retrieve the package installation path with the Context.getPackageCodePath() function call.

How to remove time portion of date in C# in DateTime object only?

Declare the variable as a string.

example :

public string dateOfBirth ;

then assign a value like :

dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();

How to go back (ctrl+z) in vi/vim

Here is a trick though. You can map the Ctrl+Z keys. This can be achieved by editing the .vimrc file. Add the following lines in the '.vimrc` file.

nnoremap <c-z> :u<CR>      " Avoid using this**
inoremap <c-z> <c-o>:u<CR>

This may not the a preferred way, but can be used.

** Ctrl+Z is used in Linux to suspend the ongoing program/process.

Should functions return null or an empty object?

I tend to

  • return null if the object id doesn't exist when it's not known beforehand whether it should exist.
  • throw if the object id doesn't exist when it should exist.

I differentiate these two scenarios with these three types of methods. First:

Boolean TryGetSomeObjectById(Int32 id, out SomeObject o)
{
    if (InternalIdExists(id))
    {
        o = InternalGetSomeObject(id);

        return true;
    }
    else
    {
        return false;
    }
}

Second:

SomeObject FindSomeObjectById(Int32 id)
{
    SomeObject o;

    return TryGetObjectById(id, out o) ? o : null;
}

Third:

SomeObject GetSomeObjectById(Int32 id)
{
    SomeObject o;

    if (!TryGetObjectById(id, out o))
    {
        throw new SomeAppropriateException();
    }

    return o;
}

Failed to execute 'atob' on 'Window'

Here I got the error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Because you didn't pass a base64-encoded string. Look at your functions: both download and dataURItoBlob do expect a data URI for some reason; you however are passing a plain html markup string to download in your example.

Not only is HTML invalid as base64, you are calling .split(',')[1] on it which will yield undefined - and "undefined" is not a valid base64-encoded string either.

I don't know, but I read that I need to encode my string to base64

That doesn't make much sense to me. You want to encode it somehow, only to decode it then?

What should I call and how?

Change the interface of your download function back to where it received the filename and text arguments.

Notice that the BlobBuilder does not only support appending whole strings (so you don't need to create those ArrayBuffer things), but also is deprecated in favor of the Blob constructor.

Can I put a name on my saved file?

Yes. Don't use the Blob constructor, but the File constructor.

function download(filename, text) {
    try {
        var file = new File([text], filename, {type:"text/plain"});
    } catch(e) {
        // when File constructor is not supported
        file = new Blob([text], {type:"text/plain"});
    }
    var url  = window.URL.createObjectURL(file);
    …
}

download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");

See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS verb and includes several headers, one of which being Access-Control-Request-Headers listing the headers the client wants to include in the request.

You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).

https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.

Multiple modals overlay

No script solutions , using only css given you have two layers of modals, set the 2nd modal to a higher z index

.second-modal { z-index: 1070 }

div.modal-backdrop + div.modal-backdrop {
   z-index: 1060; 
}

SQL Server Format Date DD.MM.YYYY HH:MM:SS

CONVERT(VARCHAR,GETDATE(),120)

Get product id and product type in magento?

$product=Mage::getModel('catalog/product')->load($product_id);

above code not working for me. its throw exception;

This is working for me for get product details.

$obj = Mage::getModel('catalog/product'); $_product = $obj->load($product_id);

So use for for product type.

$productType = $_product->getTypeId();

Easiest way to compare arrays in C#

You can use Enumerable.Intersect:

int[] array1 = new int[] { 1, 2, 3, 4,5 },
      array2 = new int[] {7,8};

if (array1.Intersect(array2).Any())
    Console.WriteLine("matched");
else
    Console.WriteLine("not matched");

Extracting text OpenCV

You can utilize a python implementation SWTloc.

Full Disclosure : I am the author of this library

To do that :-

First and Second Image

Notice that the text_mode here is 'lb_df', which stands for Light Background Dark Foreground i.e the text in this image is going to be in darker color than the background

from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow

swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths='img1.jpg', text_mode = 'lb_df',
                  save_results=True, save_rootpath = 'swtres/',
                  minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)

# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb  = respacket[5]

# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')

enter image description here enter image description here


enter image description here enter image description here

Third Image

Notice that the text_mode here is 'db_lf', which stands for Dark Background Light Foreground i.e the text in this image is going to be in lighter color than the background

from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow

swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths=imgpaths[1], text_mode = 'db_lf',
              save_results=True, save_rootpath = 'swtres/',
              minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)

# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb  = respacket[5]

# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')

enter image description here enter image description here

You will also notice that the grouping done is not so accurate, to get the desired results as the images might vary, try to tune the grouping parameters in swtl.get_grouped() function.

How to round the minute of a datetime object

I used Stijn Nevens code (thank you Stijn) and have a little add-on to share. Rounding up, down and rounding to nearest.

update 2019-03-09 = comment Spinxz incorporated; thank you.

update 2019-12-27 = comment Bart incorporated; thank you.

Tested for date_delta of "X hours" or "X minutes" or "X seconds".

import datetime

def round_time(dt=None, date_delta=datetime.timedelta(minutes=1), to='average'):
    """
    Round a datetime object to a multiple of a timedelta
    dt : datetime.datetime object, default now.
    dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
    from:  http://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python
    """
    round_to = date_delta.total_seconds()
    if dt is None:
        dt = datetime.now()
    seconds = (dt - dt.min).seconds

    if seconds % round_to == 0 and dt.microsecond == 0:
        rounding = (seconds + round_to / 2) // round_to * round_to
    else:
        if to == 'up':
            # // is a floor division, not a comment on following line (like in javascript):
            rounding = (seconds + dt.microsecond/1000000 + round_to) // round_to * round_to
        elif to == 'down':
            rounding = seconds // round_to * round_to
        else:
            rounding = (seconds + round_to / 2) // round_to * round_to

    return dt + datetime.timedelta(0, rounding - seconds, - dt.microsecond)

# test data
print(round_time(datetime.datetime(2019,11,1,14,39,00), date_delta=datetime.timedelta(seconds=30), to='up'))
print(round_time(datetime.datetime(2019,11,2,14,39,00,1), date_delta=datetime.timedelta(seconds=30), to='up'))
print(round_time(datetime.datetime(2019,11,3,14,39,00,776980), date_delta=datetime.timedelta(seconds=30), to='up'))
print(round_time(datetime.datetime(2019,11,4,14,39,29,776980), date_delta=datetime.timedelta(seconds=30), to='up'))
print(round_time(datetime.datetime(2018,11,5,14,39,00,776980), date_delta=datetime.timedelta(seconds=30), to='down'))
print(round_time(datetime.datetime(2018,11,6,14,38,59,776980), date_delta=datetime.timedelta(seconds=30), to='down'))
print(round_time(datetime.datetime(2017,11,7,14,39,15), date_delta=datetime.timedelta(seconds=30), to='average'))
print(round_time(datetime.datetime(2017,11,8,14,39,14,999999), date_delta=datetime.timedelta(seconds=30), to='average'))
print(round_time(datetime.datetime(2019,11,9,14,39,14,999999), date_delta=datetime.timedelta(seconds=30), to='up'))
print(round_time(datetime.datetime(2012,12,10,23,44,59,7769),to='average'))
print(round_time(datetime.datetime(2012,12,11,23,44,59,7769),to='up'))
print(round_time(datetime.datetime(2010,12,12,23,44,59,7769),to='down',date_delta=datetime.timedelta(seconds=1)))
print(round_time(datetime.datetime(2011,12,13,23,44,59,7769),to='up',date_delta=datetime.timedelta(seconds=1)))
print(round_time(datetime.datetime(2012,12,14,23,44,59),date_delta=datetime.timedelta(hours=1),to='down'))
print(round_time(datetime.datetime(2012,12,15,23,44,59),date_delta=datetime.timedelta(hours=1),to='up'))
print(round_time(datetime.datetime(2012,12,16,23,44,59),date_delta=datetime.timedelta(hours=1)))
print(round_time(datetime.datetime(2012,12,17,23,00,00),date_delta=datetime.timedelta(hours=1),to='down'))
print(round_time(datetime.datetime(2012,12,18,23,00,00),date_delta=datetime.timedelta(hours=1),to='up'))
print(round_time(datetime.datetime(2012,12,19,23,00,00),date_delta=datetime.timedelta(hours=1)))

Remove first 4 characters of a string with PHP

function String2Stars($string='',$first=0,$last=0,$rep='*'){
  $begin  = substr($string,0,$first);
  $middle = str_repeat($rep,strlen(substr($string,$first,$last)));
  $end    = substr($string,$last);
  $stars  = $begin.$middle.$end;
  return $stars;
}

example

$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5);   // abcde****************vwxyz

How to copy part of an array to another array in C#?

int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

How can I print the contents of an array horizontally?

You are probably using Console.WriteLine for printing the array.

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
    Console.WriteLine(item.ToString());
}

If you don't want to have every item on a separate line use Console.Write:

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
    Console.Write(item.ToString());
}

or string.Join<T> (in .NET Framework 4 or later):

int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));

How to set IE11 Document mode to edge as default?

I was having the same problem while developing my own website. While it was resident locally, resources opened as file//. For pages from the internet, including my own loaded as http://, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.

After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".

That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.

So if you are referring to using F12 for locally hosted files, this may help.

Android: how to make keyboard enter button say "Search" and handle its click?

by XML:

 <EditText
        android:id="@+id/search_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/search"
        android:imeOptions="actionSearch"
        android:inputType="text" />

By Java:

 editText.clearFocus();
    InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);

Get a particular cell value from HTML table using JavaScript

To get the text from this cell-

<table>
    <tr id="somerow">
        <td>some text</td>            
    </tr>
</table>

You can use this -

var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);

Python's time.clock() vs. time.time() accuracy?

I use this code to compare 2 methods .My OS is windows 8 , processor core i5 , RAM 4GB

import time

def t_time():
    start=time.time()
    time.sleep(0.1)
    return (time.time()-start)


def t_clock():
    start=time.clock()
    time.sleep(0.1)
    return (time.clock()-start)




counter_time=0
counter_clock=0

for i in range(1,100):
    counter_time += t_time()

    for i in range(1,100):
        counter_clock += t_clock()

print "time() =",counter_time/100
print "clock() =",counter_clock/100

output:

time() = 0.0993799996376

clock() = 0.0993572257367

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

If you don't want to change your Java version (I don't), you can temporarily change the version in your shell:

First run

/usr/libexec/java_home -V

Then pick a major version if you have it installed, otherwise install it first:

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`

Now you can run sdkmanager.

How can I implement prepend and append with regular JavaScript?

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.

insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.

Examples can be found here: Node.insertBefore

How to write a cursor inside a stored procedure in SQL Server 2008

Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses in the coupon table will be updated.

CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS

Declare     @couponCount int,
            @CouponName nvarchar(50),
            @couponIdFromQuery int


Declare curP cursor For

  select COUNT(*) as totalcount , Name as name,couponuse.couponid  as couponid from Coupon as coupon 
  join CouponUse as couponuse on coupon.id = couponuse.couponid
  where couponuse.id=@cuponId
  group by couponuse.couponid , coupon.Name

OPEN curP 
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

While @@Fetch_Status = 0 Begin

    print @couponCount
    print @CouponName

    update Coupon SET NoofUses=@couponCount
    where couponuse.id=@couponIdFromQuery


Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery

End -- End of Fetch

Close curP
Deallocate curP

Hope this helps!

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    How do I `jsonify` a list in Flask?

    josonify works..but if you intend to just pass an array without the 'results' key, you can use json library from python. The following conversion works for me..

     import json
    
     @app.route('/test/json')
     def test_json():
     list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
     return json.dumps(list))
    

    Android: show soft keyboard automatically when focus is on an EditText

    I know this question is old by I think using an extension function is a prettier way to show keyboard for an edit text

    here is the method I use to show keyboard for an edittext.

    kotlin code: just need to call edittext.showKeyboard()

    fun EditText.showKeyboard() {
      post {
        requestFocus()
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
      }
    }
    

    the java code:

    public static void showKeyboard(EditText editText) {
        editText.post(new Runnable() {
          @Override
          public void run() {
            editText.requestFocus();
            InputMethodManager imm = (InputMethodManager) editText.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
          }
        });
      }
    

    'Source code does not match the bytecode' when debugging on a device

    Here is my solution:

    If you got more than one library version, this may help.

    1. set a breakpoint on the lib source code
    2. let the code run to the breakpoint
    3. you will got these tips

    enter image description here

    1. click the arrow icon

    2. you will get this

      enter image description here

    3. double click to select the correct lib (normally the highest version of the lib is correct)

    I have clicked the "disable" button by mistake, you can enable it in the debugger setting

    enter image description here

    If you do not have the tips in the step 3, maybe you can check whether you have checked the setting options

    What are the differences between Deferred, Promise and Future in JavaScript?

    • A promise represents a value that is not yet known
    • A deferred represents work that is not yet finished

    A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.

    Reference

    Getting year in moment.js

    The year() function just retrieves the year component of the underlying Date object, so it returns a number.

    Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

    If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

    Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

    How to make an AJAX call without jQuery?

    You can get the correct object according to the browser with

    function getXmlDoc() {
      var xmlDoc;
    
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlDoc = new XMLHttpRequest();
      }
      else {
        // code for IE6, IE5
        xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
      }
    
      return xmlDoc;
    }
    

    With the correct object, a GET might can be abstracted to:

    function myGet(url, callback) {
      var xmlDoc = getXmlDoc();
    
      xmlDoc.open('GET', url, true);
    
      xmlDoc.onreadystatechange = function() {
        if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
          callback(xmlDoc);
        }
      }
    
      xmlDoc.send();
    }
    

    And a POST to:

    function myPost(url, data, callback) {
      var xmlDoc = getXmlDoc();
    
      xmlDoc.open('POST', url, true);
      xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
      xmlDoc.onreadystatechange = function() {
        if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
          callback(xmlDoc);
        }
      }
    
      xmlDoc.send(data);
    }
    

    Finding diff between current and last version

    to show individual changes in a commit, to head.

    git show Head~0
    

    to show accumulated changes in a commit, to head.

    git diff Head~0
    

    where 0 is the desired number of commits.

    Why doesn't Python have a sign function?

    In Python 2, cmp() returns an integer: there's no requirement that the result be -1, 0, or 1, so sign(x) is not the same as cmp(x,0).

    In Python 3, cmp() has been removed in favor of rich comparison. For cmp(), Python 3 suggests this:

    def cmp(a, b):
        return (a > b) - (a < b)
    

    which is fine for cmp(), but again can't be used for sign() because the comparison operators need not return booleans.

    To deal with this possibility, the comparison results must be coerced to booleans:

     def sign(x):
        return bool(x > 0) - bool(x < 0)
    

    This works for any type which is totally ordered (including special values like NaN or infinities).

    Why is Visual Studio 2013 very slow?

    This issue seems to be because of uninstalling the SQL Server Compact edition (4.0).

    I was having this issue, and it got fixed after installing the SQL Server Compact edition 4.0. On closing Visual Studio 2013, I was getting a message to install SQL Server Compact edition as a C++ project needed some thing... can't put finger on anything.

    Copy directory contents into a directory with python

    I found this code working:

    from distutils.dir_util import copy_tree
    
    # copy subdirectory example
    fromDirectory = "/a/b/c"
    toDirectory = "/x/y/z"
    
    copy_tree(fromDirectory, toDirectory)
    

    Reference:

    How to efficiently use try...catch blocks in PHP

    There is no reason against using a single block for multiple operations, since any thrown exception will prevent the execution of further operations after the failed one. At least as long as you can conclude which operation failed from the exception caught. That is as long as it is fine if some operations are not processed.

    However I'd say that returning the exception makes only limited sense. A return value of a function should be the expected result of some action, not the exception. If you need to react on the exception in the calling scope then either do not catch the exception here inside your function, but in the calling scope or re-throw the exception for later processing after having done some debug logging and the like.

    HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

    if you are using tomcat you may try this

    <servlet-mapping>
    
        <http-method>POST</http-method>
    
    </servlet-mapping>
    

    in addition to <servlet-name> and <url-mapping>

    getting the table row values with jquery

    All Elements

    $('#tabla > tbody  > tr').each(function() {
        $(this).find("td:gt(0)").each(function(){
           alert($(this).html());
           });
    });
    

    Build unsigned APK file with Android Studio

    Android studio also create the apk file on every time compile the program, just go to your workspace folder and find app->build->outputs-> then you can see the apk file.

    how to extract only the year from the date in sql server 2008?

    year(@date)
    year(getdate())
    year('20120101')
    
    update table
    set column = year(date_column)
    whre ....
    

    or if you need it in another table

     update t
       set column = year(t1.date_column)
         from table_source t1
         join table_target t on (join condition)
        where ....
    

    Python NameError: name is not defined

    You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

    You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

    Make function definition in a python file order independent

    opening html from google drive

    1. Create a new folder in Drive and share it as "Public on the web."
    2. Upload your HTML, JS & CSS files to this folder.
    3. Open the HTML file & you will see "Preview" button in the toolbar.
    4. Share the URL that looks like www.googledrive.com/host/... from the preview window and anyone can view your web page.

    How to programmatically connect a client to a WCF service?

    You can also do what the "Service Reference" generated code does

    public class ServiceXClient : ClientBase<IServiceX>, IServiceX
    {
        public ServiceXClient() { }
    
        public ServiceXClient(string endpointConfigurationName) :
            base(endpointConfigurationName) { }
    
        public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress) { }
    
        public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress) { }
    
        public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
            base(binding, remoteAddress) { }
    
        public bool ServiceXWork(string data, string otherParam)
        {
            return base.Channel.ServiceXWork(data, otherParam);
        }
    }
    

    Where IServiceX is your WCF Service Contract

    Then your client code:

    var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
    client.ServiceXWork("data param", "otherParam param");
    

    Add 10 seconds to a Date

    Try this way.

    Date.prototype.addSeconds = function(seconds) {
      var copiedDate = new Date(this.getTime());
      return new Date(copiedDate.getTime() + seconds * 1000);
    }
    

    Just call and assign new Date().addSeconds(10)