Programs & Examples On #Request pipeline

ASP.NET MVC Request Handling Pipeline. The flow that ASP.NET MVC runs from the time when the request is made until returning the contents to the user's browser.

How can I merge the columns from two tables into one output?

SELECT col1,
  col2
FROM
  (SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
  (SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;

Padding between ActionBar's home icon and title

For me only the following combination worked, tested from API 18 to 24

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"

where in "app" is : xmlns:app="http://schemas.android.com/apk/res-auto"

for example.

 <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/SE_Life_Green"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                app:contentInsetStartWithNavigation="0dp"
                >
                .......
                .......
                .......
            </android.support.v7.widget.Toolbar>

Get image data url in JavaScript?

This is all you need to read.

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString

var height = 200;
var width  = 200;

canvas.width  = width;
canvas.height = height;

var ctx = canvas.getContext('2d');

ctx.strokeStyle = '#090';
ctx.beginPath();
ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
ctx.stroke();

canvas.toBlob(function (blob) {
  //consider blob is your file object

  var reader = new FileReader();

  reader.onload = function () {
    console.log(reader.result);
  }

  reader.readAsBinaryString(blob);
});

How to time Java program execution speed

You may also try Perf4J. Its a neat way of doing what you are looking for, and helps in aggregated performance statistics like mean, minimum, maximum, standard deviation and transactions per second over a set time span. An extract from http://perf4j.codehaus.org/devguide.html:

StopWatch stopWatch = new LoggingStopWatch();

try {
    // the code block being timed - this is just a dummy example
    long sleepTime = (long)(Math.random() * 1000L);
    Thread.sleep(sleepTime);
    if (sleepTime > 500L) {
        throw new Exception("Throwing exception");
    }

    stopWatch.stop("codeBlock2.success", "Sleep time was < 500 ms");
} catch (Exception e) {
    stopWatch.stop("codeBlock2.failure", "Exception was: " + e);
}

Output:

INFO: start[1230493236109] time[447] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493236719] time[567] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493237286] time[986] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493238273] time[194] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238467] time[463] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238930] time[310] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239241] time[610] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493239852] time[84] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239937] time[30] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239968] time[852] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

SyntaxError: "can't assign to function call"

You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )

subsequent_amount = invest(initial_amount,top_company(5,year,year+1))

Check if all values in list are greater than a certain number

I write this function

def larger(x, than=0):
    if not x or min(x) > than:
        return True
    return False

Then

print larger([5, 6, 7], than=5)  # False
print larger([6, 7, 8], than=5)  # True
print larger([], than=5)  # True
print larger([6, 7, 8, None], than=5)  # False


Empty list on min() will raise ValueError. So I added if not x in condition.

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

MySQL LEFT JOIN 3 tables

Try this definitely work.

SELECT p.PersonID AS person_id,
   p.Name, p.SS, 
   f.FearID AS fear_id,
   f.Fear 
   FROM person_fear AS pf 
      LEFT JOIN persons AS p ON pf.PersonID = p.PersonID 
      LEFT JOIN fears AS f ON pf.PersonID = f.FearID 
   WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID

Specify the from user when sending email using the mail command

None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.

I'm using Ubuntu 12.04 LTS with mailutils v2.1.

I found this solutions somewhere on the net, don't know where, can't find it again:

-aFrom:[email protected]

Full Command used:

cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]

hibernate could not get next sequence value

You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

What should a JSON service return on failure / error

The HTTP status code you return should depend on the type of error that has occurred. If an ID doesn't exist in the database, return a 404; if a user doesn't have enough privileges to make that Ajax call, return a 403; if the database times out before being able to find the record, return a 500 (server error).

jQuery automatically detects such error codes, and runs the callback function that you define in your Ajax call. Documentation: http://api.jquery.com/jQuery.ajax/

Short example of a $.ajax error callback:

$.ajax({
  type: 'POST',
  url: '/some/resource',
  success: function(data, textStatus) {
    // Handle success
  },
  error: function(xhr, textStatus, errorThrown) {
    // Handle error
  }
});

Java and HTTPS url connection without downloading certificate

Use the latest X509ExtendedTrustManager instead of X509Certificate as advised here: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

    package javaapplication8;

    import java.io.InputStream;
    import java.net.Socket;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLEngine;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509ExtendedTrustManager;

    /**
     *
     * @author hoshantm
     */
    public class JavaApplication8 {

        /**
         * @param args the command line arguments
         * @throws java.lang.Exception
         */
        public static void main(String[] args) throws Exception {
            /*
             *  fix for
             *    Exception in thread "main" javax.net.ssl.SSLHandshakeException:
             *       sun.security.validator.ValidatorException:
             *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
             *               unable to find valid certification path to requested target
             */
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509ExtendedTrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            /*
             * end of the fix
             */

            URL url = new URL("https://10.52.182.224/cgi-bin/dynamic/config/panel.bmp");
            URLConnection con = url.openConnection();
            //Reader reader = new ImageStreamReader(con.getInputStream());

            InputStream is = new URL(url.toString()).openStream();

            // Whatever you may want to do next

        }

    }

print call stack in C or C++

You can use the Boost libraries to print the current callstack.

#include <boost/stacktrace.hpp>

// ... somewhere inside the `bar(int)` function that is called recursively:
std::cout << boost::stacktrace::stacktrace();

Man here: https://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace.html

How to margin the body of the page (html)?

Try using CSS.

body {
   margin: 0 0 auto 0;
}

The order is clockwise from the top, so top right bottom left.

Turning Sonar off for certain code

I not be able to find squid number in sonar 5.6, with this annotation also works:

@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})

How to convert a Java object (bean) to key-value pairs (and vice versa)?

There is of course the absolute simplest means of conversion possible - no conversion at all!

instead of using private variables defined in the class, make the class contain only a HashMap which stores the values for the instance.

Then your getters and setters return and set values into and out of the HashMap, and when it is time to convert it to a map, voila! - it is already a map.

With a little bit of AOP wizardry, you could even maintain the inflexibility inherent in a bean by allowing you to still use getters and setters specific to each values name, without having to actually write the individual getters and setters.

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

404 Not Found The requested URL was not found on this server

For saving a file as .htaccess, when using windows, you have to open notepad and then saveas .htaccess as windows does not create files starting with a dot. That should get your .htaccess working and it'll clear up the issue.

By the way, in order to receive specific error messages set Configure::write('debug', 0); to '2' in app/config/core.php for development purposes.

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

CSS position:fixed inside a positioned element

Try position:sticky on parent div of the element you want to be fixed.

More info here: http://html5-demos.appspot.com/static/css/sticky.html. Caution: Check for browser version compatibility.

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

NumPy array is not JSON serializable

May do simple for loop with checking types:

with open("jsondontdoit.json", 'w') as fp:
    for key in bests.keys():
        if type(bests[key]) == np.ndarray:
            bests[key] = bests[key].tolist()
            continue
        for idx in bests[key]:
            if type(bests[key][idx]) == np.ndarray:
                bests[key][idx] = bests[key][idx].tolist()
    json.dump(bests, fp)
    fp.close()

Implement a simple factory pattern with Spring 3 annotations

Why not add the interface FactoryBean to MyServiceFactory (to tell Spring that it's a factory), add a register(String service, MyService instance) then, have each of the services call:

@Autowired
MyServiceFactory serviceFactory;

@PostConstruct
public void postConstruct() {
    serviceFactory.register(myName, this);
}

This way, you can separate each service provider into modules if necessary, and Spring will automagically pick up any deployed and available service providers.

Click in OK button inside an Alert (Selenium IDE)

1| Print Alert popup text and close -I

Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());

2| Print Alert popup text and close -II

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()); //Print Alert popup
alert.accept(); //Close Alert popup

3| Assert Alert popup text and close

Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());

What is __main__.py?

You create __main__.py in yourpackage to make it executable as:

$ python -m yourpackage

Trying to handle "back" navigation button action in iOS

The problem with didMoveToParentViewController it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.

And it doesn't work with the driven animation gesture. Using willMoveToParentViewController works better.

Objective-c

- (void)willMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        // ...
    }
}

Swift

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // ...  
    }
}

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

This is now a multiple-year old question, but being very popular, it's worth mentioning a fantastic resource for learning about the C++11 memory model. I see no point in summing up his talk in order to make this yet another full answer, but given this is the guy who actually wrote the standard, I think it's well worth watching the talk.

Herb Sutter has a three hour long talk about the C++11 memory model titled "atomic<> Weapons", available on the Channel9 site - part 1 and part 2. The talk is pretty technical, and covers the following topics:

  1. Optimizations, Races, and the Memory Model
  2. Ordering – What: Acquire and Release
  3. Ordering – How: Mutexes, Atomics, and/or Fences
  4. Other Restrictions on Compilers and Hardware
  5. Code Gen & Performance: x86/x64, IA64, POWER, ARM
  6. Relaxed Atomics

The talk doesn't elaborate on the API, but rather on the reasoning, background, under the hood and behind the scenes (did you know relaxed semantics were added to the standard only because POWER and ARM do not support synchronized load efficiently?).

How to do a JUnit assert on a message in a logger

The API for Log4J2 is slightly different. Also you might be using its async appender. I created a latched appender for this:

    public static class LatchedAppender extends AbstractAppender implements AutoCloseable {

    private final List<LogEvent> messages = new ArrayList<>();
    private final CountDownLatch latch;
    private final LoggerConfig loggerConfig;

    public LatchedAppender(Class<?> classThatLogs, int expectedMessages) {
        this(classThatLogs, null, null, expectedMessages);
    }
    public LatchedAppender(Class<?> classThatLogs, Filter filter, Layout<? extends Serializable> layout, int expectedMessages) {
        super(classThatLogs.getName()+"."+"LatchedAppender", filter, layout);
        latch = new CountDownLatch(expectedMessages);
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        loggerConfig = config.getLoggerConfig(LogManager.getLogger(classThatLogs).getName());
        loggerConfig.addAppender(this, Level.ALL, ThresholdFilter.createFilter(Level.ALL, null, null));
        start();
    }

    @Override
    public void append(LogEvent event) {
        messages.add(event);
        latch.countDown();
    }

    public List<LogEvent> awaitMessages() throws InterruptedException {
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        return messages;
    }

    @Override
    public void close() {
        stop();
        loggerConfig.removeAppender(this.getName());
    }
}

Use it like this:

        try (LatchedAppender appender = new LatchedAppender(ClassUnderTest.class, 1)) {

        ClassUnderTest.methodThatLogs();
        List<LogEvent> events = appender.awaitMessages();
        assertEquals(1, events.size());
        //more assertions here

    }//appender removed

Execute bash script from URL

bash | curl http://your.url.here/script.txt

actual example:

juan@juan-MS-7808:~$ bash | curl https://raw.githubusercontent.com/JPHACKER2k18/markwe/master/testapp.sh


Oh, wow im alive


juan@juan-MS-7808:~$ 

How to tell if a string is not defined in a Bash shell script

A summary of tests.

[ -n "$var" ] && echo "var is set and not empty"
[ -z "$var" ] && echo "var is unset or empty"
[ "${var+x}" = "x" ] && echo "var is set"  # may or may not be empty
[ -n "${var+x}" ] && echo "var is set"  # may or may not be empty
[ -z "${var+x}" ] && echo "var is unset"
[ -z "${var-x}" ] && echo "var is set and empty"

How do I read a text file of about 2 GB?

For reading and editing, Geany for Windows is another good option. I've run in to limit issues with Notepad++, but not yet with Geany.

<img>: Unsafe value used in a resource URL context

The most elegant way to fix this: use pipe. Here is example (my blog). So you can then simply use url | safe pipe to bypass the security.

<iframe [src]="url | safe"></iframe>

Refer to the documentation on npm for details: https://www.npmjs.com/package/safe-pipe

Background color not showing in print preview

There's a style in the bootstrap css files under @media print{*,:after,:before ....} that has color and background styles labeled !important, which remove any background colors on any elements. Kill those two pieces of css and it will work.

Bootstrap is making the executing decision that you should never have any background color in prints, so you have to edit their css or have another !important style that is a higher precedence. Good job bootstrap...

How to rename array keys in PHP?

It is from duplicated question

$json = '[   
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},    
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';

$array = json_decode($json, true);

$out = array_map(function ($product) {
  return array_merge([
    'price'    => $product['product_price'],
    'quantity' => $product['product_quantity'],
  ], array_flip(array_filter(array_flip($product), function ($value) {
    return $value != 'product_price' && $value != 'product_quantity';
  })));
}, $array);

var_dump($out);

https://repl.it/@Piterden/Replace-keys-in-array

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

How can I make the browser wait to display the page until it's fully loaded?

Immediately following your <body> tag add something like this...

 <style> body  {opacity:0;}</style>

And for the very first thing in your <head> add something like...

 <script>
  window.onload = function() {setTimeout(function(){document.body.style.opacity="100";},500);};
 </script>

As far as this being good practice or bad depends on your visitors, and the time the wait takes.

The question that is stil left open and I am not seeing any answers here is how to be sure the page has stabilized. For example if you are loading fonts the page may reflow a bit until all the fonts are loaded and displayed. I would like to know if there is an event that tells me the page is done rendering.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

This means that your server is sending "text/html" instead of the already supported types. My solution was to add "text/html" to acceptableContentTypes set in AFURLResponseSerialization class. Just search for "acceptableContentTypes" and add @"text/html" to the set manually.

Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.

Why did my Git repo enter a detached HEAD state?

It can easily happen if you try to undo changes you've made by re-checking-out files and not quite getting the syntax right.

You can look at the output of git log - you could paste the tail of the log here since the last successful commit, and we could all see what you did. Or you could paste-bin it and ask nicely in #git on freenode IRC.

Is Java "pass-by-reference" or "pass-by-value"?

There is a very simple way to understand this. Lets's take C++ pass by reference.

#include <iostream>
using namespace std;

class Foo {
    private:
        int x;
    public:
        Foo(int val) {x = val;}
        void foo()
        {
            cout<<x<<endl;
        }
};

void bar(Foo& ref)
{
    ref.foo();
    ref = *(new Foo(99));
    ref.foo();
}

int main()
{
   Foo f = Foo(1);
   f.foo();
   bar(f);
   f.foo();

   return 0;
}

What is the outcome?

1
1
99
99

So, after bar() assigned a new value to a "reference" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.

Now, lets see what java says.

public class Ref {

    private static class Foo {
        private int x;

        private Foo(int x) {
            this.x = x;
        }

        private void foo() {
            System.out.println(x);
        }
    }

    private static void bar(Foo f) {
        f.foo();
        f = new Foo(99);
        f.foo();
    }

    public static void main(String[] args) {
        Foo f = new Foo(1);
        System.out.println(f.x);
        bar(f);
        System.out.println(f.x);
    }

}

It says:

1
1
99
1

Voilà, the reference of Foo in main that was passed to bar, is still unchanged!

This example clearly shows that java is not the same as C++ when we say "pass by reference". Essentially, java is passing "references" as "values" to functions, meaning java is pass by value.

php refresh current page?

PHP refresh current page

With PHP code:

<?php
$secondsWait = 1;
header("Refresh:$secondsWait");
echo date('Y-m-d H:i:s');
?>

Note: Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

if you send any output, you can use javascript:

<?php
echo date('Y-m-d H:i:s');
echo '<script type="text/javascript">location.reload(true);</script>';
?>

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

Or you can explicitly use "meta refresh" (with pure html):

<?php
$secondsWait = 1;
echo date('Y-m-d H:i:s');
echo '<meta http-equiv="refresh" content="'.$secondsWait.'">';
?>

Greetings and good code,

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Try,

 #!/bin/bash
 pause ()
 {
 REPLY=Y
 while [ "$REPLY" == "Y" ] || [ "$REPLY" != "y" ]
 do
  echo -e "\t\tPress 'y' to continue\t\t\tPress 'n' to quit"
  read -n1 -s
      case "$REPLY" in
      "n")  exit                      ;;
      "N")  echo "case sensitive!!"   ;; 
      "y")  clear                     ;;
      "Y")  echo "case sensitive!!"   ;;
      * )  echo "$REPLY is Invalid Option"     ;;
 esac
 done
 }
 pause
 echo "Hi"

Changing an AIX password via script?

Here is the script... 

#!/bin/bash
echo "Please enter username:"
read username
echo "Please enter the new password:"
read -s password1
echo "Please repeat the new password:"
read -s password2

# Check both passwords match
if [ $password1 != $password2 ]; then
echo "Passwords do not match"
 exit    
fi

# Does User exist?
id $username &> /dev/null
if [ $? -eq 0 ]; then
echo "$username exists... changing password."
else
echo "$username does not exist - Password could not be updated for $username"; exit 
fi

# Change password
echo -e "$password1\n$password1" | passwd $username

Refer the link below as well...

http://www.putorius.net/2013/04/bash-script-to-change-users-password.html

How to find whether MySQL is installed in Red Hat?

yum list installed | grep mysql

Then if it's not installed you can do (as root)

yum install mysql -y

Is it possible to clone html element objects in JavaScript / JQuery?

Yes, you can copy children of one element and paste them into the other element:

var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');

foo1.html(foo2.children().clone());

Proof: http://jsfiddle.net/de9kc/

Reset local repository branch to be just like remote repository HEAD

Use the commands below. These commands will remove all untracked files from local git too

git fetch origin
git reset --hard origin/master
git clean -d -f

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

How to kill all active and inactive oracle sessions for user

inactive session the day before kill

_x000D_
_x000D_
begin_x000D_
    for i in (select * from v$session where status='INACTIVE' and (sysdate-PREV_EXEC_START)>1)_x000D_
    LOOP_x000D_
        EXECUTE IMMEDIATE(q'{ALTER SYSTEM KILL SESSION '}'||i.sid||q'[,]'  ||i.serial#||q'[']'||' IMMEDIATE');_x000D_
    END LOOP;_x000D_
end;
_x000D_
_x000D_
_x000D_

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

Cannot use a leading ../ to exit above the top directory

In my case it turned out to be commented out HTML in a master page!

Who knew that commented out HTML such as this were actually interpreted by ASP.NET!

<!--
<link rel="icon" href="../../favicon.ico">
-->

Generating UML from C++ code?

UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Fowloing code remove newline from both side of string:

select ltrim(rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)),''||CHR(10)||CHR(13))  from dual

but in most cases this one is just enought :

select rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)))  from dual

make div's height expand with its content

I tried pretty much every suggestion listed above and none of them worked. However, "display: table" did the trick for me.

PL/pgSQL checking if a row exists

Use count(*)

declare 
   cnt integer;
begin
  SELECT count(*) INTO cnt
  FROM people
  WHERE person_id = my_person_id;

IF cnt > 0 THEN
  -- Do something
END IF;

Edit (for the downvoter who didn't read the statement and others who might be doing something similar)

The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)

Because of that where clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.

Retrieve column names from java.sql.ResultSet

You can get this info from the ResultSet metadata. See ResultSetMetaData

e.g.

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

and you can get the column name from there. If you do

select x as y from table

then rsmd.getColumnLabel() will get you the retrieved label name too.

Add object to ArrayList at specified index

You should set instead of add to replace existing value at index.

list.add(1, object1)
list.add(2, object3)
list.set(2, object2)

List will contain [object1,object2]

What are the differences between if, else, and else if?

if (numOptions == 1)
    return "if";
else if (numOptions > 2)
    return "else if";
else 
    return "else";

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

I believe the get() function immediately runs the select query and does not accept ORDER BY conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:

$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get(); 
return $query->result();

CodeIgniter Documentation order_by()

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

How can you get the active users connected to a postgreSQL database via SQL?

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

Before and After Suite execution hook in jUnit 4.x

Using annotations, you can do something like this:

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

class SomethingUnitTest {
    @BeforeClass
    public static void runBeforeClass()
    {

    }

    @AfterClass
    public static void runAfterClass()
    {  

    }

    @Before  
    public void setUp()
    {

    }

    @After
    public void tearDown()
    {

    }

    @Test
    public void testSomethingOrOther()
    {

    }

}

Refresh Fragment at reload

For example with TabLayout: just implement OnTabSelectedListener. To reload the page, you may use implement SwipeRefreshLayout.OnRefreshListener i.e. public class YourFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

the onRefresh() method will be @Override from the interface i.e.:

@Override
public void onRefresh() {
 loadData();
}

Here's the layout:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tablayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryLighter"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/white"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorTextPrimary"
    app:tabTextColor="@color/colorTextDisable" />

Code in your activity

TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.setupWithViewPager(viewPager);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                yourFragment1.onRefresh();
            } else if (tab.getPosition() == 1) {
                yourFragment2.onRefresh();
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

List all kafka topics

For dockerized kafka/zookeeper

docker ps

find you zookeeper container id

docker exec -it <id> bash

cd bin

./zkCli.sh

ls /brokers/topics

How to convert Blob to String and String to Blob in java

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

Terminal Commands: For loop with echo

jot would work too (in bash shell)

for i in `jot 1000 1`; do echo "http://example.com/$i.jpg"; done

While loop in batch

A while loop can be simulated in cmd.exe with:

:still_more_files
    if %countfiles% leq 21 (
        rem change countfile here
        goto :still_more_files
    )

For example, the following script:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set /a "x = 0"

:more_to_process
    if %x% leq 5 (
        echo %x%
        set /a "x = x + 1"
        goto :more_to_process
    )

    endlocal

outputs:

0
1
2
3
4
5

For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:

    @echo off
    set backupdir=c:\test

:more_files_to_process
    for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
    if %num% gtr 20 (
        cscript /nologo c:\deletefile.vbs %backupdir%
        goto :more_files_to_process
    )

How to add an element to Array and shift indexes?

Jrad solution is good but I don't like that he doesn't use array copy. Internally System.arraycopy() does a native call so you will a get faster results.

public static int[] addPos(int[] a, int index, int num) {
    int[] result = new int[a.length];
    System.arraycopy(a, 0, result, 0, index);
    System.arraycopy(a, index, result, index + 1, a.length - index - 1);
    result[index] = num;
    return result;
}

How can I make the computer beep in C#?

You can also use the relatively unused:

    System.Media.SystemSounds.Beep.Play();
    System.Media.SystemSounds.Asterisk.Play();
    System.Media.SystemSounds.Exclamation.Play();
    System.Media.SystemSounds.Question.Play();
    System.Media.SystemSounds.Hand.Play();

Documentation for this sounds is available in http://msdn.microsoft.com/en-us/library/system.media.systemsounds(v=vs.110).aspx

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

When should I use Kruskal as opposed to Prim (and vice versa)?

I know that you did not ask for this, but if you have more processing units, you should always consider Boruvka's algorithm, because it might be easily parallelized - hence it has a performance advantage over Kruskal and Jarník-Prim algorithm.

Converting RGB to grayscale/intensity

Heres some code in c to convert rgb to grayscale. The real weighting used for rgb to grayscale conversion is 0.3R+0.6G+0.11B. these weights arent absolutely critical so you can play with them. I have made them 0.25R+ 0.5G+0.25B. It produces a slightly darker image.

NOTE: The following code assumes xRGB 32bit pixel format

unsigned int *pntrBWImage=(unsigned int*)..data pointer..;  //assumes 4*width*height bytes with 32 bits i.e. 4 bytes per pixel
unsigned int fourBytes;
        unsigned char r,g,b;
        for (int index=0;index<width*height;index++)
        {
            fourBytes=pntrBWImage[index];//caches 4 bytes at a time
            r=(fourBytes>>16);
            g=(fourBytes>>8);
            b=fourBytes;

            I_Out[index] = (r >>2)+ (g>>1) + (b>>2); //This runs in 0.00065s on my pc and produces slightly darker results
            //I_Out[index]=((unsigned int)(r+g+b))/3;     //This runs in 0.0011s on my pc and produces a pure average
        }

How to call code behind server method from a client side JavaScript function?

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

How can I obtain the element-wise logical NOT of a pandas Series?

I just give it a shot:

In [9]: s = Series([True, True, True, False])

In [10]: s
Out[10]: 
0     True
1     True
2     True
3    False

In [11]: -s
Out[11]: 
0    False
1    False
2    False
3     True

Object spread vs. Object.assign

This is now part of ES6, thus is standardized, and is also documented on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

It's very convenient to use and makes a lot of sense alongside object destructuring.

The one remaining advantage listed above is the dynamic capabilities of Object.assign(), however this is as easy as spreading the array inside of a literal object. In the compiled babel output it uses exactly what is demonstrated with Object.assign()

So the correct answer would be to use object spread since it is now standardized, widely used (see react, redux, etc), is easy to use, and has all the features of Object.assign()

How do I get a list of all subdomains of a domain?

In Windows nslookup the command is

ls -d somedomain.com > outfile.txt

which stores the subdomain list in outfile.txt

few domains these days allow this

Converting DateTime format using razor

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")

how to move elasticsearch data from one server to another

If anyone encounter the same issue, when trying to dump from elasticsearch <2.0 to >2.0 you need to do:

elasticdump --input=http://localhost:9200/$SRC_IND --output=http://$TARGET_IP:9200/$TGT_IND --type=analyzer
elasticdump --input=http://localhost:9200/$SRC_IND --output=http://$TARGET_IP:9200/$TGT_IND --type=mapping
elasticdump --input=http://localhost:9200/$SRC_IND --output=http://$TARGET_IP:9200/$TGT_IND --type=data --transform "delete doc.__source['_id']"

How do you allow spaces to be entered using scanf?

People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).

Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.

Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:

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

/* Maximum name size + 1. */

#define MAX_NAME_SZ 256

int main(int argC, char *argV[]) {
    /* Allocate memory and check if okay. */

    char *name = malloc(MAX_NAME_SZ);
    if (name == NULL) {
        printf("No memory\n");
        return 1;
    }

    /* Ask user for name. */

    printf("What is your name? ");

    /* Get the name, with size limit. */

    fgets(name, MAX_NAME_SZ, stdin);

    /* Remove trailing newline, if there. */

    if ((strlen(name) > 0) && (name[strlen (name) - 1] == '\n'))
        name[strlen (name) - 1] = '\0';

    /* Say hello. */

    printf("Hello %s. Nice to meet you.\n", name);

    /* Free memory and exit. */

    free (name);
    return 0;
}

How to disable 'X-Frame-Options' response header in Spring Security?

If you're using Java configs instead of XML configs, put this in your WebSecurityConfigurerAdapter.configure(HttpSecurity http) method:

http.headers().frameOptions().disable();

Custom CSS Scrollbar for Firefox

I thought I would share my findings in case someone is considering a JQuery plugin to do the job.

I gave JQuery Custom Scrollbar a go. It's pretty fancy and does some smooth scrolling (with scrolling inertia) and has loads of parameters you can tweak, but it ended up being a bit too CPU intensive for me (and it adds a fair amount to the DOM).

Now I'm giving Perfect Scrollbar a go. It's simple and lightweight (6KB) and it's doing a decent job so far. It's not CPU intensive at all (as far as I can tell) and adds very little to your DOM. It's only got a couple of parameters to tweak (wheelSpeed and wheelPropagation), but it's all I need and it handles updates to the scrolling content nicely (such as loading images).

P.S. I did have a quick look at JScrollPane, but @simone is right, it's a bit dated now and a PITA.

How can I solve ORA-00911: invalid character error?

I encountered the same thing lately. it was just due to spaces when copying a script from a document to sql developer. I had to remove the spaces and the script ran.

Hibernate vs JPA vs JDO - pros and cons of each?

Some notes:

  • JDO and JPA are both specifications, not implementations.
  • The idea is you can swap JPA implementations, if you restrict your code to use standard JPA only. (Ditto for JDO.)
  • Hibernate can be used as one such implementation of JPA.
  • However, Hibernate provides a native API, with features above and beyond that of JPA.

IMO, I would recommend Hibernate.


There have been some comments / questions about what you should do if you need to use Hibernate-specific features. There are many ways to look at this, but my advice would be:

  • If you are not worried by the prospect of vendor tie-in, then make your choice between Hibernate, and other JPA and JDO implementations including the various vendor specific extensions in your decision making.

  • If you are worried by the prospect of vendor tie-in, and you can't use JPA without resorting to vendor specific extensions, then don't use JPA. (Ditto for JDO).

In reality, you will probably need to trade-off how much you are worried by vendor tie-in versus how much you need those vendor specific extensions.

And there are other factors too, like how well you / your staff know the respective technologies, how much the products will cost in licensing, and whose story you believe about what is going to happen in the future for JDO and JPA.

How to make a <ul> display in a horizontal row

As others have mentioned, you can set the li to display:inline;, or float the li left or right. Additionally, you can also use display:flex; on the ul. In the snippet below I also added justify-content:space-around to give it more spacing.

For more information on flexbox, checkout this complete guide.

_x000D_
_x000D_
#div_top_hypers {_x000D_
    background-color:#eeeeee;_x000D_
    display:inline;      _x000D_
}_x000D_
#ul_top_hypers {_x000D_
    display: flex;_x000D_
    justify-content:space-around;_x000D_
    list-style-type:none;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
    <ul id="ul_top_hypers">_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> logout</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Yes. If you have installed sp_who2k5 into your master database, you can simply run:

sp_who2k5 1,1

The resultset will include all the active transactions. The currently running backup(s) will contain the string "BACKUP" in the requestCommand field. The aptly named percentComplete field will give you the progress of the backup.

Note: sp_who2k5 should be a part of everyone's toolkit, it does a lot more than just this.

Named capturing groups in JavaScript regex?

Don't have ECMAScript 2018?

My goal was to make it work as similar as possible to what we are used to with named groups. Whereas in ECMAScript 2018 you can place ?<groupname> inside the group to indicate a named group, in my solution for older javascript, you can place (?!=<groupname>) inside the group to do the same thing. So it's an extra set of parenthesis and an extra !=. Pretty close!

I wrapped all of it into a string prototype function

Features

  • works with older javascript
  • no extra code
  • pretty simple to use
  • Regex still works
  • groups are documented within the regex itself
  • group names can have spaces
  • returns object with results

Instructions

  • place (?!={groupname}) inside each group you want to name
  • remember to eliminate any non-capturing groups () by putting ?: at the beginning of that group. These won't be named.

arrays.js

// @@pattern - includes injections of (?!={groupname}) for each group
// @@returns - an object with a property for each group having the group's match as the value 
String.prototype.matchWithGroups = function (pattern) {
  var matches = this.match(pattern);
  return pattern
  // get the pattern as a string
  .toString()
  // suss out the groups
  .match(/<(.+?)>/g)
  // remove the braces
  .map(function(group) {
    return group.match(/<(.+)>/)[1];
  })
  // create an object with a property for each group having the group's match as the value 
  .reduce(function(acc, curr, index, arr) {
    acc[curr] = matches[index + 1];
    return acc;
  }, {});
};    

usage

function testRegGroups() {
  var s = '123 Main St';
  var pattern = /((?!=<house number>)\d+)\s((?!=<street name>)\w+)\s((?!=<street type>)\w+)/;
  var o = s.matchWithGroups(pattern); // {'house number':"123", 'street name':"Main", 'street type':"St"}
  var j = JSON.stringify(o);
  var housenum = o['house number']; // 123
}

result of o

{
  "house number": "123",
  "street name": "Main",
  "street type": "St"
}

Android load from URL to Bitmap

public Drawable loadImageFromURL(String url, String name) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, name);
        return d;
    } catch (Exception e) {
        return null;
    }
}

Get file content from URL?

$url = "https://chart.googleapis....";
$json = file_get_contents($url);

Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

$data = json_decode($json);
var_dump($data);

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++ with win32/GDI is relatively easy to get going, but far more difficult than say Flash or Python (pygame) - however, by using C++ you'll learn a lot in the process and be well poised to continue advancing your career as a game developer. You can also look into XNA if you want to program to the xbox360.

I took some classes at Game Institute (GI) and learned a lot about C++, win32 API and DirectX.

Comparing two arrays & get the values which are not common

Collection

$a = 1..5
$b = 4..8

$Yellow = $a | Where {$b -NotContains $_}

$Yellow contains all the items in $a except the ones that are in $b:

PS C:\> $Yellow
1
2
3

$Blue = $b | Where {$a -NotContains $_}

$Blue contains all the items in $b except the ones that are in $a:

PS C:\> $Blue
6
7
8

$Green = $a | Where {$b -Contains $_}

Not in question, but anyways; Green contains the items that are in both $a and $b.

PS C:\> $Green
4
5

Note: Where is an alias of Where-Object. Alias can introduce possible problems and make scripts hard to maintain.


Addendum 12 October 2019

As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).

Union

The symmetric difference between the $a and $b can be literally defined as the union of $Yellow and $Blue:

$NotGreen = $Yellow + $Blue

Which is written out:

$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})

Performance

As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a iterate (using Where) through items in list $b (using -NotContains) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b):

$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}

By using the ForEach statement instead of the ForEach-Object cmdlet and the Where method instead of the Where-Object you might increase the performance by a factor 2.5:

$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})

LINQ

But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:

To use LINQ you need to explicitly define the array types:

[Int[]]$a = 1..5
[Int[]]$b = 4..8

And use the [Linq.Enumerable]:: operator:

$Yellow   = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue     = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green    = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))

Benchmark

Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.

Using             Time
Compare-Object    111,9712
NotContains       197,3792
ForEach-Object    82,8324
ForEach Statement 36,5721
LINQ              22,7091

To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.

$a = 1..1000
$b = 500..1500

(Measure-Command {
    Compare-Object -ReferenceObject $a -DifferenceObject $b  -PassThru
}).TotalMilliseconds
(Measure-Command {
    ($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
    $Count = @{}
    $a + $b | ForEach-Object {$Count[$_] += 1}
    $Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds

(Measure-Command {
    $Count = @{}
    ForEach ($Item in $a + $b) {$Count[$Item] += 1}
    $Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds

[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
    [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds

java.lang.IllegalAccessError: tried to access method

I was getting same error because of configuration issue in intellij. As shown in screenshot. Main and test module was pointing to two different JDK. (Press F12 on the intellij project to open module settings)

Also all my dto's were using @lombok.Builder which I changed it to @Data.

enter image description here

enter image description here

How can I delete a query string parameter in JavaScript?

Using jQuery:

function removeParam(key) {
    var url = document.location.href;
    var params = url.split('?');
    if (params.length == 1) return;

    url = params[0] + '?';
    params = params[1];
    params = params.split('&');

    $.each(params, function (index, value) {
        var v = value.split('=');
        if (v[0] != key) url += value + '&';
    });

    url = url.replace(/&$/, '');
    url = url.replace(/\?$/, '');

    document.location.href = url;
}

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

How to get height of <div> in px dimension

There is a built-in method to get the bounding rectangle: Element.getBoundingClientRect.

The result is the smallest rectangle which contains the entire element, with the read-only left, top, right, bottom, x, y, width, and height properties.

See the example below:

_x000D_
_x000D_
let innerBox = document.getElementById("myDiv").getBoundingClientRect().height;_x000D_
document.getElementById("data_box").innerHTML = "height: " + innerBox;
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.relative {_x000D_
  width: 220px;_x000D_
  height: 180px;_x000D_
  position: relative;_x000D_
  background-color: purple;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 30px;_x000D_
  left: 20px;_x000D_
  background-color: orange;_x000D_
  padding: 30px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#myDiv {_x000D_
  margin: 20px;_x000D_
  padding: 10px;_x000D_
  color: red;_x000D_
  font-weight: bold;_x000D_
  background-color: yellow;_x000D_
}_x000D_
_x000D_
#data_box {_x000D_
  font: 30px arial, sans-serif;_x000D_
}
_x000D_
Get height of <mark>myDiv</mark> in px dimension:_x000D_
<div id="data_box"></div>_x000D_
<div class="relative">_x000D_
  <div class="absolute">_x000D_
    <div id="myDiv">myDiv</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Find and copy files

i faced an issue something like this...

Actually, in two ways you can process find command output in copy command

  1. If find command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:

    Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>

    Example: find -mtime -1 -type f | xargs cp -t inner/

  2. But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:

    Syntax: find <path> <condition> -exec cp '{}' <copy path> \;

    Example find -mtime -1 -type f -exec cp '{}' inner/ \;

In the second example, last part i.e semi-colon is also considered as part of find command, that should be escaped before press the enter button. Otherwise you will get an error something like this

find: missing argument to `-exec'

In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend. The following command will work:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp  {} /home/shantanu/tosend \;

Generic Property in C#

You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.

How to define hash tables in Bash?

Bash 4

Bash 4 natively supports this feature. Make sure your script's hashbang is #!/usr/bin/env bash or #!/bin/bash so you don't end up using sh. Make sure you're either executing your script directly, or execute script with bash script. (Not actually executing a Bash script with Bash does happen, and will be really confusing!)

You declare an associative array by doing:

declare -A animals

You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of animal[sound(key)] = animal(value):

animals=( ["moo"]="cow" ["woof"]="dog")

Or merge them:

declare -A animals=( ["moo"]="cow" ["woof"]="dog")

Then use them just like normal arrays. Use

  • animals['key']='value' to set value

  • "${animals[@]}" to expand the values

  • "${!animals[@]}" (notice the !) to expand the keys

Don't forget to quote them:

echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done

Bash 3

Before bash 4, you don't have associative arrays. Do not use eval to emulate them. Avoid eval like the plague, because it is the plague of shell scripting. The most important reason is that eval treats your data as executable code (there are many other reasons too).

First and foremost: Consider upgrading to bash 4. This will make the whole process much easier for you.

If there's a reason you can't upgrade, declare is a far safer option. It does not evaluate data as bash code like eval does, and as such does not allow arbitrary code injection quite so easily.

Let's prepare the answer by introducing the concepts:

First, indirection.

$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow

Secondly, declare:

$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow

Bring them together:

# Set a value:
declare "array_$index=$value"

# Get a value:
arrayGet() { 
    local array=$1 index=$2
    local i="${array}_$index"
    printf '%s' "${!i}"
}

Let's use it:

$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow

Note: declare cannot be put in a function. Any use of declare inside a bash function turns the variable it creates local to the scope of that function, meaning we can't access or modify global arrays with it. (In bash 4 you can use declare -g to declare global variables - but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)

Summary:

  • Upgrade to bash 4 and use declare -A for associative arrays.
  • Use the declare option if you can't upgrade.
  • Consider using awk instead and avoid the issue altogether.

Python: Differentiating between row and column vectors

The vector you are creating is neither row nor column. It actually has 1 dimension only. You can verify that by

  • checking the number of dimensions myvector.ndim which is 1
  • checking the myvector.shape, which is (3,) (a tuple with one element only). For a row vector is should be (1, 3), and for a column (3, 1)

Two ways to handle this

  • create an actual row or column vector
  • reshape your current one

You can explicitly create a row or column

row = np.array([    # one row with 3 elements
   [1, 2, 3]
]
column = np.array([  # 3 rows, with 1 element each
    [1],
    [2],
    [3]
])

or, with a shortcut

row = np.r_['r', [1,2,3]]     # shape: (1, 3)
column = np.r_['c', [1,2,3]]  # shape: (3,1)

Alternatively, you can reshape it to (1, n) for row, or (n, 1) for column

row = my_vector.reshape(1, -1)
column = my_vector.reshape(-1, 1)

where the -1 automatically finds the value of n.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

How to change the sender's name or e-mail address in mutt?

Normally, mutt sets the From: header based on the from configuration variable you set in ~/.muttrc:

set from="Fubar <foo@bar>"

If this is not set, mutt uses the EMAIL environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):

EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"

However, if you want to be able to edit the From: header while composing, you need to configure mutt to allow you to edit headers first. This involves adding the following line in your ~/.muttrc:

set edit_headers=yes

After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From: header.

filtering NSArray into a new NSArray in Objective-C

Another category method you could use:

- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {
    NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                                       return block(obj);
                                   }];

    return [self objectsAtIndexes:filteredIndexes];
}

Display rows with one or more NaN values in pandas dataframe

You can use DataFrame.any with parameter axis=1 for check at least one True in row by DataFrame.isna with boolean indexing:

df1 = df[df.isna().any(axis=1)]

d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')

print (df)
                             alpha1  alpha2    gamma1    gamma2       chi2min
filename                                                                     
M66_MI_NSRh35d32kpoints.dat  0.8016  0.9283  1.000000  0.074804  3.985599e+01
F71_sMI_DMRI51d.dat          0.0000  0.0000       NaN  0.000000  1.000000e+25
F62_sMI_St22d7.dat           1.7210  3.8330  0.237480  0.150000  1.091832e+01
F41_Car_HOC498d.dat          1.1670  2.8090  0.364190  0.300000  7.966335e+00
F78_MI_547d.dat              1.8970  5.4590  0.095319       NaN  2.593468e+01

Explanation:

print (df.isna())
                            alpha1 alpha2 gamma1 gamma2 chi2min
filename                                                       
M66_MI_NSRh35d32kpoints.dat  False  False  False  False   False
F71_sMI_DMRI51d.dat          False  False   True  False   False
F62_sMI_St22d7.dat           False  False  False  False   False
F41_Car_HOC498d.dat          False  False  False  False   False
F78_MI_547d.dat              False  False  False   True   False

print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat    False
F71_sMI_DMRI51d.dat             True
F62_sMI_St22d7.dat             False
F41_Car_HOC498d.dat            False
F78_MI_547d.dat                 True
dtype: bool

df1 = df[df.isna().any(axis=1)]
print (df1)
                     alpha1  alpha2    gamma1  gamma2       chi2min
filename                                                           
F71_sMI_DMRI51d.dat   0.000   0.000       NaN     0.0  1.000000e+25
F78_MI_547d.dat       1.897   5.459  0.095319     NaN  2.593468e+01

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to remove carriage return and newline from a variable in shell script

Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

Is there a way for non-root processes to bind to "privileged" ports on Linux?

systemd is a sysvinit replacement which has an option to launch a daemon with specific capabilities. Options Capabilities=, CapabilityBoundingSet= in systemd.exec(5) manpage.

How to fix corrupted git repository?

I wanted to add this as a comment under Zoey Hewil's awesome answer above, but I don't currently have enough rep to do so, so I have to add it here and give credit for her work :P

If you're using Poshgit and are feeling exceptionally lazy, you can use the following to automatically extract your URL from your git config and make an easy job even easier. Standard caveats apply about testing this on a copy/backing up your local repo first in case it blows up in your face.

$config = get-content .git\config
$url = $config -match " url = (?<content>.*)"
$url = $url.trim().Substring(6)
$url

move-item -v .git .git_old;
git init;
git remote add origin "$url";
git fetch;
git reset origin/master --mixed

How to configure PHP to send e-mail?

configure your php.ini like this

SMTP = smtp.gmail.com

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury

; SMTP = smtp.gmail.com

; smtp_port = 465

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

What is the most efficient way to deep clone an object in JavaScript?

For a shallow copy there is a great, simple method introduced in ECMAScript2018 standard. It involves the use of Spread Operator :

let obj = {a : "foo", b:"bar" , c:10 , d:true , e:[1,2,3] };

let objClone = { ...obj };

I have tested it in Chrome browser, both objects are stored in different locations, so changing immediate child values in either will not change the other. Though (in the example) changing a value in e will effect both copies.

This technique is very simple and straight forward. I consider this a true Best Practice for this question once and for all.

iOS 7 status bar overlapping UI

For iPhoneX

For all the answers above :

The height of the status bar in the iPhoneX is 44 and not 20

Remove innerHTML from div

To remove all child elements from your div:

$('#mysweetdiv').empty();

.removeData() and the corresponding .data() function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:

var $li = $('<li>Joe</li>').data('id', 25);

"document.getElementByClass is not a function"

If you wrote this "getElementByClassName" then you will encounter with this error "document.getElementByClass is not a function" so to overcome that error just write "getElementsByClassName". Because it should be Elements not Element.

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows:

  • Ctrl+K,Ctrl+U for UPPERCASE.
  • Ctrl+K,Ctrl+L for lowercase.

Method 1 (Two keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K, release K while holding Ctrl. (Do not release the Ctrl key)
  3. Immediately, press U (for uppercase) OR L (for lowercase) with Ctrl still being pressed, then release all pressed keys.

Method 2 (3 keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K.
  3. Without releasing Ctrl and K, immediately press U (for uppercase) OR L (for lowercase) and release all pressed keys.

Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.

I use the above shortcuts, and they work on my Windows system.

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

Guava's function Maps.transformValues is what you are looking for, and it works nicely with lambda expressions:

Maps.transformValues(originalMap, val -> ...)

Print number of keys in Redis

Since Redis 2.6, lua is supported, you can get number of wildcard keys like this

eval "return #redis.call('keys', 'prefix-*')" 0

see eval command

Run script on mac prompt "Permission denied"

You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.

So try:

sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

If this doesn't work, try adapting the permissions:

sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme

How to check if a file contains a specific string using Bash

Shortest (correct) version:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

can be also written as

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

but you dont need to explicitly test it in this case, so the same with:

grep -q "something" file && echo "yes" || echo "no"

How to determine CPU and memory consumption from inside a process?

For Linux You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status

See http://man7.org/linux/man-pages/man5/proc.5.html

   /proc/[pid]/statm
          Provides information about memory usage, measured in pages.
          The columns are:

              size       (1) total program size
                         (same as VmSize in /proc/[pid]/status)
              resident   (2) resident set size
                         (same as VmRSS in /proc/[pid]/status)
              shared     (3) number of resident shared pages (i.e., backed by a file)
                         (same as RssFile+RssShmem in /proc/[pid]/status)
              text       (4) text (code)
              lib        (5) library (unused since Linux 2.6; always 0)
              data       (6) data + stack
              dt         (7) dirty pages (unused since Linux 2.6; always 0)

Open URL in Java to get the content

It may be more useful to use a http client library like such as this

There are more things like access denied , document moved etc to handle when dealing with http.

(though, it is unlikely in this case)

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Android SeekBar setOnSeekBarChangeListener

Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically

volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

How to overlay density plots in R?

You can use the ggjoy package. Let's say that we have three different beta distributions such as:

set.seed(5)
b1<-data.frame(Variant= "Variant 1", Values = rbeta(1000, 101, 1001))
b2<-data.frame(Variant= "Variant 2", Values = rbeta(1000, 111, 1011))
b3<-data.frame(Variant= "Variant 3", Values = rbeta(1000, 11, 101))


df<-rbind(b1,b2,b3)

You can get the three different distributions as follows:

library(tidyverse)
library(ggjoy)


ggplot(df, aes(x=Values, y=Variant))+
    geom_joy(scale = 2, alpha=0.5) +
    scale_y_discrete(expand=c(0.01, 0)) +
    scale_x_continuous(expand=c(0.01, 0)) +
    theme_joy()

enter image description here

Resolve absolute path from relative path and/or file name

SET CD=%~DP0

SET REL_PATH=%CD%..\..\build\

call :ABSOLUTE_PATH    ABS_PATH   %REL_PATH%

ECHO %REL_PATH%

ECHO %ABS_PATH%

pause

exit /b

:ABSOLUTE_PATH

SET %1=%~f2

exit /b

Playing .mp3 and .wav in Java?

Use this library: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}

Is it better in C++ to pass by value or pass by constant reference?

Depends on the type. You are adding the small overhead of having to make a reference and dereference. For types with a size equal or smaller than pointers that are using the default copy ctor, it would probably be faster to pass by value.

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

return(
  data.frame(
    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE
  )
)

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

Find mouse position relative to element

canvas.onmousedown = function(e) {
    pos_left = e.pageX - e.currentTarget.offsetLeft;
    pos_top = e.pageY - e.currentTarget.offsetTop;
    console.log(pos_left, pos_top)
}

HTMLElement.offsetLeft

The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node.

For block-level elements, offsetTop, offsetLeft, offsetWidth, and offsetHeight describe the border box of an element relative to the offsetParent.

However, for inline-level elements (such as span) that can wrap from one line to the next, offsetTop and offsetLeft describe the positions of the first border box (use Element.getClientRects() to get its width and height), while offsetWidth and offsetHeight describe the dimensions of the bounding border box (use Element.getBoundingClientRect() to get its position). Therefore, a box with the left, top, width and height of offsetLeft, offsetTop, offsetWidth and offsetHeight will not be a bounding box for a span with wrapped text.

HTMLElement.offsetTop

The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.

MouseEvent.pageX

The pageX read-only property returns the X (horizontal) coordinate in pixels of the event relative to the whole document. This property takes into account any horizontal scrolling of the page.

MouseEvent.pageY

The MouseEvent.pageY read-only property returns the Y (vertical) coordinate in pixels of the event relative to the whole document. This property takes into account any vertical scrolling of the page.

For further explanation, please see the Mozilla Developer Network:

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageY https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

Select single item from a list

just saw this now, if you are working with a list of object you can try this

 public class user
{
    public string username { get; set; }
    public string password { get; set; }
}

  List<user> userlist = new List<user>();

        userlist.Add(new user { username = "macbruno", password = "1234" });
        userlist.Add(new user { username = "james", password = "5678" });
        string myusername = "james";
        string mypassword = "23432";

  user theUser = userlist.Find(
            delegate (user thisuser)
            {
                return thisuser.username== myusername && thisuser.password == mypassword;
            }
            );

            if (theUser != null)
            {
               Dosomething();
            }
            else
            {
                DoSomethingElse();

            }

Git push failed, "Non-fast forward updates were rejected"

I've hade the same problem. I resolved with

git checkout <name branch>
git pull origin <name branch>
git push origin <name branch>

How to use fetch in typescript

A few examples follow, going from basic through to adding transformations after the request and/or error handling:

Basic:

// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<T>()
    })

}

// Consumer
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Data transformations:

Often you may need to do some tweaks to the data before its passed to the consumer, for example, unwrapping a top level data attribute. This is straight forward:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => { /* <-- data inferred as { data: T }*/
      return data.data
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Error handling:

I'd argue that you shouldn't be directly error catching directly within this service, instead, just allowing it to bubble, but if you need to, you can do the following:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => {
      return data.data
    })
    .catch((error: Error) => {
      externalErrorLogging.error(error) /* <-- made up logging service */
      throw error /* <-- rethrow the error so consumer can still catch it */
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Edit

There has been some changes since writing this answer a while ago. As mentioned in the comments, response.json<T> is no longer valid. Not sure, couldn't find where it was removed.

For later releases, you can do:

// Standard variation
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<T>
    })
}


// For the "unwrapping" variation

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<{ data: T }>
    })
    .then(data => {
        return data.data
    })
}

Getting error "No such module" using Xcode, but the framework is there

IF you have done everything above and still nothing worked for you then try adding $(inherited) in Framework search path of your target's build setting.

How to set image width to be 100% and height to be auto in react native?

I've found a solution for width: "100%", height: "auto" if you know the aspectRatio (width / height) of the image.

Here's the code:

import { Image, StyleSheet, View } from 'react-native';

const image = () => (
    <View style={styles.imgContainer}>
        <Image style={styles.image} source={require('assets/images/image.png')} />
    </View>
);

const style = StyleSheet.create({
    imgContainer: {
        flexDirection: 'row'
    },
    image: {
        resizeMode: 'contain',
        flex: 1,
        aspectRatio: 1 // Your aspect ratio
    }
});

This is the most simplest way I could get it to work without using onLayout or Dimension calculations. You can even wrap it in a simple reusable component if needed. Give it a shot if anyone is looking for a simple implementation.

How to get ° character in a string in python?

just use \xb0 (in a string); python will convert it automatically

How can I change the language (to english) in Oracle SQL Developer?

You can also set language at runtime

sqldeveloper.exe --AddVMOption=-Duser.language=en

to avoid editing sqldeveloper.conf every time you install new version.

How do I calculate percentiles with python/numpy?

A convenient way to calculate percentiles for a one-dimensional numpy sequence or matrix is by using numpy.percentile <https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html>. Example:

import numpy as np

a = np.array([0,1,2,3,4,5,6,7,8,9,10])
p50 = np.percentile(a, 50) # return 50th percentile, e.g median.
p90 = np.percentile(a, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median =  5.0  and p90 =  9.0

However, if there is any NaN value in your data, the above function will not be useful. The recommended function to use in that case is the numpy.nanpercentile <https://docs.scipy.org/doc/numpy/reference/generated/numpy.nanpercentile.html> function:

import numpy as np

a_NaN = np.array([0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.])
a_NaN[0] = np.nan
print('a_NaN',a_NaN)
p50 = np.nanpercentile(a_NaN, 50) # return 50th percentile, e.g median.
p90 = np.nanpercentile(a_NaN, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median =  5.5  and p90 =  9.1

In the two options presented above, you can still choose the interpolation mode. Follow the examples below for easier understanding.

import numpy as np

b = np.array([1,2,3,4,5,6,7,8,9,10])
print('percentiles using default interpolation')
p10 = np.percentile(b, 10) # return 10th percentile.
p50 = np.percentile(b, 50) # return 50th percentile, e.g median.
p90 = np.percentile(b, 90) # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  1.9 , median =  5.5  and p90 =  9.1

print('percentiles using interpolation = ', "linear")
p10 = np.percentile(b, 10,interpolation='linear') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='linear') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='linear') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  1.9 , median =  5.5  and p90 =  9.1

print('percentiles using interpolation = ', "lower")
p10 = np.percentile(b, 10,interpolation='lower') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='lower') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='lower') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  1 , median =  5  and p90 =  9

print('percentiles using interpolation = ', "higher")
p10 = np.percentile(b, 10,interpolation='higher') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='higher') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='higher') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  2 , median =  6  and p90 =  10

print('percentiles using interpolation = ', "midpoint")
p10 = np.percentile(b, 10,interpolation='midpoint') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='midpoint') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='midpoint') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  1.5 , median =  5.5  and p90 =  9.5

print('percentiles using interpolation = ', "nearest")
p10 = np.percentile(b, 10,interpolation='nearest') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='nearest') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='nearest') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 =  2 , median =  5  and p90 =  9

If your input array only consists of integer values, you might be interested in the percentil answer as an integer. If so, choose interpolation mode such as ‘lower’, ‘higher’, or ‘nearest’.

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string 
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.

How to loop backwards in python?

All of these three solutions give the same results if the input is a string:

1.

def reverse(text):
    result = ""
    for i in range(len(text),0,-1):
        result += text[i-1]
    return (result)

2.

text[::-1]

3.

"".join(reversed(text))

How can I label points in this scatterplot?

Your call to text() doesn't output anything because you inverted your x and your y:

plot(abs_losses, percent_losses, 
     main= "Absolute Losses vs. Relative Losses(in%)",
     xlab= "Losses (absolute, in miles of millions)",
     ylab= "Losses relative (in % of January´2007 value)",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(abs_losses, percent_losses, labels=namebank, cex= 0.7)

Now if you want to move your labels down, left, up or right you can add argument pos= with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:

 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)

enter image description here

You can of course gives a vector of value to pos if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):

 pos_vector <- rep(3, length(namebank))
 pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)

enter image description here

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
    IF NOT <@PortfolioID contains Comma>
    BEGIN
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
    END ELSE
    BEGIN
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>
    END
END

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.

regular expression for anything but an empty string

You could also use:

public static bool IsWhiteSpace(string s) 
{
    return s.Trim().Length == 0;
}

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I had the same problems, but using easy_install "module" solved the problem for me.

I am not sure why, but pip and easy_install use different install locations, and easy_install chose the right ones.

Edit: without re-checking but because of the comments; it seems that different (OSX and brew-installed) installations interfere with each other which is why they tools mentioned indeed point to different locations (since they belong to different installations). I understand that usually those tools from one install point to the same folder.

How can I add spaces between two <input> lines using CSS?

You can also wrap your text in label fields, so your form will be more self-explainable semantically.

Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).

That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.

For example:

<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>

And the css will be:

form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}

How to make a div fill a remaining horizontal space?

Rules for items and containers;

Container: {*** display: table; ***}
Items: {*** display: table-cell; width: 100%; ***}

Use white-space: nowrap; for texts in last items for their undestructuring.

Item X% | Item Y% | Item Z%

Total length always = 100%!

if

Item X=50%
Item Y=10%
Item z=20%

then

Item X=70%

Item X is dominant (first items are dominant in table CSS layout)!

Try max-content; property for div inside for spreading div in container:

div[class="item"] {
...
  width: -webkit-max-content;
  width: -moz-max-content;
  width: max-content;
...

}

TypeError: got multiple values for argument

This exception also will be raised whenever a function has been called with the combination of keyword arguments and args, kwargs

Example:

def function(a, b, c, *args, **kwargs):
    print(f"a: {a}, b: {b}, c: {c}, args: {args}, kwargs: {kwargs}")

function(a=1, b=2, c=3, *(4,))

And it'll raise:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-1dcb84605fe5> in <module>
----> 1 function(a=1, b=2, c=3, *(4,))

TypeError: function() got multiple values for argument 'a'

And Also it'll become more complicated, whenever you misuse it in the inheritance. so be careful we this stuff!

1- Calling a function with keyword arguments and args:

class A:
    def __init__(self, a, b, *args, **kwargs):
        self.a = a
        self.b = b
    
class B(A):
    def __init__(self, *args, **kwargs):

        a = 1
        b = 2
        super(B, self).__init__(a=a, b=b, *args, **kwargs)

B(3, c=2)

Exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-17e0c66a5a95> in <module>
     11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
---> 13 B(3, c=2)

<ipython-input-5-17e0c66a5a95> in __init__(self, *args, **kwargs)
      9         a = 1
     10         b = 2
---> 11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
     13 B(3, c=2)

TypeError: __init__() got multiple values for argument 'a'

2- Calling a function with keyword arguments and kwargs which it contains keyword arguments too:

class A:
    def __init__(self, a, b, *args, **kwargs):
        self.a = a
        self.b = b
    
class B(A):
    def __init__(self, *args, **kwargs):

        a = 1
        b = 2
        super(B, self).__init__(a=a, b=b, *args, **kwargs)

B(**{'a': 2})

Exception:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c465f5581810> in <module>
     11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
---> 13 B(**{'a': 2})

<ipython-input-7-c465f5581810> in __init__(self, *args, **kwargs)
      9         a = 1
     10         b = 2
---> 11         super(B, self).__init__(a=a, b=b, *args, **kwargs)
     12 
     13 B(**{'a': 2})

TypeError: __init__() got multiple values for keyword argument 'a'

Selecting last element in JavaScript array

var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]

This will return undefined if the array is empty and this will not change the value of the array.

Scroll part of content in fixed position container

Actually this is better way to do that. If height: 100% is used, the content goes off the border, but when it is 95% everything is in order:

div#scrollable {
    overflow-y: scroll;
    height: 95%;
}

How to show disable HTML select option in by default?

use

<option selected="true" disabled="disabled">Choose Tagging</option>    

error while loading shared libraries: libncurses.so.5:

If you are absolutely sure that libncurses, aka ncurses, is installed, as in you've done a successful 'ls' of the library, then perhaps you are running a 64 bit Linux operating system and only have the 64 bit libncurses installed, when the program that is running (adb) is 32 bit.

If so, a 32 bit program can't link to a 64 bit library (and won't located it anyway), so you might have to install libcurses, or ncurses (32 bit version). Likewise, if you are running a 64 bit adb, perhaps your ncurses is 32 bit (a possible but less likely scenario).

ReflectionException: Class ClassName does not exist - Laravel

Check your capitalization!

Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.

Whenever you get a ClassNotFound Exception check the following:

  1. Spelling
  2. Namespaces
  3. Capitalization

How to automatically insert a blank row after a group of data

I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:

  1. I sorted my file according to control fields
  2. I added a column to the file
  3. I used the "IF" function to determine when there is a change in the control data .
  4. If there is a change the result will indicate "yes", otherwise "no"
  5. Then I filtered the data to group all "yes" items
  6. I copied mutual fund names, folio number etc (no financial data)
  7. Then I removed the filter and sorted the file again. The result is a row added at the desired place. (It is not entirely a blank row, because if it is fully blank, sorting will not place the row at the desired place.)
  8. After sorting, you can easily delete all values to get a completely blank row.

This method also may be tried by the readers.

Check if value already exists within list of dictionaries?

Based on @Mark Byers great answer, and following @Florent question, just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:

names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})

if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):

    print('Not exists!')
else:
    print('Exists!')

Result:

Exists!

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

How to lowercase a pandas dataframe string column if it has missing values?

May be using List comprehension

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']] 

print(df)

Golang append an item to a slice

Go takes a more lean and lazy approach in doing this. It keeps modifying the same underlying array until the capacity of a slice is reached.

Ref: http://criticalindirection.com/2016/02/17/slice-with-a-pinch-of-salt/

Output of the example from the link explains the behavior of slices in Go.

Creating slice a.

Slice a len=7 cap=7 [0 0 0 0 0 0 0]

Slice b refers to the 2, 3, 4 indices in slice a. Hence, the capacity is 5 (= 7-2).

b := a[2:5]
Slice b len=3 cap=5 [0 0 0]

Modifying slice b, also modifies a, since they are pointing to the same underlying array.

b[0] = 9
Slice a len=7 cap=7 [0 0 9 0 0 0 0]
Slice b len=3 cap=5 [9 0 0]

Appending 1 to slice b. Overwrites a.

Slice a len=7 cap=7 [0 0 9 0 0 1 0]
Slice b len=4 cap=5 [9 0 0 1]

Appending 2 to slice b. Overwrites a.

Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=5 cap=5 [9 0 0 1 2]

Appending 3 to slice b. Here, a new copy is made as the capacity is overloaded.

Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 0 0 1 2 3]

Verifying slices a and b point to different underlying arrays after the capacity-overload in the previous step.

b[1] = 8
Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 8 0 1 2 3]

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

PHP remove all characters before specific string

I use this functions

function strright($str, $separator) {
    if (intval($separator)) {
        return substr($str, -$separator);
    } elseif ($separator === 0) {
        return $str;
    } else {
        $strpos = strpos($str, $separator);

        if ($strpos === false) {
            return $str;
        } else {
            return substr($str, -$strpos + 1);
        }
    }
}

function strleft($str, $separator) {
    if (intval($separator)) {
        return substr($str, 0, $separator);
    } elseif ($separator === 0) {
        return $str;
    } else {
        $strpos = strpos($str, $separator);

        if ($strpos === false) {
            return $str;
        } else {
            return substr($str, 0, $strpos);
        }
    }
}

How to truncate text in Angular2?

Limit length based on words

Try this one, if you want to truncate based on Words instead of characters while also allowing an option to see the complete text.

Came here searching for a Read More solution based on words, sharing the custom Pipe i ended up writing.

Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {

  transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
    
    if (showAll) {
      return text;
    }

    if ( text.split(" ").length > length ) {
      
      return text.split(" ").splice(0, length).join(" ") + suffix;
    }

    return text;
  }

}

In Template:

<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>

Component:

export class ExamplePage implements OnInit {

    public showAll: any = false;
    
    triggerReadMore() {
        this.showAll = true;
    }
    
}

In Module:

import { ReadMorePipe } from '../_helpers/read-more.pipe';

@NgModule({
  declarations: [ReadMorePipe]
})
export class ExamplePageModule {}

Changing Java Date one hour back

Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!

    int minutes = 60;
    long currentDateTime = System.currentTimeMillis();
    Date currentDate = new Date(currentDateTime - minutes*60*1000);
    System.out.println(currentDate);

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

With mysql Ver 14.14 Distrib 5.7.22 the update statement is now:

update user set authentication_string=password('1111') where user='root';

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to find file accessed/created just few minutes ago

If you know the file is in your current directory, I would use:

ls -lt | head

This lists your most recently modified files and directories in order. In fact, I use it so much I have it aliased to 'lh'.

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

@Directive vs @Component in Angular

Components

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Our application in Angular is built on a component tree. Every component should have its template, styling, life cycle, selector, etc. So, every component has its structure You can treat them as an apart standalone small web application with own template and logic and a possibility to communicate and be used together with other components.

Sample .ts file for Component:

import { Component } from '@angular/core';

@Component({
    // component attributes
    selector: 'app-training',
    templateUrl: './app-training.component.html',
    styleUrls: ['./app-training.component.less']
})

export class AppTrainingComponent {
    title = 'my-app-training';
}

and its ./app.component.html template view:

Hello {{title}}

Then you can render AppTrainingComponent template with its logic in other components (after adding it into module)

<div>
   <app-training></app-training>
</div>

and the result will be

<div>
   my-app-training
</div>

as AppTrainingComponent was rendered here

See more about Components

Directives

Directive changes the appearance or behavior of an existing DOM element. For example [ngStyle] is a directive. Directives can extend components (can be used inside them) but they don't build a whole application. Let's say they just support components. They don't have its own template (but of course, you can manipulate template with them).

Sample directive:

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @Input('appHighlight') highlightColor: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || 'red');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

And its usage:

<p [appHighlight]="color" [otherPar]="someValue">Highlight me!</p>

See more about directives

Clear Application's Data Programmatically

There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().

I highly recommend using it in new applications:

import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.

Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.


Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.

private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

Android Studio - Unable to find valid certification path to requested target

I had this problem today after upgrading to Android Studio 3.2 Beta 2. I had configured my JDK for OpenJDK 10.0.1, and it threw this error after upgrading. I set the JDK back to using the enbedded JDK, and the error went away.enter image description here

I have no idea why it worked fine before I upgraded to Beta 2, but all is good now. Honestly I guess there is no need for OpenJDK 10 for Android.

Access event to call preventdefault from custom function originating from onclick attribute of tag

The simplest solution simply is:

<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>

It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)

<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' + 
Math.round(new Date().getTime() / 1000);" 
href="http://www.domain.com/docs/thingy.pdf">

If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.

How to create a dynamic array of integers

You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.

http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                 // all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

How to create a backup of a single table in a postgres database?

Use --table to tell pg_dump what table it has to backup:

pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname

What is ":-!!" in C code?

This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO, rather than ...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)

You should read the expression like this:

sizeof(struct { int: -!!(e); }))
  1. (e): Compute expression e.

  2. !!(e): Logically negate twice: 0 if e == 0; otherwise 1.

  3. -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.

  4. struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.

  5. struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof that field, so we get a size_t with the appropriate width (which will be zero in the case where e is zero).


Some people have asked: Why not just use an assert?

keithmo's answer here has a good response:

These macros implement a compile-time test, while assert() is a run-time test.

Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

Make javascript alert Yes/No Instead of Ok/Cancel

"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

On Windows make sure your Windows firewall is correctly configure / disabled. I had to disable the Windows firewall (because I didn't bother with configuring it) to get things to work even when I was testing with localhost.

How to check iOS version?

Add the Swift code below in your project and access information such as iOS version and device easily.

class DeviceInfo: NSObject {

    struct ScreenSize
    {
        static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
        static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
        static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
        static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    }

    struct DeviceType
    {
        static let IS_IPHONE_4_OR_LESS =  UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
        static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
        static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH >= 667.0
        static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
        static let IS_IPHONE_X = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
        static let IS_IPAD      = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
        static let IS_IPAD_PRO  = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
    }

    struct VersionType{
        static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
        static let iOS7 = (VersionType.SYS_VERSION_FLOAT < 8.0 && VersionType.SYS_VERSION_FLOAT >= 7.0)
        static let iOS8 = (VersionType.SYS_VERSION_FLOAT >= 8.0 && VersionType.SYS_VERSION_FLOAT < 9.0)
        static let iOS9 = (VersionType.SYS_VERSION_FLOAT >= 9.0 && VersionType.SYS_VERSION_FLOAT < 10.0)
        static let iOS10 = (VersionType.SYS_VERSION_FLOAT >= 9.0 && VersionType.SYS_VERSION_FLOAT < 11.0)
    }
}

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

For Jar

Add pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Bash script prints "Command Not Found" on empty lines

Problems with running scripts may also be connected to bad formatting of multi-line commands, for example if you have a whitespace character after line-breaking "\". E.g. this:

./run_me.sh \ 
--with-some parameter

(please note the extra space after "\") will cause problems, but when you remove that space, it will run perfectly fine.

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

Best way to randomize an array with .NET

You can also make an extention method out of Matt Howells. Example.

   namespace System
    {
        public static class MSSystemExtenstions
        {
            private static Random rng = new Random();
            public static void Shuffle<T>(this T[] array)
            {
                rng = new Random();
                int n = array.Length;
                while (n > 1)
                {
                    int k = rng.Next(n);
                    n--;
                    T temp = array[n];
                    array[n] = array[k];
                    array[k] = temp;
                }
            }
        }
    }

Then you can just use it like:

        string[] names = new string[] {
                "Aaron Moline1", 
                "Aaron Moline2", 
                "Aaron Moline3", 
                "Aaron Moline4", 
                "Aaron Moline5", 
                "Aaron Moline6", 
                "Aaron Moline7", 
                "Aaron Moline8", 
                "Aaron Moline9", 
            };
        names.Shuffle<string>();

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

What's the best way to validate an XML file against an XSD file?

Here's how to do it using Xerces2. A tutorial for this, here (req. signup).

Original attribution: blatantly copied from here:

import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;

public class SchemaTest {
  public static void main (String args[]) {
      File docFile = new File("memory.xml");
      try {
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setProperty(
             "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", 
             "memory.xsd");
        ErrorChecker errors = new ErrorChecker();
        parser.setErrorHandler(errors);
        parser.parse("memory.xml");
     } catch (Exception e) {
        System.out.print("Problem parsing the file.");
     }
  }
}

How to recursively find and list the latest modified files in a directory with subdirectories and times

Try this one:

#!/bin/bash
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).

If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs instead:

#!/bin/bash
find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head

which is a bit faster.

Check whether a value exists in JSON object

Below function can be used to check for a value in any level in a JSON

function _isContains(json, value) {
    let contains = false;
    Object.keys(json).some(key => {
        contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value;
         return contains;
    });
    return contains;
 }

then to check if JSON contains the value

_isContains(JSONObject, "dog")

See this fiddle: https://jsfiddle.net/ponmudi/uykaacLw/

Most of the answers mentioned here compares by 'name' key. But no need to care about the key, can just checks if JSON contains the given value. So that the function can be used to find any value irrespective of the key.

How can I set a DateTimePicker control to a specific date?

If you want to set a date, DateTimePicker.Value is a DateTime object.

DateTimePicker.Value = new DateTime(2012,05,28);

This is the constructor of DateTime:

new DateTime(int year,int month,int date);

My Visual is 2012

How to extract a value from a string using regex and a shell?

you can use the shell(bash for example)

$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45

How do I make a text input non-editable?

if you really want to use CSS, use following property which will make field non-editable.

pointer-events: none;

Difference between two dates in years, months, days in JavaScript

Some math is in order.

You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)

For example:

var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);

var c = a - b; // c equals 2674800000,
               // the amount of milisseconds between September 1, 2010
               // and August 1, 2010.

Now you can get any part you want. For example, how many days have elapsed between the two dates:

var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.

That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.