Programs & Examples On #Jqgrid php

Description Tag for the PHP wrapper of jqGrid. For more information, visit: http://www.trirand.net/default.aspx

How can I add a username and password to Jenkins?

If installed as an admin, use:-

uname - admin
pw - the passkey that was generated during installation

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.

PS c:\temp> $global:test="one"

PS c:\temp> $test
one

PS c:\temp> function changet() {$global:test="two"}

PS c:\temp> changet

PS c:\temp> $test
two

His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:

PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}

PS c:\temp> changet 1 2 3

PS c:\temp> $test
3
3
4

PS C:\nb> $test[2]
4

I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)

Slack clean all messages (~8K) in a channel

Here is a great chrome extension to bulk delete your slack channel/group/im messages - https://slackext.com/deleter , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.

Python import csv to list

Updated for Python 3:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print(your_list)

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

Choosing the best concurrency list in Java

If set is sufficient, ConcurrentSkipListSet might be used. (Its implementation is based on ConcurrentSkipListMap which implements a skip list.)

The expected average time cost is log(n) for the contains, add, and remove operations; the size method is not a constant-time operation.

How to secure phpMyAdmin

Most likely, somewhere on your webserver will be an Alias directive like this;

Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"

In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.

Just change the alias directive and you should be good to go.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

How to show "if" condition on a sequence diagram?

If else condition, also called alternatives in UML terms can indeed be represented in sequence diagrams. Here is a link where you can find some nice resources on the subject http://www.ibm.com/developerworks/rational/library/3101.html

branching with alt

Change table header color using bootstrap

//use css
.blue {
    background-color:blue !important;
}
.blue th {
    color:white !important;
}

//html
<table class="table blue">.....</table>

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!ADPAction.Value.ToString().ToUpper().Contains("FAIL"),"Red","White")

Also need to convert to upper case for comparision is binary test.

How to install Visual C++ Build tools?

I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.

enter image description here

I hope it helps save others time!

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:

  1. There are no scroll bars to let the user know that they can scroll
  2. Users have to use two-finger scrolling
  3. The PDF files are not centered (still working on it)

    <!DOCTYPE HTML>
    <html>
    <head>
      <title>Testing iFrames on iPad</title>
      <style>
      div {
        border: solid 1px green;
        height:100px;
      }
    
    .scroller{
        border:solid 1px #66AA66;
        height: 400px;
        width: 400px;
        overflow: auto;
        text-align:center;
    
    }
    </style>
    

    <table>
      <tr>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
      <tr>
      <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
    </table>
    <div> Here are some additional contents.</div>
    

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-

Second.h:

void second();
int third();
double fourth();

main.cpp:

#include <iostream>
#include "second.h"
int main()
{
    //.....
    return 0;
}

second.cpp:

void second()
{
    //...
}

int third()
{ 
    //...
    return foo;
}

double fourth()
{ 
    //...
    return f;
}

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

Spring MVC - How to get all request params in a map in Spring controller?

@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
    jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

All params will be stored in jsonObject.

Cannot kill Python script with Ctrl-C

I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.

import threading
import time

class MyThread (threading.Thread):
    die = False
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run (self):
        while not self.die:
            time.sleep(1)
            print (self.name)

    def join(self):
        self.die = True
        super().join()

if __name__ == '__main__':
    f = MyThread('first')
    f.start()
    s = MyThread('second')
    s.start()
    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        f.join()
        s.join()

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

How to use moment.js library in angular 2 typescript app?

The following worked for me:

typings install dt~moment-node --save --global

The moment-node does not exist in typings repository. You need to redirect to Definitely Typed in order to make it work using the prefix dt.

The SQL OVER() clause - when and why is it useful?

The OVER clause when combined with PARTITION BY state that the preceding function call must be done analytically by evaluating the returned rows of the query. Think of it as an inline GROUP BY statement.

OVER (PARTITION BY SalesOrderID) is stating that for SUM, AVG, etc... function, return the value OVER a subset of the returned records from the query, and PARTITION that subset BY the foreign key SalesOrderID.

So we will SUM every OrderQty record for EACH UNIQUE SalesOrderID, and that column name will be called 'Total'.

It is a MUCH more efficient means than using multiple inline views to find out the same information. You can put this query within an inline view and filter on Total then.

SELECT ...,
FROM (your query) inlineview
WHERE Total < 200

Which command in VBA can count the number of characters in a string variable?

Do you mean counting the number of characters in a string? That's very simple

Dim strWord As String
Dim lngNumberOfCharacters as Long

strWord = "habit"
lngNumberOfCharacters = Len(strWord)
Debug.Print lngNumberOfCharacters

Find index of a value in an array

int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created

Java: Detect duplicates in ArrayList?

With Java 8+ you can use Stream API:

boolean areAllDistinct(List<Block> blocksList) {
    return blocksList.stream().map(Block::getNum).distinct().count() == blockList.size();
}

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

Adding a simple UIAlertView

Here is a complete method that only has one button, an 'ok', to close the UIAlert:

- (void) myAlert: (NSString*)errorMessage
{
    UIAlertView *myAlert = [[UIAlertView alloc]
                          initWithTitle:errorMessage
                          message:@""
                          delegate:self
                          cancelButtonTitle:nil
                          otherButtonTitles:@"ok", nil];
    myAlert.cancelButtonIndex = -1;
    [myAlert setTag:1000];
    [myAlert show];
}

Spring Boot - Loading Initial Data

If I just want to insert simple test data I often implement a ApplicationRunner. Implementations of this interface are run at application startup and can use e.g. a autowired repository to insert some test data.

I think such an implementation would be slightly more explicit than yours because the interface implies that your implementation contains something you would like to do directly after your application is ready.

Your implementation would look sth. like this:

@Component
public class DataLoader implements ApplicationRunner {

    private UserRepository userRepository;

    @Autowired
    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void run(ApplicationArguments args) {
        userRepository.save(new User("lala", "lala", "lala"));
    }
}

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

Remove an item from a dictionary when its key is unknown

items() returns a list, and it is that list you are iterating, so mutating the dict in the loop doesn't matter here. If you were using iteritems() instead, mutating the dict in the loop would be problematic, and likewise for viewitems() in Python 2.7.

I can't think of a better way to remove items from a dict by value.

How to select data of a table from another database in SQL Server?

To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.

Once the server is linked you can run a query against it.

How to position text over an image in css

For a responsive design it is good to use a container having a relative layout and content (placed in container) having fixed layout as.

CSS Styles:

/*Centering element in a base container*/

.contianer-relative{ 
  position: relative;
 }

.content-center-text-absolute{ 
  position: absolute; 
  text-align: center;
  width: 100%;
  height: 0%;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 51;
}

HTML code:

<!-- Have used ionic classes -->
<div class="row">
    <div class="col remove-padding contianer-relative"><!-- container with position relative -->
        <div class="item item-image clear-border" ><a href="#"><img ng-src="img/engg-manl.png" alt="ENGINEERING MANUAL" title="ENGINEERING MANUAL" ></a></div> <!-- Image intended to work as a background -->
        <h4 class="content-center-text-absolute white-text"><strong>ENGINEERING <br> MANUALS</strong></h4><!-- content div with position fixed -->
    </div>
    <div class="col remove-padding contianer-relative"><!-- container with position relative -->
        <div class="item item-image clear-border"><a href="#"><img ng-src="img/contract-directory.png" alt="CONTRACTOR DIRECTORY" title="CONTRACTOR DIRECTORY"></a></div><!-- Image intended to work as a background -->
        <h4 class="content-center-text-absolute white-text"><strong>CONTRACTOR <br> DIRECTORY</strong></h4><!-- content div with position fixed -->
    </div>       
</div>

For IONIC Grid layout, evenly spaced grid elements and the classes used in above HTML, please refer - Grid: Evenly Spaced Columns. Hope it helps you out... :)

HTTP Ajax Request via HTTPS Page

Make a bypass API in server.js. This works for me.

app.post('/by-pass-api',function(req, response){
  const url = req.body.url;
  console.log("calling url", url);
  request.get(
    url,
    (error, res, body) => {
      if (error) {
        console.error(error)
        return response.status(200).json({'content': "error"}) 
}
        return response.status(200).json(JSON.parse(body))
        },
      )
    })

And call it using axios or fetch like this:

const options = {
     method: 'POST',
     headers: {'content-type': 'application/json'},
     url:`http://localhost:3000/by-pass-api`, // your environment 
     data: { url },  // your https request here
    };

Angularjs loading screen on ajax request

You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

angular.module('directive.loading', [])
        .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isNoLoadingForced = false;
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                    };

                    $rootScope.$on('stopLoader', function(){
                        scope.isNoLoadingForced = true;
                    })

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);

This is definatly not the best solution but it would still works.

Fixed digits after decimal with f-strings

a = 10.1234

print(f"{a:0.2f}")

in 0.2f:

  • 0 is telling python to put no limit on the total number of digits to display
  • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
  • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

Python int to binary string?

Python actually does have something already built in for this, the ability to do operations such as '{0:b}'.format(42), which will give you the bit pattern (in a string) for 42, or 101010.


For a more general philosophy, no language or library will give its user base everything that they desire. If you're working in an environment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example, the pseudo-code:

define intToBinString, receiving intVal:
    if intVal is equal to zero:
        return "0"
    set strVal to ""
    while intVal is greater than zero:
        if intVal is odd:
            prefix "1" to strVal
        else:
            prefix "0" to strVal
        divide intVal by two, rounding down
    return strVal

which will construct your binary string based on the decimal value. Just keep in mind that's a generic bit of pseudo-code which may not be the most efficient way of doing it though, with the iterations you seem to be proposing, it won't make much difference. It's really just meant as a guideline on how it could be done.

The general idea is to use code from (in order of preference):

  • the language or built-in libraries.
  • third-party libraries with suitable licenses.
  • your own collection.
  • something new you need to write (and save in your own collection for later).

move_uploaded_file gives "failed to open stream: Permission denied" error

I have tried all the solutions above, but the following solved my problem

chcon -R -t httpd_sys_rw_content_t your_file_directory

Invalid hook call. Hooks can only be called inside of the body of a function component

My case.... SOLUTION in HOOKS

const [cep, setCep] = useState('');
const mounted = useRef(false);

useEffect(() => {
    if (mounted.current) {
        fetchAPI();
      } else {
        mounted.current = true;
      }
}, [cep]);

const setParams = (_cep) => {
    if (cep !== _cep || cep === '') {
        setCep(_cep);
    }
};

Java: how to use UrlConnection to post request with authorization?

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

Why Would I Ever Need to Use C# Nested Classes

There is good uses of public nested members too...

Nested classes have access to the private members of the outer class. So a scenario where this is the right way would be when creating a Comparer (ie. implementing the IComparer interface).

In this example, the FirstNameComparer has access to the private _firstName member, which it wouldn't if the class was a separate class...

public class Person
{
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    //...
    
    public class FirstNameComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x._firstName.CompareTo(y._firstName);
        }
    }
}

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

iframe to Only Show a Certain Part of the Page

An <iframe> gives you a complete window to work with. The most direct way to do what you want is to have your server give you a complete page that only contains the fragment you want to show.

As an alternative, you could just use a simple <div> and use the jQuery "load" function to load the whole page and pluck out just the section you want:

$('#target-div').load('http://www.mywebsite.com/portfolio.php #portfolio-sports');

There may be other things you need to do, and a significant difference is that the content will become part of the main page instead of being segregated into a separate window.

Update Multiple Rows in Entity Framework from a list of ids

I have created a library to batch delete or update records with a round trip on EF Core 5.

Sample code as follows:

await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");

await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();

Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/

Free space in a CMD shell

df.exe

Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.

You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.

df -h will show all your drive's used and available disk space. For example:

M:\>df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/cygwin/bin   932G   78G  855G   9% /usr/bin
C:/cygwin/lib   932G   78G  855G   9% /usr/lib
C:/cygwin       932G   78G  855G   9% /
C:              932G   78G  855G   9% /cygdrive/c
E:              1.9T  1.3T  621G  67% /cygdrive/e
F:              1.9T  201G  1.7T  11% /cygdrive/f
H:              1.5T  524G  938G  36% /cygdrive/h
M:              1.5T  524G  938G  36% /cygdrive/m
P:               98G   67G   31G  69% /cygdrive/p
R:               98G   14G   84G  15% /cygdrive/r

Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:

M:\>df -h | grep M: | awk '{print $4}'

SQL Server principal "dbo" does not exist,

As the message said, you should set permission as owner to your user. So you can use following:

ALTER AUTHORIZATION 
ON DATABASE::[YourDBName]
TO [UserLogin];

Hope helpful! Leave comment if it's ok for you.

What is the size of ActionBar in pixels?

From the de-compiled sources of Android 3.2's framework-res.apk, res/values/styles.xml contains:

<style name="Theme.Holo">
    <!-- ... -->
    <item name="actionBarSize">56.0dip</item>
    <!-- ... -->
</style>

3.0 and 3.1 seem to be the same (at least from AOSP)...

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Listing all the folders subfolders and files in a directory using php

function listFolderFiles($dir){
    $ffs = scandir($dir);

    unset($ffs[array_search('.', $ffs, true)]);
    unset($ffs[array_search('..', $ffs, true)]);

    // prevent empty ordered elements
    if (count($ffs) < 1)
        return;

    echo '<ol>';
    foreach($ffs as $ff){
        echo '<li>'.$ff;
        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
        echo '</li>';
    }
    echo '</ol>';
}

listFolderFiles('Main Dir');

notifyDataSetChanged example

I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged() in the right place.

So my situation was as follows.

I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged() of the action bar adapter in the code of the activity which had to return the data.

This is the code snippet which I used in the activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) 
    {
        case R.id.action_new_forward:

            FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
            Intent ina = new Intent(getApplicationContext(), MainActivity.class);
            ina.putExtra("stra", values1);
            startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
    }
}

This activity would return some data to FragmentTab2 and it would directly update my listview in FragmentTab2.

Hope someone finds this useful!

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

Saving to CSV in Excel loses regional date format

Change the date range to "General" format and save the workbook once, and change them back to date format (eg, numberformat = "d/m/yyyy") before save & close the book. savechanges parameter is true.

ImportError: cannot import name

When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a

import importlib

and

importlib.reload (*module*)

likely to solve your problem

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to download file in swift?

Example downloader class without Alamofire:

class Downloader {
    class func load(URL: NSURL) {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = "GET"
        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as NSHTTPURLResponse).statusCode
                println("Success: \(statusCode)")

                // This is your file-variable:
                // data
            }
            else {
                // Failure
                println("Failure: %@", error.localizedDescription);
            }
        })
        task.resume()
    }
}

This is how to use it in your own code:

class Foo {
    func bar() {
        if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
            Downloader.load(URL)
        }
    }
}

Swift 3 Version

Also note to download large files on disk instead instead in memory. see `downloadTask:

class Downloader {
    class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = try! URLRequest(url: url, method: .get)

        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Success: \(statusCode)")
                }

                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
                    completion()
                } catch (let writeError) {
                    print("error writing file \(localUrl) : \(writeError)")
                }

            } else {
                print("Failure: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }
}

MySQL table is marked as crashed and last (automatic?) repair failed

If this happend to your XAMPP installation, just copy global_priv.MAD and global_priv.MAI files from ./xampp/mysql/backup/mysql/ to ./xampp/mysql/data/mysql/.

Difference between numeric, float and decimal in SQL Server

Guidelines from MSDN: Using decimal, float, and real Data

The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified.

The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.

How to download fetch response in react as file

Browser technology currently doesn't support downloading a file directly from an Ajax request. The work around is to add a hidden form and submit it behind the scenes to get the browser to trigger the Save dialog.

I'm running a standard Flux implementation so I'm not sure what the exact Redux (Reducer) code should be, but the workflow I just created for a file download goes like this...

  1. I have a React component called FileDownload. All this component does is render a hidden form and then, inside componentDidMount, immediately submit the form and call it's onDownloadComplete prop.
  2. I have another React component, we'll call it Widget, with a download button/icon (many actually... one for each item in a table). Widget has corresponding action and store files. Widget imports FileDownload.
  3. Widget has two methods related to the download: handleDownload and handleDownloadComplete.
  4. Widget store has a property called downloadPath. It's set to null by default. When it's value is set to null, there is no file download in progress and the Widget component does not render the FileDownload component.
  5. Clicking the button/icon in Widget calls the handleDownload method which triggers a downloadFile action. The downloadFile action does NOT make an Ajax request. It dispatches a DOWNLOAD_FILE event to the store sending along with it the downloadPath for the file to download. The store saves the downloadPath and emits a change event.
  6. Since there is now a downloadPath, Widget will render FileDownload passing in the necessary props including downloadPath as well as the handleDownloadComplete method as the value for onDownloadComplete.
  7. When FileDownload is rendered and the form is submitted with method="GET" (POST should work too) and action={downloadPath}, the server response will now trigger the browser's Save dialog for the target download file (tested in IE 9/10, latest Firefox and Chrome).
  8. Immediately following the form submit, onDownloadComplete/handleDownloadComplete is called. This triggers another action that dispatches a DOWNLOAD_FILE event. However, this time downloadPath is set to null. The store saves the downloadPath as null and emits a change event.
  9. Since there is no longer a downloadPath the FileDownload component is not rendered in Widget and the world is a happy place.

Widget.js - partial code only

import FileDownload from './FileDownload';

export default class Widget extends Component {
    constructor(props) {
        super(props);
        this.state = widgetStore.getState().toJS();
    }

    handleDownload(data) {
        widgetActions.downloadFile(data);
    }

    handleDownloadComplete() {
        widgetActions.downloadFile();
    }

    render() {
        const downloadPath = this.state.downloadPath;

        return (

            // button/icon with click bound to this.handleDownload goes here

            {downloadPath &&
                <FileDownload
                    actionPath={downloadPath}
                    onDownloadComplete={this.handleDownloadComplete}
                />
            }
        );
    }

widgetActions.js - partial code only

export function downloadFile(data) {
    let downloadPath = null;

    if (data) {
        downloadPath = `${apiResource}/${data.fileName}`;
    }

    appDispatcher.dispatch({
        actionType: actionTypes.DOWNLOAD_FILE,
        downloadPath
    });
}

widgetStore.js - partial code only

let store = Map({
    downloadPath: null,
    isLoading: false,
    // other store properties
});

class WidgetStore extends Store {
    constructor() {
        super();
        this.dispatchToken = appDispatcher.register(action => {
            switch (action.actionType) {
                case actionTypes.DOWNLOAD_FILE:
                    store = store.merge({
                        downloadPath: action.downloadPath,
                        isLoading: !!action.downloadPath
                    });
                    this.emitChange();
                    break;

FileDownload.js
- complete, fully functional code ready for copy and paste
- React 0.14.7 with Babel 6.x ["es2015", "react", "stage-0"]
- form needs to be display: none which is what the "hidden" className is for

import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';

function getFormInputs() {
    const {queryParams} = this.props;

    if (queryParams === undefined) {
        return null;
    }

    return Object.keys(queryParams).map((name, index) => {
        return (
            <input
                key={index}
                name={name}
                type="hidden"
                value={queryParams[name]}
            />
        );
    });
}

export default class FileDownload extends Component {

    static propTypes = {
        actionPath: PropTypes.string.isRequired,
        method: PropTypes.string,
        onDownloadComplete: PropTypes.func.isRequired,
        queryParams: PropTypes.object
    };

    static defaultProps = {
        method: 'GET'
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).submit();
        this.props.onDownloadComplete();
    }

    render() {
        const {actionPath, method} = this.props;

        return (
            <form
                action={actionPath}
                className="hidden"
                method={method}
            >
                {getFormInputs.call(this)}
            </form>
        );
    }
}

How do I kill this tomcat process in Terminal?

Tomcat is not running. Your search is showing you the grep process, which is searching for tomcat. Of course, by the time you see that output, grep is no longer running, so the pid is no longer valid.

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

Download a file from HTTPS using download.file()

Offering the curl package as an alternative that I found to be reliable when extracting large files from an online database. In a recent project, I had to download 120 files from an online database and found it to half the transfer times and to be much more reliable than download.file.

#install.packages("curl")
library(curl)
#install.packages("RCurl")
library(RCurl)

ptm <- proc.time()
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
proc.time() - ptm
ptm

ptm1 <- proc.time()
curl_download(url =URL ,destfile="TEST.CSV",quiet=FALSE, mode="wb")
proc.time() - ptm1
ptm1

ptm2 <- proc.time()
y = download.file(URL, destfile = "./data/data.csv", method="curl")
proc.time() - ptm2
ptm2

In this case, rough timing on your URL showed no consistent difference in transfer times. In my application, using curl_download in a script to select and download 120 files from a website decreased my transfer times from 2000 seconds per file to 1000 seconds and increased the reliability from 50% to 2 failures in 120 files. The script is posted in my answer to a question I asked earlier, see .

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

How to disable GCC warnings for a few lines of code

#pragma GCC diagnostic ignored "-Wformat"

Replace "-Wformat" with the name of your warning flag.

AFAIK there is no way to use push/pop semantics for this option.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

PHP: If internet explorer 6, 7, 8 , or 9

You can as well look into PHP's get_browser(); http://php.net/manual/en/function.get-browser.php

Maybe you'll find it useful for more features.

Is it possible to decompile a compiled .pyc file into a .py file?

Yes.

I use uncompyle6 decompile (even support latest Python 3.8.0):

uncompyle6 utils.cpython-38.pyc > utils.py

and the origin python and decompiled python comparing look like this:

pyc uncompile utils

so you can see, ALMOST same, decompile effect is VERY GOOD.

How to read data from a zip file without having to unzip the entire file

In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).

How can I move HEAD back to a previous location? (Detached head) & Undo commits

This may not be a technical solution, but it works. (if anyone of your teammate has the same branch in local)

Let's assume your branch name as branch-xxx.

Steps to Solve:

  • Don't do update or pull - nothing
  • Just create a new branch (branch-yyy) from branch-xxx on his machine
  • That's all, all your existing changes will be in this new branch (branch-yyy). You can continue your work with this branch.

Note: Again, this is not a technical solution, but it will help for sure.

Diff files present in two different directories

Try this:

diff -rq /path/to/folder1 /path/to/folder2      

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

Node.js create folder or use existing

You can use this:

if(!fs.existsSync("directory")){
    fs.mkdirSync("directory", 0766, function(err){
        if(err){
            console.log(err);
            // echo the result back
            response.send("ERROR! Can't make the directory! \n");
        }
    });
}

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

You need to make sure if package.json file exist in app folder. i run into same problem differently but solution would be same

Run this command where "package.json" file exist. even i experience similar problem then i change the folder and got resolve it. for more explanation i run c:\selfPractice> npm start whereas my package.json resides in c:\selfPractice\frontend> then i change the folder and run c:\selfPractice\frontend> npm start and it got run

How to navigate through textfields (Next / Done Buttons)

This is a simple solution in swift, with no tag using, no storyboard tricks...

Just use this extension :

extension UITextField{

    func nextTextFieldField() -> UITextField?{
        //field to return
        var returnField : UITextField?
        if self.superview != nil{
            //for each view in superview
            for (_, view) in self.superview!.subviews.enumerate(){
                //if subview is a text's field
                if view.isKindOfClass(UITextField){
                    //cast curent view as text field
                    let currentTextField = view as! UITextField
                    //if text field is after the current one
                    if currentTextField.frame.origin.y > self.frame.origin.y{
                        //if there is no text field to return already
                        if returnField == nil {
                            //set as default return
                            returnField = currentTextField
                        }
                            //else if this this less far than the other
                        else if currentTextField.frame.origin.y < returnField!.frame.origin.y{
                            //this is the field to return
                            returnField = currentTextField
                        }
                    }
                }
            }
        }
        //end of the mdethod
        return returnField
    }

}

And call it like this (for example) with your textfield delegate:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    textField.nextTextFieldField()?.becomeFirstResponder()
    return true
}

getOutputStream() has already been called for this response

In some cases this case occurs when you declare

Writer out=response.getWriter   

after declaring or using RequestDispatcher.

I encountered this similar problem while creating a simple LoginServlet, where I have defined Writer after declaring RequestDispatcher.

Try defining Writer class object before RequestDispatcher class.

Showing empty view when ListView is empty

First check the list contains some values:

if (list.isEmpty()) {
    listview.setVisibility(View.GONE);
}

If it is then OK, otherwise use:

else {
     listview.setVisibility(View.VISIBLE);
}

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

String Concatenation in EL

it also can be a great idea using concat for EL + MAP + JSON problem like in this example :

#{myMap[''.concat(myid)].content}

Java 8 LocalDate Jackson format

If your request contains an object like this:

{
    "year": 1900,
    "month": 1,
    "day": 20
}

Then you can use:

data class DateObject(
    val day: Int,
    val month: Int,
    val year: Int
)
class LocalDateConverter : StdConverter<DateObject, LocalDate>() {
    override fun convert(value: DateObject): LocalDate {
        return value.run { LocalDate.of(year, month, day) }
    }
}

Above the field:

@JsonDeserialize(converter = LocalDateConverter::class)
val dateOfBirth: LocalDate

The code is in Kotlin but this would work for Java too of course.

jquery find element by specific class when element has multiple classes

You can combine selectors like this

$(".alert-box.warn, .alert-box.dead");

Or if you want a wildcard use the attribute-contains selector

$("[class*='alert-box']");

Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.

$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");

Get length of array?

Try CountA:

Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

Java multiline string

A simple option is to edit your java-code with an editor like SciTE (http://www.scintilla.org/SciTEDownload.html), which allows you to WRAP the text so that long strings are easily viewed and edited. If you need escape characters you just put them in. By flipping the wrap-option off you can check that your string indeed is still just a long single-line string. But of course, the compiler will tell you too if it isn't.

Whether Eclipse or NetBeans support text-wrapping in an editor I don't know, because they have so many options. But if not, that would be a good thing to add.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

How to get Linux console window width in Python

I was trying the solution from here that calls out to stty size:

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that "stdin isn't a terminal" in that case.

I was able to make it work like this:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Here is a way to do it while passing in an extra argument:

https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

With the backend:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

.


And yet another way with an in-template filter only:

https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)

<div ng:app>
  <div ng-controller="HelloCntl">
    <ul>
       <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
            <span>{{friend.name}}</span>
            <span>{{friend.phone}}</span>
        </li>
    </ul>
</div>

You are trying to add a non-nullable field 'new_field' to userprofile without a default

Do you already have database entries in the table UserProfile? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL. Therefore it asks you what you want to set those fields in the column new_fields to. I had to delete all the rows from this table to solve the problem.

(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

How to draw a rectangle around a region of interest in python

You can use cv2.rectangle():

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)

Draws a simple, thick, or filled up-right rectangle.

The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.

Parameters
    img   Image.
    pt1   Vertex of the rectangle.
    pt2    Vertex of the rectangle opposite to pt1 .
    color Rectangle color or brightness (grayscale image).
    thickness  Thickness of lines that make up the rectangle. Negative values,
    like CV_FILLED , mean that the function has to draw a filled rectangle.
    lineType  Type of the line. See the line description.
    shift   Number of fractional bits in the point coordinates.

I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)

How can I change an element's class with JavaScript?

classList DOM API:

A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

_x000D_
_x000D_
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
_x000D_
_x000D_

We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

Example:

_x000D_
_x000D_
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
   el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
     el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
       el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
  background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
  border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
  "Sed ut perspiciatis unde omnis _x000D_
  iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
  totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
  quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
  voluptatem quia voluptas _x000D_
 </div>_x000D_
  _x000D_
<button onclick="addClass()">AddClass</button>_x000D_
  _x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
  _x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Overwriting my local branch with remote branch

first, create a new branch in the current position (in case you need your old 'screwed up' history):

git branch fubar-pin

update your list of remote branches and sync new commits:

git fetch --all

then, reset your branch to the point where origin/branch points to:

git reset --hard origin/branch

be careful, this will remove any changes from your working tree!

How to use Collections.sort() in Java?

Sort the unsorted hashmap in ascending order.

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

Find a private field with Reflection?

Here is some extension methods for simple get and set private fields and properties (properties with setter):

usage example:

    public class Foo
    {
        private int Bar = 5;
    }

    var targetObject = new Foo();
    var barValue = targetObject.GetMemberValue("Bar");//Result is 5
    targetObject.SetMemberValue("Bar", 10);//Sets Bar to 10

Code:

    /// <summary>
    /// Extensions methos for using reflection to get / set member values
    /// </summary>
    public static class ReflectionExtensions
    {
        /// <summary>
        /// Gets the public or private member using reflection.
        /// </summary>
        /// <param name="obj">The source target.</param>
        /// <param name="memberName">Name of the field or property.</param>
        /// <returns>the value of member</returns>
        public static object GetMemberValue(this object obj, string memberName)
        {
            var memInf = GetMemberInfo(obj, memberName);

            if (memInf == null)
                throw new System.Exception("memberName");

            if (memInf is System.Reflection.PropertyInfo)
                return memInf.As<System.Reflection.PropertyInfo>().GetValue(obj, null);

            if (memInf is System.Reflection.FieldInfo)
                return memInf.As<System.Reflection.FieldInfo>().GetValue(obj);

            throw new System.Exception();
        }

        /// <summary>
        /// Gets the public or private member using reflection.
        /// </summary>
        /// <param name="obj">The target object.</param>
        /// <param name="memberName">Name of the field or property.</param>
        /// <returns>Old Value</returns>
        public static object SetMemberValue(this object obj, string memberName, object newValue)
        {
            var memInf = GetMemberInfo(obj, memberName);


            if (memInf == null)
                throw new System.Exception("memberName");

            var oldValue = obj.GetMemberValue(memberName);

            if (memInf is System.Reflection.PropertyInfo)
                memInf.As<System.Reflection.PropertyInfo>().SetValue(obj, newValue, null);
            else if (memInf is System.Reflection.FieldInfo)
                memInf.As<System.Reflection.FieldInfo>().SetValue(obj, newValue);
            else
                throw new System.Exception();

            return oldValue;
        }

        /// <summary>
        /// Gets the member info
        /// </summary>
        /// <param name="obj">source object</param>
        /// <param name="memberName">name of member</param>
        /// <returns>instanse of MemberInfo corresponsing to member</returns>
        private static System.Reflection.MemberInfo GetMemberInfo(object obj, string memberName)
        {
            var prps = new System.Collections.Generic.List<System.Reflection.PropertyInfo>();

            prps.Add(obj.GetType().GetProperty(memberName,
                                               System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance |
                                               System.Reflection.BindingFlags.FlattenHierarchy));
            prps = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where( prps,i => !ReferenceEquals(i, null)));
            if (prps.Count != 0)
                return prps[0];

            var flds = new System.Collections.Generic.List<System.Reflection.FieldInfo>();

            flds.Add(obj.GetType().GetField(memberName,
                                            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance |
                                            System.Reflection.BindingFlags.FlattenHierarchy));

            //to add more types of properties

            flds = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where(flds, i => !ReferenceEquals(i, null)));

            if (flds.Count != 0)
                return flds[0];

            return null;
        }

        [System.Diagnostics.DebuggerHidden]
        private static T As<T>(this object obj)
        {
            return (T)obj;
        }
    }

Getting the text from a drop-down box

var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;

Joining three tables using MySQL

Simply use:

select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 

Install a Windows service using a Windows command prompt?

Open command prompt as administrator, go to your Folder where your .exe resides. To Install Exe as service

D:\YourFolderName\YourExeName /i

To uninstall use /u.

How to create a zip archive of a directory in Python?

Zip a file or a tree (a directory and its sub-directories).

from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED

def make_zip(tree_path, zip_path, mode='w', skip_empty_dir=False):
    with ZipFile(zip_path, mode=mode, compression=ZIP_DEFLATED) as zf:
        paths = [Path(tree_path)]
        while paths:
            p = paths.pop()
            if p.is_dir():
                paths.extend(p.iterdir())
                if skip_empty_dir:
                    continue
            zf.write(p)

To append to an existing archive, pass mode='a', to create a fresh archive mode='w' (the default in the above). So let's say you want to bundle 3 different directory trees under the same archive.

make_zip(path_to_tree1, path_to_arch, mode='w')
make_zip(path_to_tree2, path_to_arch, mode='a')
make_zip(path_to_file3, path_to_arch, mode='a')

How to set auto increment primary key in PostgreSQL?

Steps to do it on PgAdmin:

  • CREATE SEQUENCE sequnence_title START 1; // if table exist last id
  • Add this sequense to the primary key, table - properties - columns - column_id(primary key) edit - Constraints - Add nextval('sequnence_title'::regclass) to the field default.

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

How do I run a class in a WAR from the command line?

If you're using Maven, just follow the maven-war-plugin documentation about "How do I create a JAR containing the classes in my webapp?": add <attachClasses>true</attachClasses> to the <configuration> of the plugin:

<project>
  ...
  <artifactId>mywebapp</artifactId>
  <version>1.0-SNAPSHOT</version>
  ...
  <build>
    <plugins>
      <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
      <attachClasses>true</attachClasses>
    </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

The you will have 2 products in the target/ folder:

  • The project.war itself
  • The project-classes.jar which contains all the compiled classes in a jar

Then you will be able to execute a main class using classic method: java -cp target/project-classes.jar 'com.mycompany.MainClass' param1 param2

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How to remove padding around buttons in Android?

It doesn't seem to be padding, margin, or minheight/width. Setting android:background="@null" the button loses its touch animation, but it turns out that setting the background to anything at all fixes that border.


I am currently working with:

minSdkVersion 19
targetSdkVersion 23

Session 'app': Error Installing APK

I changed my USB port and that fixed it for me.

Why do we use __init__ in Python classes?

class Dog(object):

    # Class Object Attribute
    species = 'mammal'

    def __init__(self,breed,name):
        self.breed = breed
        self.name = name

In above example we use species as a global since it will be always same(Kind of constant you can say). when you call __init__ method then all the variable inside __init__ will be initiated(eg:breed,name).

class Dog(object):
    a = '12'

    def __init__(self,breed,name,a):
        self.breed = breed
        self.name = name
        self.a= a

if you print the above example by calling below like this

Dog.a
12

Dog('Lab','Sam','10')
Dog.a
10

That means it will be only initialized during object creation. so anything which you want to declare as constant make it as global and anything which changes use __init__

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

String.Format alternative in C++

You can use sprintf in combination with std::string.c_str().

c_str() returns a const char* and works with sprintf:

string a = "test";
string b = "text.txt";
string c = "text1.txt";
char* x = new char[a.length() + b.length() + c.length() + 32];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

string str = x;
delete[] x;

or you can use a pre-allocated char array if you know the size:

string a = "test";
string b = "text.txt";
string c = "text1.txt";
char x[256];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Java Generics With a Class & an Interface - Together

Here's how you would do it in Kotlin

fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
    //your code here
}

Select N random elements from a List<T> in C#

Using LINQ with large lists (when costly to touch each element) AND if you can live with the possibility of duplicates:

new int[5].Select(o => (int)(rnd.NextDouble() * maxIndex)).Select(i => YourIEnum.ElementAt(i))

For my use i had a list of 100.000 elements, and because of them being pulled from a DB I about halfed (or better) the time compared to a rnd on the whole list.

Having a large list will reduce the odds greatly for duplicates.

Why can't I define a default constructor for a struct in .NET?

What I use is the null-coalescing operator (??) combined with a backing field like this:

public struct SomeStruct {
  private SomeRefType m_MyRefVariableBackingField;

  public SomeRefType MyRefVariable {
    get { return m_MyRefVariableBackingField ?? (m_MyRefVariableBackingField = new SomeRefType()); }
  }
}

Hope this helps ;)

Note: the null coalescing assignment is currently a feature proposal for C# 8.0.

Can I set a breakpoint on 'memory access' in GDB?

Assuming the first answer is referring to the C-like syntax (char *)(0x135700 +0xec1a04f) then the answer to do rwatch *0x135700+0xec1a04f is incorrect. The correct syntax is rwatch *(0x135700+0xec1a04f).

The lack of ()s there caused me a great deal of pain trying to use watchpoints myself.

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

Do you (really) write exception safe code?

It is not possible to write exception-safe code under the assumption that "any line can throw". The design of exception-safe code relies critically on certain contracts/guarantees that you are supposed to expect, observe, follow and implement in your code. It is absolutely necessary to have code that is guaranteed to never throw. There are other kinds of exception guarantees out there.

In other words, creating exception-safe code is to a large degree a matter of program design not just a matter of plain coding.

Download a single folder or directory from a GitHub repo

Just 5 steps to go

  • Download SVN from here.
  • Open CMD and go to SVN bin directory like: cd %ProgramFiles%\SlikSvn\bin
  • Let's suppose I wan to download this directory URL
    https://github.com/ZeBobo5/Vlc.DotNet/tree/develop/src/Samples
  • Replace tree/develop or tree/master with trunk
  • Now fire this last command to download folder in same directory.
svn export https://github.com/ZeBobo5/Vlc.DotNet/trunk/src/Samples

Flutter Countdown Timer

Here is an example using Timer.periodic :

Countdown starts from 10 to 0 on button click :

import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          _start--;
        });
      }
    },
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}

Result :

Flutter countdown timer example

You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :

import 'package:quiver/async.dart';

[...]

int _start = 10;
int _current = 10;

void startTimer() {
  CountdownTimer countDownTimer = new CountdownTimer(
    new Duration(seconds: _start),
    new Duration(seconds: 1),
  );

  var sub = countDownTimer.listen(null);
  sub.onData((duration) {
    setState(() { _current = _start - duration.elapsed.inSeconds; });
  });

  sub.onDone(() {
    print("Done");
    sub.cancel();
  });
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_current")
      ],
    ),
  );
}

EDIT : For the question in comments about button click behavior

With the above code which uses Timer.periodic, a new timer will indeed be started on each button click, and all these timers will update the same _start variable, resulting in a faster decreasing counter.

There are multiple solutions to change this behavior, depending on what you want to achieve :

  • disable the button once clicked so that the user could not disturb the countdown anymore (maybe enable it back once timer is cancelled)
  • wrap the Timer.periodic creation with a non null condition so that clicking the button multiple times has no effect
if (_timer != null) {
  _timer = new Timer.periodic(...);
}
  • cancel the timer and reset the countdown if you want to restart the timer on each click :
if (_timer != null) {
  _timer.cancel();
  _start = 10;
}
_timer = new Timer.periodic(...);
  • if you want the button to act like a play/pause button :
if (_timer != null) {
  _timer.cancel();
  _timer = null;
} else {
  _timer = new Timer.periodic(...);
}

You could also use this official async package which provides a RestartableTimer class which extends from Timer and adds the reset method.

So just call _timer.reset(); on each button click.

Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb

Mysql - How to quit/exit from stored procedure

To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
         CALL SP_Reporting_2(tablename);
     END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
     #proceed with code
END;

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

As for Apache running on Ubuntu, the solution was to check error log, which showed that the error was related with folder and file permission.

First, check Apache error log

nano /var/log/apache2/error.log

Then set folder permission to be executable

sudo chmod 755 /var/www/html/

Also set file permission to be readable

sudo chmod 644 /var/www/html/.htaccess

Add error bars to show standard deviation on a plot in R

You can use arrows:

arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

How do I set vertical space between list items?

To apply to an entire list, use

ul.space_list li { margin-bottom: 1em; }

Then, in the html:

<ul class=space_list>
<li>A</li>
<li>B</li>
</ul>

No resource identifier found for attribute '...' in package 'com.app....'

this helps for me:

on your build.gradle:

implementation 'com.android.support:design:28.0.0'

Display MessageBox in ASP

Here is one way of doing it:

    <%
       Dim message    
       message = "This is my message"
       Response.Write("<script language=VBScript>MsgBox """ + message + """</script>") 
    %>

Regular expression to get a string between two strings in Javascript

Task

Extract substring between two string (excluding this two strings)

Solution

let allText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
let textBefore = "five centuries,";
let textAfter = "electronic typesetting";
var regExp = new RegExp(`(?<=${textBefore}\\s)(.+?)(?=\\s+${textAfter})`, "g");
var results = regExp.exec(allText);
if (results && results.length > 1) {
    console.log(results[0]);
}

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

You've already listed the most notable solutions for embedding Chromium (CEF, Chrome Frame, Awesomium). There aren't any more projects that matter.

There is still the Berkelium project (see Berkelium Sharp and Berkelium Managed), but it emebeds an old version of Chromium.

CEF is your best bet - it's fully open source and frequently updated. It's the only option that allows you to embed the latest version of Chromium. Now that Per Lundberg is actively working on porting CEF 3 to CefSharp, this is the best option for the future. There is also Xilium.CefGlue, but this one provides a low level API for CEF, it binds to the C API of CEF. CefSharp on the other hand binds to the C++ API of CEF.

Adobe is not the only major player using CEF, see other notable applications using CEF on the CEF wikipedia page.

Updating Chrome Frame is pointless since the project has been retired.

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Giving my function access to outside variable

Global $myArr;
$myArr = array();

function someFuntion(){
    global $myArr;

    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

Be forewarned, generally people stick away from globals as it has some downsides.

You could try this

function someFuntion($myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
    return $myArr;
}
$myArr = someFunction($myArr);

That would make it so you aren't relying on Globals.

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

Npm Please try using this command again as root/administrator

Here is how I fixed this on my Windows (7) Dev. environment. I assume the following...

  • You are Running Command Prompt, Git Bash, Cmder or your favorite Terminal, as an Administrator by right clicking
  • Privileges Permissions have been granted for Read/Write (i.e chmod -777)

Okay, let's get to it:

  1. Update any packages where a version check is returning a warning ("npm WARN"..) for example...

    npm update -g npm

    npm update -g graceful-fs

  2. Next we want to force a cache clean. This is flagged by an '--f' or '-f'..

    npm cache clean --f

  3. In Widows Explorer search for the following path

%APPDATA%\npm-cache

And Delete it's contents

  1. Start a fresh instance of your Terminal, remembering to 'Right-Click' and 'Run as Administrator', install the packages again.

Hope this helps someone!!

Xcode 4 - build output directory

This was so annoying. Open your project, click on Target, Open Build Phases tab. Check your Copy Bundle Resources for any red items.

How to convert Integer to int?

Another simple way would be:

Integer i = new Integer("10");

if (i != null)
    int ip = Integer.parseInt(i.toString());

Angular 2 Scroll to top on Route Change

Using the Router itself will cause issues which you cannot completely overcome to maintain consistent browser experience. In my opinion the best method is to just use a custom directive and let this reset the scroll on click. The good thing about this, is that if you are on the same url as that you click on, the page will scroll back to the top as well. This is consistent with normal websites. The basic directive could look something like this:

import {Directive, HostListener} from '@angular/core';

@Directive({
    selector: '[linkToTop]'
})
export class LinkToTopDirective {

    @HostListener('click')
    onClick(): void {
        window.scrollTo(0, 0);
    }
}

With the following usage:

<a routerLink="/" linkToTop></a>

This will be enough for most use-cases, but I can imagine a few issues which may arise from this:

  • Doesn't work on universal because of the usage of window
  • Small speed impact on change detection, because it is triggered by every click
  • No way to disable this directive

It is actually quite easy to overcome these issues:

@Directive({
  selector: '[linkToTop]'
})
export class LinkToTopDirective implements OnInit, OnDestroy {

  @Input()
  set linkToTop(active: string | boolean) {
    this.active = typeof active === 'string' ? active.length === 0 : active;
  }

  private active: boolean = true;

  private onClick: EventListener = (event: MouseEvent) => {
    if (this.active) {
      window.scrollTo(0, 0);
    }
  };

  constructor(@Inject(PLATFORM_ID) private readonly platformId: Object,
              private readonly elementRef: ElementRef,
              private readonly ngZone: NgZone
  ) {}

  ngOnDestroy(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.elementRef.nativeElement.removeEventListener('click', this.onClick, false);
    }
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.ngZone.runOutsideAngular(() => 
        this.elementRef.nativeElement.addEventListener('click', this.onClick, false)
      );
    }
  }
}

This takes most use-cases into account, with the same usage as the basic one, with the advantage of enable/disabling it:

<a routerLink="/" linkToTop></a> <!-- always active -->
<a routerLink="/" [linkToTop]="isActive"> <!-- active when `isActive` is true -->

commercials, don't read if you don't want to be advertised

Another improvement could be made to check whether or not the browser supports passive events. This will complicate the code a bit more, and is a bit obscure if you want to implement all these in your custom directives/templates. That's why I wrote a little library which you can use to address these problems. To have the same functionality as above, and with the added passive event, you can change your directive to this, if you use the ng-event-options library. The logic is inside the click.pnb listener:

@Directive({
    selector: '[linkToTop]'
})
export class LinkToTopDirective {

    @Input()
    set linkToTop(active: string|boolean) {
        this.active = typeof active === 'string' ? active.length === 0 : active;
    }

    private active: boolean = true;

    @HostListener('click.pnb')
    onClick(): void {
      if (this.active) {
        window.scrollTo(0, 0);
      }        
    }
}

When should I really use noexcept?

When can I realistically except to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

Um, never? Is never a time? Never.

noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never.

noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something. So noexcept is not a matter of giving the compiler hints about how to optimize a function so much as giving you hints about how to use a function.

Templates like move_if_noexcept will detect if the move constructor is defined with noexcept and will return a const& instead of a && of the type if it is not. It's a way of saying to move if it is very safe to do so.

In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.

In short: use it for move constructors and similar constructs, but don't feel like you have to go nuts with it.

"NOT IN" clause in LINQ to Entities

I created it in a more similar way to the SQL, I think it is easier to understand

var list = (from a in listA.AsEnumerable()
            join b in listB.AsEnumerable() on a.id equals b.id into ab
            from c in ab.DefaultIfEmpty()
            where c != null
            select new { id = c.id, name = c.nome }).ToList();

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

Regular expression that matches valid IPv6 addresses

The regex allows the use of leading zeros in the IPv4 parts.

Some Unix and Mac distros convert those segments into octals.

I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d as an IPv4 segment.

function to remove duplicate characters in a string

The function looks fine to me. I've written inline comments. Hope it helps:

// function takes a char array as input.
// modifies it to remove duplicates and adds a 0 to mark the end
// of the unique chars in the array.
public static void removeDuplicates(char[] str) {
  if (str == null) return; // if the array does not exist..nothing to do return.
  int len = str.length; // get the array length.
  if (len < 2) return; // if its less than 2..can't have duplicates..return.
  int tail = 1; // number of unique char in the array.
  // start at 2nd char and go till the end of the array.
  for (int i = 1; i < len; ++i) { 
    int j;
    // for every char in outer loop check if that char is already seen.
    // char in [0,tail) are all unique.
    for (j = 0; j < tail; ++j) {
      if (str[i] == str[j]) break; // break if we find duplicate.
    }
    // if j reachs tail..we did not break, which implies this char at pos i
    // is not a duplicate. So we need to add it our "unique char list"
    // we add it to the end, that is at pos tail.
    if (j == tail) {
      str[tail] = str[i]; // add
      ++tail; // increment tail...[0,tail) is still "unique char list"
    }
  }
  str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}

Python return statement error " 'return' outside function"

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

google chrome extension :: console.log() from background page?

The simplest solution would be to add the following code on the top of the file. And than you can use all full Chrome console api as you would normally.

 console = chrome.extension.getBackgroundPage().console;
// for instance, console.assert(1!=1) will return assertion error
// console.log("msg") ==> prints msg
// etc

How to serialize Object to JSON?

One can use the Jackson library as well.

Add Maven Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId> 
  <artifactId>jackson-core</artifactId>
</dependency>

Simply do this:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );

How does autowiring work in Spring?

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.

In your controllers, you just have the following:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

A few notes:

  • In your applicationContext.xml you should enable the <context:component-scan> so that classes are scanned for the @Controller, @Service, etc. annotations.
  • The entry point for a Spring-MVC application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.
  • UserServiceImpl should also be defined as bean - either using <bean id=".." class=".."> or using the @Service annotation. Since it will be the only implementor of UserService, it will be injected.
  • Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used.

How to remove duplicate white spaces in string using Java?

You can use the regex

(\s)\1

and

replace it with $1.

Java code:

str = str.replaceAll("(\\s)\\1","$1");

If the input is "foo\t\tbar " you'll get "foo\tbar " as output
But if the input is "foo\t bar" it will remain unchanged because it does not have any consecutive whitespace characters.

If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:

str = str.replaceAll("\\s+"," ");

But if you want to replace two consecutive white space with a single space you should do:

str = str.replaceAll("\\s{2}"," ");

How to add an extra column to a NumPy array

For me, the next way looks pretty intuitive and simple.

zeros = np.zeros((2,1)) #2 is a number of rows in your array.   
b = np.hstack((a, zeros))

Change <br> height using CSS

_x000D_
_x000D_
#biglinebreakid {_x000D_
  line-height: 450%;_x000D_
  // 9x the normal height of a line break!_x000D_
}_x000D_
.biglinebreakclass {_x000D_
  line-height: 1em;_x000D_
  // you could even use calc!_x000D_
}
_x000D_
This is a small line_x000D_
<br />_x000D_
break. Whereas, this is a BIG line_x000D_
<br />_x000D_
<br id="biglinebreakid" />_x000D_
break! You can use any CSS selectors you want for things like this line_x000D_
<br />_x000D_
<br class="biglinebreakclass" />_x000D_
break!
_x000D_
_x000D_
_x000D_

How to print Boolean flag in NSLog?

Note that in Swift, you can just do

let testBool: Bool = true
NSLog("testBool = %@", testBool.description)

This will log testBool = true

check if a key exists in a bucket in s3 using boto3

FWIW, here are the very simple functions that I am using

import boto3

def get_resource(config: dict={}):
    """Loads the s3 resource.

    Expects AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to be in the environment
    or in a config dictionary.
    Looks in the environment first."""

    s3 = boto3.resource('s3',
                        aws_access_key_id=os.environ.get(
                            "AWS_ACCESS_KEY_ID", config.get("AWS_ACCESS_KEY_ID")),
                        aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY", config.get("AWS_SECRET_ACCESS_KEY")))
    return s3


def get_bucket(s3, s3_uri: str):
    """Get the bucket from the resource.
    A thin wrapper, use with caution.

    Example usage:

    >> bucket = get_bucket(get_resource(), s3_uri_prod)"""
    return s3.Bucket(s3_uri)


def isfile_s3(bucket, key: str) -> bool:
    """Returns T/F whether the file exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) == 1 and objs[0].key == key


def isdir_s3(bucket, key: str) -> bool:
    """Returns T/F whether the directory exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) > 1

How do I get a human-readable file size in bytes abbreviation using .NET?

[DllImport ( "Shlwapi.dll", CharSet = CharSet.Auto )]
public static extern long StrFormatByteSize ( 
        long fileSize
        , [MarshalAs ( UnmanagedType.LPTStr )] StringBuilder buffer
        , int bufferSize );


/// <summary>
/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.
/// </summary>
/// <param name="filelength">The numeric value to be converted.</param>
/// <returns>the converted string</returns>
public static string StrFormatByteSize (long filesize) {
     StringBuilder sb = new StringBuilder( 11 );
     StrFormatByteSize( filesize, sb, sb.Capacity );
     return sb.ToString();
}

From: http://www.pinvoke.net/default.aspx/shlwapi/StrFormatByteSize.html

Difference between jQuery’s .hide() and setting CSS to display: none

See there is no difference if you use basic hide method. But jquery provides various hide method which give effects to the element. Refer below link for detailed explanation: Effects for Hide in Jquery

How can I get a side-by-side diff when I do "git diff"?

Several others already mentioned cdiff for git side-by-side diffing but no one gave a full implementation of it.

Setup cdiff:

git clone https://github.com/ymattw/cdiff.git
cd cdiff
ln -s `pwd`/cdiff ~/bin/cdiff
hash -r # refresh your PATH executable in bash (or 'rehash' if you use tcsh)
        # or just create a new terminal

Edit ~/.gitconfig inserting these lines:

[pager]
        diff = false
        show = false

[diff]
        tool = cdiff
        external = "cdiff -s $2 $5 #"

[difftool "cdiff"]
        cmd = cdiff -s \"$LOCAL\" \"$REMOTE\"

[alias]
        showw = show --ext-dif

The pager off is needed for cdiff to work with Diff, it is essentially a pager anyway so this is fine. Difftool will work regardless of these settings.

The show alias is needed because git show only supports external diff tools via argument.

The '#' at the end of the diff external command is important. Git's diff command appends a $@ (all available diff variables) to the diff command, but we only want the two filenames. So we call out those two explicitly with $2 and $5, and then hide the $@ behind a comment which would otherwise confuse sdiff. Resulting in an error that looks like:

fatal: <FILENAME>: no such path in the working tree
Use 'git <command> -- <path>...' to specify paths that do not exist locally.

Git commands that now produce side-by-side diffing:

git diff <SHA1> <SHA2> 
git difftool <SHA1> <SHA2>
git showw <SHA>

Cdiff usage:

'SPACEBAR' - Advances the page of the current file.
'Q'        - Quits current file, thus advancing you to the next file.

You now have side-by-side diff via git diff and difftool. And you have the cdiff python source code for power user customization should you need it.

Python MYSQL update statement

You've got the syntax all wrong:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))

For more, read the documentation.

How to underline a UILabel in swift?

I have algorithm that used in my app. In this algorithm you can underline substring even that have space between words

extension NSMutableAttributedString{

    static func  findSubStringAndUnderlineIt(subStringToBeFound : String,totalString : String)->  NSMutableAttributedString?{
        
        let attributedString = NSMutableAttributedString(string: totalString)

        var spaceCount = 0
        
        if subStringToBeFound.contains(" "){
            spaceCount = subStringToBeFound.components(separatedBy:" ").count-1
        }

        
        if  let range = attributedString.string.range(of: subStringToBeFound, options: .caseInsensitive){
        
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange((range.lowerBound.utf16Offset(in: subStringToBeFound)) ,(range.upperBound.utf16Offset(in: subStringToBeFound)) +
            spaceCount))
                return attributedString
        }
        return attributedString
        
    }
    
}

in used section

 lblWarning.attributedText = NSMutableAttributedString.findSubStringAndUnderlineIt(subStringToBeFound:"Not: Sadece uygulamanin reklamlari kaldirilacaktir.", totalString: lblWarning.text!)

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

Change event on select with knockout binding, how can I know if it is a real change?

Here is a solution that may help with this strange behaviour. I couldn't find a better solution than place a button to manually trigger the change event.

EDIT: Maybe a custom binding like this could help:

ko.bindingHandlers.changeSelectValue = {

   init: function(element,valueAccessor){

        $(element).change(function(){

            var value = $(element).val();

            if($(element).is(":focus")){

                  //Do whatever you want with the new value
            }

        });

    }
  };

And in your select data-bind attribute add:

changeSelectValue: yourSelectValue

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

Npm install failed with "cannot run in wd"

I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:

1: use --allow-root option for bower install command

"postinstall": "./node_modules/bower/bin/bower --allow-root install"

2: use --unsafe-perm option for npm install command

npm install --unsafe-perm

What properties can I use with event.target?

window.onclick = e => {
    console.dir(e.target);  // use this in chrome
    console.log(e.target);  // use this in firefox - click on tag name to view 
}  

enter image description here

take advantage of using filter propeties


e.target.tagName
e.target.className
e.target.style.height  // its not the value applied from the css style sheet, to get that values use `getComputedStyle()`

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Nothing easier than that man. Try this one:

<?xml version="1.0" encoding="iso-8859-1"?>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
    <style>
        .loading { background: url(/img/spinner.gif) center no-repeat !important}
    </style>
</head>
<body>
    <a class="ajax" href="http://www.google.com">
      Open as dialog
    </a>

    <script type="text/javascript">
    $(function (){
        $('a.ajax').click(function() {
            var url = this.href;
            // show a spinner or something via css
            var dialog = $('<div style="display:none" class="loading"></div>').appendTo('body');
            // open the dialog
            dialog.dialog({
                // add a close listener to prevent adding multiple divs to the document
                close: function(event, ui) {
                    // remove div with all data and events
                    dialog.remove();
                },
                modal: true
            });
            // load remote content
            dialog.load(
                url, 
                {}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
                function (responseText, textStatus, XMLHttpRequest) {
                    // remove the loading class
                    dialog.removeClass('loading');
                }
            );
            //prevent the browser to follow the link
            return false;
        });
    });
    </script>
</body>
</html>

Note that you can't load remote from local, so you'll have to upload this to a server or whatever. Also note that you can't load from foreign domains, so you should replace href of the link to a document hosted on the same domain (and here's the workaround).

Cheers

What is the difference between a static method and a non-static method?

Generally

static: no need to create object we can directly call using

ClassName.methodname()

Non Static: we need to create a object like

ClassName obj=new ClassName()
obj.methodname();

Spring Data and Native Query with pagination

I'm using the code below. working

@Query(value = "select * from user usr" +
  "left join apl apl on usr.user_id = apl.id" +
  "left join lang on lang.role_id = usr.role_id" +
  "where apl.scr_name like %:scrname% and apl.uname like %:uname and usr.role_id in :roleIds ORDER BY ?#{#pageable}",
  countQuery = "select count(*) from user usr" +
      "left join apl apl on usr.user_id = apl.id" +
      "left join lang on lang.role_id = usr.role_id" +
      "where apl.scr_name like %:scrname% and apl.uname like %:uname and usr.role_id in :roleIds",
  nativeQuery = true)
Page<AplUserEntity> searchUser(@Param("scrname") String scrname,@Param("uname") String  uname,@Param("roleIds") List<Long> roleIds,Pageable pageable);

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

Proper way to empty a C-String

If you are trying to clear out a receive buffer for something that receives strings I have found the best way is to use memset as described above. The reason is that no matter how big the next received string is (limited to sizeof buffer of course), it will automatically be an asciiz string if written into a buffer that has been pre-zeroed.

PHP: trying to create a new line with "\n"

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;

Using CSS to affect div style inside iframe

In short no.

You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.

COALESCE Function in TSQL

There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/

Reading column names alone in a csv file

here is the code to print only the headers or columns of the csv file.

import csv
HEADERS = next(csv.reader(open('filepath.csv')))
print (HEADERS)

Another method with pandas

import pandas as pd
HEADERS = list(pd.read_csv('filepath.csv').head(0))
print (HEADERS)

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

PHP function to get the subdomain of a URL

$host = $_SERVER['HTTP_HOST'];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
$domain = $matches[0];
$url = explode($domain, $host);
$subdomain = str_replace('.', '', $url[0]);

echo 'subdomain: '.$subdomain.'<br />';
echo 'domain: '.$domain.'<br />';

What's the difference between IFrame and Frame?

While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed.

How to convert Observable<any> to array[]

Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.

Using your CountryData class, you would define a service method like this:

getCountries()  {
  return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}

Then when you need it, define an array like this:

countries:CountryData[] = [];

and subscribe to it like this:

this.countryService.getCountries().subscribe(countries => this.countries = countries);

A complete setup answer is posted here also.

How do I make the return type of a method generic?

You need to make it a generic method, like this:

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType, assuming that all the relevant types are supported:

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

I'm not entirely convinced that all this is a good idea, mind you...

Removing "NUL" characters

I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:

//The hexidecimal 0x0 is the null character  
mystring.Contains(Convert.ToChar(0x0).ToString() );  

// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");  

Get everything after the dash in a string in JavaScript

A solution I prefer would be:

const str = 'sometext-20202';
const slug = str.split('-').pop();

Where slug would be your result

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

INNER JOIN vs LEFT JOIN performance in SQL Server

Your performance problems are more likely to be because of the number of joins you are doing and whether the columns you are joining on have indexes or not.

Worst case you could easily be doing 9 whole table scans for each join.

Checking if a variable exists in javascript

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:

this.hasOwnProperty("bar")

to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

Merge some list items in a Python List

just a variation

alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist

How to call loading function with React useEffect only once

If you only want to run the function given to useEffect after the initial render, you can give it an empty array as second argument.

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return <div> {/* ... */} </div>;
}

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

What is fastest children() or find() in jQuery?

Those won't necessarily give the same result: find() will get you any descendant node, whereas children() will only get you immediate children that match.

At one point, find() was a lot slower since it had to search for every descendant node that could be a match, and not just immediate children. However, this is no longer true; find() is much quicker due to using native browser methods.

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

Can't load AMD 64-bit .dll on a IA 32-bit platform

Try this:

  1. Download and install a 32-bit JDK.
  2. Go to eclipse click on your project (Run As ? Run Configurations...) under Java Application branch.
  3. Go to the JRE tab and select Alternate JRE. Click on Installed JRE button, add your 32-bit JRE and select.

How do I write a for loop in bash

if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells

Statically rotate font-awesome icons

In case someone else stumbles upon this question and wants it here is the SASS mixin I use.

@mixin rotate($deg: 90){
    $sDeg: #{$deg}deg;

    -webkit-transform: rotate($sDeg);
    -moz-transform: rotate($sDeg);
    -ms-transform: rotate($sDeg);
    -o-transform: rotate($sDeg);
    transform: rotate($sDeg);
}

Convert seconds value to hours minutes seconds?

Here is the working code:

private String getDurationString(int seconds) {

    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    seconds = seconds % 60;

    return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}

private String twoDigitString(int number) {

    if (number == 0) {
        return "00";
    }

    if (number / 10 == 0) {
        return "0" + number;
    }

    return String.valueOf(number);
}

Query to get all rows from previous month

select fields FROM table WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');

this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

pip issue installing almost any library

macOS Sierra 10.12.6. Wasn't able to install anything through pip (python installed through homebrew). All the answers above didn't work.

Eventually, upgrade from python 3.5 to 3.6 worked.

brew update
brew doctor #(in case you see such suggestion by brew)

then follow any additional suggestions by brew, i.e. overwrite link to python.

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

this worked best for me:

        Cells(partcount + 5, "N").Value = Date + Time
        Cells(partcount + 5, "N").NumberFormat = "mm/dd/yy hh:mm:ss AM/PM"