Programs & Examples On #Ora 00932

Inconsistent datatypes. Cause: You tried to perform an operation between two different datatypes, but the datatypes are not compatible.

Oracle 10g: Extract data (select) from XML (CLOB Type)

In case of :

<?xml version="1.0" encoding="iso-8859-1"?>
<info xmlns="http://namespaces.default" xmlns:ns2="http://namespaces.ns2" >
    <id> 954 </id>
    <idboss> 954 </idboss>
    <name> Fausto </name>
    <sorname> Anonimo </sorname>
    <phone> 040000000 </phone>
    <fax> 040000001 </fax>
</info>

Query :

Select *
from xmltable(xmlnamespaces(default 'http://namespaces.default'
                              'http://namespaces.ns2' as "ns",
                       ), 
                '/info'
                passing xmltype.createxml(xml) 
                columns id varchar2(10) path '/id',
                        idboss varchar2(500) path '/idboss',
                        etc....

                ) nice_xml_table

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

Creating an iframe with given HTML dynamically

The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.

const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I implemented Joseph Johnson solution and it worked well, I noticed after using this solution sometimes the drawer on the application will not close properly. I added a functionality to remove the listener removeOnGlobalLayoutListener when the user closes the fragment where are edittexts located.

    //when the application uses full screen theme and the keyboard is shown the content not scrollable! 
//with this util it will be scrollable once again
//http://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible
public class AndroidBug5497Workaround {


    private static AndroidBug5497Workaround mInstance = null;
    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;
    private ViewTreeObserver.OnGlobalLayoutListener _globalListener;

    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static AndroidBug5497Workaround getInstance (Activity activity) {
        if(mInstance==null)
        {
            synchronized (AndroidBug5497Workaround.class)
            {
                mInstance = new AndroidBug5497Workaround(activity);
            }
        }
        return mInstance;
    }

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();

        _globalListener = new ViewTreeObserver.OnGlobalLayoutListener()
        {

            @Override
            public void onGlobalLayout()
            {
                 possiblyResizeChildOfContent();
            }
        };
    }

    public void setListener()
    {
         mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(_globalListener);
    }

    public void removeListener()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(_globalListener);
        } else {
            mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(_globalListener);
        }
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    } 
}

uses the class where is my edittexts located

@Override
public void onStart()
{
    super.onStart();
    AndroidBug5497Workaround.getInstance(getActivity()).setListener();
}

@Override
public void onStop()
{
    super.onStop();
    AndroidBug5497Workaround.getInstance(getActivity()).removeListener();
}

How to know elastic search installed version from kibana?

To check Version of Your Running Kibana,Try this:

Step1. Start your Kibana Service.

Step2. Open Browser and Type below line,

    localhost:5601

Step3. Go to settings->About

  You can See Version of Your Running kibana.

How to check if an integer is in a given range?

You could add spacing ;)

if (i > 0 && i < 100) 

Fixing npm path in Windows 8 and 10

Edit the System environment variables, and enter following path:

C:\Program Files\nodejs\node.exe;

C:\Users\{yourName}\AppData\Roaming\npm

How do I configure HikariCP in my Spring Boot app in my application.properties files?

Here is the good news. HikariCP is the default connection pool now with Spring Boot 2.0.0.

Spring Boot 2.0.0 Release Notes

The default database pooling technology in Spring Boot 2.0 has been switched from Tomcat Pool to HikariCP. We’ve found that Hakari offers superior performance, and many of our users prefer it over Tomcat Pool.

How to change port for jenkins window service when 8080 is being used

You should follow 2 steps:

  1. This step can be followed by running the cmd in the specific folder location where there will be .war file. This step helpful as Jenkins needs some disk space to perform builds and keep archives.

    set JENKINS_HOME=c:\folder\Jenkins
    
  2. This step will be helpful to change the port number, and works can be performed accordingly.

    java -jar jenkins.war --httpPort=8585
    

How to clear react-native cache?

I had a similar problem, I tried to clear all the caches possible (tried almost all the solutions above) and the only thing that worked for me was to kill the expo app and to restart it.

Changing background colour of tr element on mouseover

tr:hover td.someclass {
   background: #EDB01C;
   color:#FFF;
}

only someclass cell highlight

How to calculate the sum of the datatable column in asp.net?

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

Hibernate table not mapped error in HQL query

Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar, don't pass "foobar". You have to pass "FooBar" with that exact capitalization for it to work.

How to assign a heredoc value to a variable in Bash?

VAR=<<END
abc
END

doesn't work because you are redirecting stdin to something that doesn't care about it, namely the assignment

export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A

works, but there's a back-tic in there that may stop you from using this. Also, you should really avoid using backticks, it's better to use the command substitution notation $(..).

export A=$(cat <<END
sdfsdf
sdfsdf
sdfsfds
END
) ; echo $A

ASP.net vs PHP (What to choose)

You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.

If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.

MySQL skip first 10 results

There is an OFFSET as well that should do the trick:

SELECT column FROM table
LIMIT 10 OFFSET 10

How to stop BackgroundWorker correctly

My answer is a bit different because I've tried these methods but they didn't work. My code uses an extra class that checks for a Boolean flag in a public static class as the database values are read or where I prefer it just before an object is added to a List object or something as such. See the change in the code below. I added the ThreadWatcher.StopThread property. for this explation I'm nog going to reinstate the current thread because it's not your issue but that's as easy as setting the property to false before accessing the next thread...

private void combobox2_TextChanged(object sender, EventArgs e)
 {
  //Stop the thread here with this
     ThreadWatcher.StopThread = true;//the rest of this thread will run normally after the database function has stopped.
     if (cmbDataSourceExtractor.IsBusy)
        cmbDataSourceExtractor.CancelAsync();

     while(cmbDataSourceExtractor.IsBusy)
        Application.DoEvents();

     var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
        V2 = combobox2.Text};
     cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
  }

all fine

private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
 {
      if (this.cmbDataSourceExtractor.CancellationPending)
      {
          e.Cancel = true;
          return;
      }
      // do stuff...
 }

Now add the following class

public static class ThreadWatcher
{
    public static bool StopThread { get; set; }
}

and in your class where you read the database

List<SomeObject>list = new List<SomeObject>();
...
if (!reader.IsDbNull(0))
    something = reader.getString(0);
someobject = new someobject(something);
if (ThreadWatcher.StopThread == true)
    break;
list.Add(something);
...

don't forget to use a finally block to properly close your database connection etc. Hope this helps! Please mark me up if you find it helpful.

How to get the function name from within that function?

This might work for you:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

running foo() will output "foo" or undefined if you call from an anonymous function.

It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

Can't get Gulp to run: cannot find module 'gulp-util'

Same issue here and whatever I tried after searching around, did not work. Until I saw a remark somewhere about global or local installs. Looking in:

C:\Users\YourName\AppData\Roaming\npm\gulp

I indeed found an outdated version. So I reinstalled gulp with:

npm install gulp --global

That magically solved my problem.

node.js + mysql connection pooling

i always use connection.relase(); after pool.getconnetion like

pool.getConnection(function (err, connection) {
      connection.release();
        if (!err)
        {
            console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
            //CHECKING USERNAME EXISTENCE
            email = receivedValues.email
            connection.query('SELECT * FROM users WHERE email = ?', [email],
                function (err, rows) {
                    if (!err)
                    {
                        if (rows.length == 1)
                        {
                            if (bcrypt.compareSync(req.body.password, rows[0].password))
                            {
                                var alldata = rows;
                                var userid = rows[0].id;
                                var tokendata = (receivedValues, userid);
                                var token = jwt.sign(receivedValues, config.secret, {
                                    expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                });
                                console.log("*** Authorised User");
                                res.json({
                                    "code": 200,
                                    "status": "Success",
                                    "token": token,
                                    "userData": alldata,
                                    "message": "Authorised User!"
                                });
                                logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                return;
                            }
                            else
                            {
                                console.log("*** Redirecting: Unauthorised User");
                                res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                logger.error('*** Redirecting: Unauthorised User');
                                return;
                            }
                        }
                        else
                        {
                            console.error("*** Redirecting: No User found with provided name");
                            res.json({
                                "code": 200,
                                "status": "Error",
                                "message": "No User found with provided name"
                            });
                            logger.error('url=', URL.url, 'No User found with provided name');
                            return;
                        }
                    }
                    else
                    {
                        console.log("*** Redirecting: Error for selecting user");
                        res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                        logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                        return;
                    }
                });
            connection.on('error', function (err) {
                console.log('*** Redirecting: Error Creating User...');
                res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                return;
            });
        }
        else
        {
            Errors.Connection_Error(res);
        }
    });

Preventing iframe caching in browser

Make the URL of the iframe point to a page on your site which acts as a proxy to retrieve and return the actual contents of the iframe. Now you are no longer bound by the same-origin policy (EDIT: does not prevent the iframe caching issue).

Is there a method that calculates a factorial in Java?

Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

SQL: how to use UNION and order by a specific select?

You want to do this:

select * from 
(
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    UNION
    SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered

Update

I noticed that even though you have two different tables, you join the IDs, that means, if you have 1 in both tables, you are getting only one occurrence. If that's the desired behavior, you should stick to UNION. If not, change to UNION ALL.

So I also notice that if you change to the code I proposed, You would start getting both 1 and 2 (from both a and b). In that case, you might want to change the proposed code to:

select distinct id from 
(
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    UNION
    SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered

Append key/value pair to hash with << in Ruby

I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.

    my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
                      :type=> 'n:n', :msgheader => from}, :body=>[]}
    my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }        
    my_hash_full = my_hash_static[:body].push my_hash_dynamic

How do I use HTML as the view engine in Express?

Comment out the middleware for html i.e.

//app.set('view engine', 'html');

Instead use:

app.get("/",(req,res)=>{
    res.sendFile("index.html");
});

Bad Gateway 502 error with Apache mod_proxy and Tomcat

You can use proxy-initial-not-pooled

See http://httpd.apache.org/docs/2.2/mod/mod_proxy_http.html :

If this variable is set no pooled connection will be reused if the client connection is an initial connection. This avoids the "proxy: error reading status line from remote server" error message caused by the race condition that the backend server closed the pooled connection after the connection check by the proxy and before data sent by the proxy reached the backend. It has to be kept in mind that setting this variable downgrades performance, especially with HTTP/1.0 clients.

We had this problem, too. We fixed it by adding

SetEnv proxy-nokeepalive 1
SetEnv proxy-initial-not-pooled 1

and turning keepAlive on all servers off.

mod_proxy_http is fine in most scenarios but we are running it with heavy load and we still got some timeout problems we do not understand.

But see if the above directive fits your needs.

Can a CSS class inherit one or more other classes?

Unfortunately, CSS does not provide 'inheritance' in the way that programming languages like C++, C# or Java do. You can't declare a CSS class an then extend it with another CSS class.

However, you can apply more than a single class to an tag in your markup ... in which case there is a sophisticated set of rules that determine which actual styles will get applied by the browser.

<span class="styleA styleB"> ... </span>

CSS will look for all the styles that can be applied based on what your markup, and combine the CSS styles from those multiple rules together.

Typically, the styles are merged, but when conflicts arise, the later declared style will generally win (unless the !important attribute is specified on one of the styles, in which case that wins). Also, styles applied directly to an HTML element take precedence over CSS class styles.

How to show and update echo on same line

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

Read input stream twice

Convert inputstream into bytes and then pass it to savefile function where you assemble the same into inputstream. Also in original function use bytes to use for other tasks

Propagation Delay vs Transmission delay

Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.

Propagation delay : It's the amount of time needed for a packet to reach the destination.

If propagation delay is very high than transmission delay the chance of losing the packet is high.

The requested URL /about was not found on this server

It worked for me like this:

Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:

/index.php/%year%/%monthnum%/%day%/%postname%/

and click the Save button.

I got this solution from this link

Xcode 9 Swift Language Version (SWIFT_VERSION)

This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".

How to invoke a Linux shell command from Java

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

Is there a way to detect if a browser window is not currently active?

this works for me on chrome 67, firefox 67,

if(!document.hasFocus()) {
    // do stuff
}

Inputting a default image in case the src attribute of an html <img> is not valid?

In addition to Patrick's brilliant answer, for those of you who are searching for a cross-platform angular js solution, here you go:

<object type="image/png" data-ng-attr-data="{{ url || 'data:' }}">
    <!-- any html as a fallback -->
</object>

Here's a plunk where I was playing trying to find the right solution: http://plnkr.co/edit/nL6FQ6kMK33NJeW8DVDY?p=preview

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

In my case, there were two different 'AWS_SECRET_ACCESS_KEY' and 'AWS_ACCESS_KEY_ID' values set one through the Windows environment variable and one through the command line.

So, update these two and the default_region using a command line

> aws configure

Press enter and follow the steps to fill the correct AWS_ACESS_KEY_ID AWS_SECRET_ACCESS_KEY and AWS_DEFAULT_REGION

> aws sts get-caller-identity

should return the new set credentials

What is the difference between gravity and layout_gravity in Android?

Inside - Outside

  • gravity arranges the content inside the view.
  • layout_gravity arranges the view's position outside of itself.

Sometimes it helps to see a picture, too. The green and blue are TextViews and the other two background colors are LinearLayouts.

enter image description here

Notes

  • The layout_gravity does not work for views in a RelativeLayout. Use it for views in a LinearLayout or FrameLayout. See my supplemental answer for more details.
  • The view's width (or height) has to be greater than its content. Otherwise gravity won't have any effect. Thus, wrap_content and gravity are meaningless together.
  • The view's width (or height) has to be less than the parent. Otherwise layout_gravity won't have any effect. Thus, match_parent and layout_gravity are meaningless together.
  • The layout_gravity=center looks the same as layout_gravity=center_horizontal here because they are in a vertical linear layout. You can't center vertically in this case, so layout_gravity=center only centers horizontally.
  • This answer only dealt with setting gravity and layout_gravity on the views within a layout. To see what happens when you set the gravity of the of the parent layout itself, check out the supplemental answer that I referred to above. (Summary: gravity doesn't work well on a RelativeLayout but can be useful with a LinearLayout.)

So remember, layout_gravity arranges a view in its layout. Gravity arranges the content inside the view.

xml

Here is the xml for the above image for your reference:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#e3e2ad"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="24sp"
            android:text="gravity=" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#bcf5b1"
            android:gravity="left"
            android:text="left" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#aacaff"
            android:gravity="center_horizontal"
            android:text="center_horizontal" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#bcf5b1"
            android:gravity="right"
            android:text="right" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:background="#aacaff"
            android:gravity="center"
            android:text="center" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#d6c6cd"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="24sp"
            android:text="layout_gravity=" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="left"
            android:background="#bcf5b1"
            android:text="left" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:background="#aacaff"
            android:text="center_horizontal" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="right"
            android:background="#bcf5b1"
            android:text="right" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:background="#aacaff"
            android:text="center" />

    </LinearLayout>

</LinearLayout>

Related

Why is document.write considered a "bad practice"?

There's actually nothing wrong with document.write, per se. The problem is that it's really easy to misuse it. Grossly, even.

In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets

  1. It keeps the scripts small
  2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
  3. It's extremely compatible

As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.

How do I view executed queries within SQL Server Management Studio?

Use SQL Profiler and use a filter on it to get the most expensive queries.

How to convert Map keys to array?

Map.keys() returns a MapIterator object which can be converted to Array using Array.from:

let keys = Array.from( myMap.keys() );
// ["a", "b"]

EDIT: you can also convert iterable object to array using spread syntax

let keys =[ ...myMap.keys() ];
// ["a", "b"]

Segmentation fault on large array sizes

You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.

Converting between datetime and Pandas Timestamp objects

To answer the question of going from an existing python datetime to a pandas Timestamp do the following:

    import time, calendar, pandas as pd
    from datetime import datetime
    
    def to_posix_ts(d: datetime, utc:bool=True) -> float:
        tt=d.timetuple()
        return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
    
    def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
        return pd.to_datetime(to_posix_ts(d), unit='s')
    
    dt = pd_timestamp_from_datetime(datetime.now())
    print('({}) {}'.format(type(dt), dt))

Output:

(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55

I was hoping for a more elegant way to do this but the to_posix_ts is already in my standard tool chain so I'm moving on.

How to get the last char of a string in PHP?

I'd advise to go for Gordon's solution as it is more performant than substr():

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

outputs something like

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

Any way to make plot points in scatterplot more transparent in R?

If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:

E.g. half-transparency red:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency

Deserialize JSON with C#

If you're using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.

The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.

Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu EditPaste SpecialPaste JSON as classes).

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Response
{
    public List<Person> Data { get; set; }
}

Then you can deserialize using:

var people = JsonSerializer.Deserialize<Response>(json);

If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:

var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);

Is floating point math broken?

Can I just add; people always assume this to be a computer problem, but if you count with your hands (base 10), you can't get (1/3+1/3=2/3)=true unless you have infinity to add 0.333... to 0.333... so just as with the (1/10+2/10)!==3/10 problem in base 2, you truncate it to 0.333 + 0.333 = 0.666 and probably round it to 0.667 which would be also be technically inaccurate.

Count in ternary, and thirds are not a problem though - maybe some race with 15 fingers on each hand would ask why your decimal math was broken...

jQuery show/hide not working

Just add the document ready function, this way it waits until the DOM has been loaded, also by using the :visible pseudo you can write a simple show and hide function.

Sample

 $(document).ready(function(){

    $( '.expand' ).click(function() {
         if($( '.img_display_content' ).is(":visible")){
              $( '.img_display_content' ).hide();
         } else{
              $( '.img_display_content' ).show();
         }

    });
});

How do I execute multiple SQL Statements in Access' Query Editor?

You can easily write a bit code that will read in a file. You can either assume one sql statement per line, or assume the ;

So, assuming you have a text file such as:

insert into tblTest (t1) values ('2000');

update tbltest set t1 = '2222'
       where id = 5;


insert into tblTest (t1,t2,t3) 
       values ('2001','2002','2003');

Note the in the above text file we free to have sql statements on more then one line.

the code you can use to read + run the above script is:

Sub SqlScripts()

   Dim vSql       As Variant
   Dim vSqls      As Variant
   Dim strSql     As String
   Dim intF       As Integer

   intF = FreeFile()
   Open "c:\sql.txt" For Input As #intF
   strSql = input(LOF(intF), #intF)
   Close intF
   vSql = Split(strSql, ";")

   On Error Resume Next
   For Each vSqls In vSql
      CurrentDb.Execute vSqls
   Next

End Sub

You could expand on placing some error msg if the one statement don't work, such as

if err.number <> 0 then
   debug.print "sql err" & err.Descripiton & "-->" vSqls
end dif

Regardless, the above split() and string read does alow your sql to be on more then one line...

How do I make a list of data frames?

Taking as a given you have a "large" number of data.frames with similar names (here d# where # is some positive integer), the following is a slight improvement of @mark-miller's method. It is more terse and returns a named list of data.frames, where each name in the list is the name of the corresponding original data.frame.

The key is using mget together with ls. If the data frames d1 and d2 provided in the question were the only objects with names d# in the environment, then

my.list <- mget(ls(pattern="^d[0-9]+"))

which would return

my.list
$d1
  y1 y2
1  1  4
2  2  5
3  3  6

$d2
  y1 y2
1  3  6
2  2  5
3  1  4

This method takes advantage of the pattern argument in ls, which allows us to use regular expressions to do a finer parsing of the names of objects in the environment. An alternative to the regex "^d[0-9]+$" is "^d\\d+$".

As @gregor points out, it is a better overall to set up your data construction process so that the data.frames are put into named lists at the start.

data

d1 <- data.frame(y1 = c(1,2,3),y2 = c(4,5,6))
d2 <- data.frame(y1 = c(3,2,1),y2 = c(6,5,4))

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

As I mentioned in your other question:

The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.

The proper solution is to completely remove your invented attributes and replace them with something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"), or store them in JavaScript:

var validationData = {
  "Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}

If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.

Returning a value from thread?

A simple solution is to pass a parameter by ref to the function that is running in the thread and change its value in the thread.

       // create a list of threads
        List<Thread> threads = new List<Thread>();


        //declare the ref params
        bool is1 = false;
        bool is2 = false;

        threads.Add(new Thread(() => myFunction(someVar, ref is1)));
        threads.Add(new Thread(() => myFunction(someVar, ref is2)));

        threads.ForEach(x => x.Start());

        // wait for threads to finish
        threads.ForEach(x => x.Join());

        //check the ref params
        if (!is1)
        {
          //do something
        }

        if (!is2)
        {
           //do somethign else
        }

If you can't change the function that is running in the tread, you can wrap it another function:

 bool theirFunction(var someVar){
   return false;
}


 void myFunction(var someVar ref bool result){
  result = theirFunction(myVar);
 }

Calculating a directory's size using Python?

A solution that works on Python 3.6 using pathlib.

from pathlib import Path

sum([f.stat().st_size for f in Path("path").glob("**/*")])

How to check Grants Permissions at Run-Time?

Try this for Check Run-Time Permission:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkRunTimePermission();
}

Check run time permission:

private void checkRunTimePermission() {
    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissionArrays, 11111);
    } else {
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    }
}

Handle Permission result:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) {
                    //execute when 'never Ask Again' tick and permission dialog not show
                } else {
                    if (openDialogOnce) {
                        alertView();
                    }
                }
            }
        }

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    }
}

Set custom alert:

private void alertView() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                }
            })
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                }
            }).show();
}

Understanding Popen.communicate

.communicate() writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.

The exception EOFError is raised in the child process by raw_input() (it expected data but got EOF (no data)).

p.stdout.read() hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()) that causes a deadlock.

To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:

from subprocess import PIPE, Popen

p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
    print >>p.stdin, i # write input
    p.stdin.flush() # not necessary in this case
    print p.stdout.readline(), # read output

print p.communicate("n\n")[0], # signal the child to exit,
                               # read the rest of the output, 
                               # wait for the child to exit

Note: it is a very fragile code if read/write are not in sync; it deadlocks.

Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).

bufsize=1 makes the pipes line-buffered on the parent side.

Delegation: EventEmitter or Observable in Angular

Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.


Original answer: (don't do this)

Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:

import {EventEmitter} from 'angular2/core';

export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emit(number) {
    this.navchange.emit(number);
  }
  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.navchange.subscribe(data => call.callback(component, data));
  }
}

@Component({
  selector: 'obs-comp',
  template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private navService:NavService) {
   this.subscription = this.navService.subscribe(this, this.selectedNavItem);
  }
  selectedNavItem(item: number) {
    console.log('item index changed!', item);
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
  `,
})
export class Navigation {
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emit(item);
  }
}

If you try the Plunker, there are a few things I don't like about this approach:

  • ObservingComponent needs to unsubscribe when it is destroyed
  • we have to pass the component to subscribe() so that the proper this is set when the callback is called

Update: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange EventEmitter property:

constructor(private navService:NavService) {
   this.subscription = this.navService.navchange.subscribe(data =>
     this.selectedNavItem(data));
}

If we subscribe directly, then we wouldn't need the subscribe() method on the NavService.

To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter() method and use that:

getNavChangeEmitter() { return this.navchange; }  // in NavService

constructor(private navService:NavService) {  // in ObservingComponent
   this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
     this.selectedNavItem(data));
}

SUM OVER PARTITION BY

I think the query you want is this:

SELECT BrandId, SUM(ICount),
       SUM(sum(ICount)) over () as TotalCount,
       100.0 * SUM(ICount) / SUM(sum(Icount)) over () as Percentage
FROM Table 
WHERE DateId  = 20130618
group by BrandId;

This does the group by for brand. And it calculates the "Percentage". This version should produce a number between 0 and 100.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

in a case of Elliptic Curve and answer the question import an existing x509 certificate and private key in Java keystore, you may want to have a look also to this thread How to read EC Private key in java which is in .pem file format

What does "pending" mean for request in Chrome Developer Window?

I had a similar issue with application/json ajax calls. In ff/IE they were fine. In chrome in the Developer Network window Status was always (pending) because a different status code was being returned.

In my case I changed my Json response to send a HttpStatusCode of 200 then Chrome was fine and the Status Text changed to 200 OK.

For example using ASP.NET Web Api

 return new HttpResponseMessage(HttpStatusCode.OK ) {
            Content = request.Content
        };

What is the easiest way to parse an INI file in Java?

The library I've used is ini4j. It is lightweight and parses the ini files with ease. Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API

This is an example on how the library is used:

Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));

How to enable CORS in apache tomcat

CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.

What's the environment variable for the path to the desktop?

Quite old topic. But I want to give my 2 cents...

I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%

Also there is no dependency from powershell/vbscript/etc....

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ  set desktopdir=%%B
echo %desktopdir%

Hope it helps.

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Partial Dependency (Databases)

Partial dependence is solved for arriving to a relation in 2NF but 2NF is a "stepping stone" (C. Date) for solving any transitive dependency and arriving to a relation in 3NF (which is the operational target). However, the most interested thing on partial dependence is that it is a particular case of the own transitive dependency. This was demostrated by P. A. Berstein in 1976: IF {(x•y)?z but y?z} THEN {(x•y)?y & y?z}. The 3NF synthesizer algorithm of Berstein does not need doing distintions among these two type of relational defects.

How to Import 1GB .sql file to WAMP/phpmyadmin

The values indicated by Ram Sharma might need to be changed in Wamp alias configuration files instead.

In <wamp_dir>/alias/phpmyadmin.conf, in the <Directory> section:

  php_admin_value upload_max_filesize 1280M
  php_admin_value post_max_size 1280M
  php_admin_value max_execution_time 1800

"Are you missing an assembly reference?" compile error - Visual Studio

In my case, I had to change the Copy Local setting to true (right-click assembly in solution explorer, select properties, locate and change value of Copy Local property). Once this setting was changed, publication of my WCF service copied the file to the server and the error went away.

Mark error in form using Bootstrap

Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

how to convert a string to an array in php

explode() might be the function you are looking for

$array = explode(' ',$str);

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

Functions that return a function

Assigning a variable to a function (without the parenthesis) copies the reference to the function. Putting the parenthesis at the end of a function name, calls the function, returning the functions return value.

Demo

function a() {
    alert('A');
}
//alerts 'A', returns undefined

function b() {
    alert('B');
    return a;
}
//alerts 'B', returns function a

function c() {
    alert('C');
    return a();
}
//alerts 'C', alerts 'A', returns undefined

alert("Function 'a' returns " + a());
alert("Function 'b' returns " + b());
alert("Function 'c' returns " + c());

In your example, you are also defining functions within a function. Such as:

function d() {
    function e() {
        alert('E');
    }
    return e;
}
d()();
//alerts 'E'

The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around just like other values. Consider the following:

function counter() {
    var count = 0;
    return function() {
        alert(count++);
    }
}
var count = counter();
count();
count();
count();

The function count can keep the variables that were defined outside of it. This is called a closure. It's also used a lot in JavaScript.

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

Update multiple rows in same query using PostgreSQL

You can also use update ... from syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:

update test as t set
    column_a = c.column_a
from (values
    ('123', 1),
    ('345', 2)  
) as c(column_b, column_a) 
where c.column_b = t.column_b;

You can add as many columns as you like:

update test as t set
    column_a = c.column_a,
    column_c = c.column_c
from (values
    ('123', 1, '---'),
    ('345', 2, '+++')  
) as c(column_b, column_a, column_c) 
where c.column_b = t.column_b;

sql fiddle demo

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

React.js: Set innerHTML vs dangerouslySetInnerHTML

According to Dangerously Set innerHTML,

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name dangerouslySetInnerHTML is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.

After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key __html and your sanitized data as the value. Here is an example using the JSX syntax:

function createMarkup() {
    return {
       __html: 'First &middot; Second'    };
 }; 

<div dangerouslySetInnerHTML={createMarkup()} /> 

Read more about it using below link:

documentation: React DOM Elements - dangerouslySetInnerHTML.

JavaScript - Hide a Div at startup (load)

Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

Redirect website after certain amount of time

Use this simple javascript code to redirect page to another page using specific interval of time...

Please add this code into your web site page, which is you want to redirect :

<script type="text/javascript">
(function(){
   setTimeout(function(){
     window.location="http://brightwaay.com/";
   },3000); /* 1000 = 1 second*/
})();
</script>

Python 'list indices must be integers, not tuple"

The problem is that [...] in python has two distinct meanings

  1. expr [ index ] means accessing an element of a list
  2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

In your code you forgot the comma between the expressions for the items in the outer list:

[ [a, b, c] [d, e, f] [g, h, i] ]

therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

The correct syntax for what you're looking for is

[ [a, b, c], [d, e, f], [g, h, i] ]

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

Can I update a JSF component from a JSF backing bean method?

Using standard JSF API, add the client ID to PartialViewContext#getRenderIds().

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");

Using PrimeFaces specific API, use PrimeFaces.Ajax#update().

PrimeFaces.current().ajax().update("foo:bar");

Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update().

RequestContext.getCurrentInstance().update("foo:bar");

If you happen to use JSF utility library OmniFaces, use Ajax#update().

Ajax.update("foo:bar");

Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer separator character like as you would do from the view side on.

how to convert from int to char*?

  • In C++17, use std::to_chars as:

    std::array<char, 10> str;
    std::to_chars(str.data(), str.data() + str.size(), 42);
    
  • In C++11, use std::to_string as:

    std::string s = std::to_string(number);
    char const *pchar = s.c_str();  //use char const* as target type
    
  • And in C++03, what you're doing is just fine, except use const as:

    char const* pchar = temp_str.c_str(); //dont use cast
    

Create empty file using python

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.

What is the most "pythonic" way to iterate over a list in chunks?

import itertools
def chunks(iterable,size):
    it = iter(iterable)
    chunk = tuple(itertools.islice(it,size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# though this will throw ValueError if the length of ints
# isn't a multiple of four:
for x1,x2,x3,x4 in chunks(ints,4):
    foo += x1 + x2 + x3 + x4

for chunk in chunks(ints,4):
    foo += sum(chunk)

Another way:

import itertools
def chunks2(iterable,size,filler=None):
    it = itertools.chain(iterable,itertools.repeat(filler,size-1))
    chunk = tuple(itertools.islice(it,size))
    while len(chunk) == size:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# x2, x3 and x4 could get the value 0 if the length is not
# a multiple of 4.
for x1,x2,x3,x4 in chunks2(ints,4,0):
    foo += x1 + x2 + x3 + x4

How to check if a float value is a whole number

All the answers are good but a sure fire method would be

def whole (n):
     return (n*10)%10==0

The function returns True if it's a whole number else False....I know I'm a bit late but here's one of the interesting methods which I made...

Edit: as stated by the comment below, a cheaper equivalent test would be:

def whole(n):
    return n%1==0

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

case statement in SQL, how to return multiple variables?

The basic way, unfortunately, is to repeat yourself.

SELECT
  CASE WHEN <condition 1> THEN <a1> WHEN <condition 2> THEN <a2> ELSE <a3> END,
  CASE WHEN <condition 1> THEN <b1> WHEN <condition 2> THEN <b2> ELSE <b3> END
FROM 
  <table> 

Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.


In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...

SELECT
  *
FROM
  <table>
CROSS APPLY
  (
   SELECT a1, b1 WHERE <condition 1>
   UNION ALL
   SELECT a2, b2 WHERE <condition 2>
   UNION ALL
   SELECT a3, b3 WHERE <condition 3>
  )
  AS case_proxy

The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.


EDIT

If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).


EDIT

I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...

WITH
  checked_data AS
(
  SELECT
    CASE WHEN <condition1> THEN 1
         WHEN <condition2> THEN 2
         WHEN <condition3> THEN 3
         ...
         ELSE                   100
    END AS condition_id,
    *
  FROM
    <table>
)
,
  results (condition_id, value1, value2) AS
(
   SELECT 1, a1, b1
   UNION ALL
   SELECT 2, a2, b2
   UNION ALL
   SELECT 3, a3, b3
   UNION ALL
   ...
   SELECT 100, a100, b100
)
SELECT
  *
FROM
  checked_data
INNER JOIN
  results
    ON results.condition_id = checked_data.condition_id

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

I was also having a similar problem. Finally found one solution at https://techmeals.com/fe/questions/htmlcss/4/How-to-customize-the-select-drop-down-in-css-which-works-for-all-the-browsers

Note:

1) For Firefox support there is special CSS handling for SELECT element's parent, please take a closer look.

2) Download the down.png from Down.png

CSS code

        /* For Firefox browser we need to style for SELECT element parent. */

        @-moz-document url-prefix() {

            /* Please note this is the parent of "SELECT" element */

            .select-example {   
                background: url('https://techmeals.com/external/images/down.png');
                background-color: #FFFFFF;
                border: 1px solid #9e9e9e;
                background-size: auto 6px;
                background-repeat: no-repeat;
                background-position: 96% 13px;
            }
        }

        /* IE specific styles */
        @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) 
        {
                select.my-select-box {
                padding: 0 0 0 5px;
            }
        }

        /* IE specific styles */
        @supports (-ms-accelerator:true) {
                select.my-select-box {
                padding: 0 0 0 5px;
            }
        }

        select.my-select-box  {
            outline: none;
            background: #fff;
            -moz-appearance: window;
            -webkit-appearance: none;
            border-radius: 0px;
            text-overflow: "";
            background-image: url('https://techmeals.com/external/images/down.png');
            background-size: auto 6px;
            background-repeat: no-repeat;
            background-position: 96% 13px;
            cursor: pointer;
            height: 30px;
            width: 100%;
            border: 1px solid #9e9e9e;
            padding: 0 15px 0 5px;
            padding-right: 15px\9;      /* This will be apllied only to IE 7, IE 8 and IE 9 as */
            *padding-right: 15px;        /* This will be apllied only to IE 7 and below. */
            _padding-right: 15px;       /* This will be apllied only to IE 6 and below. */
        }

HTML code

    <div class="select-example">
        <select class="my-select-box">
            <option value="1">First Option</option>
            <option value="2">Second Option</option>
            <option value="3">Third Option</option>
            <option value="4">Fourth Option</option>
        </select>
    </div>

How to get Django and ReactJS to work together?

Hoping to provide a more nuanced answer than any of the ones here, especially as some things have changed since this was originally asked ~4 years ago, and because many of the top-voted answers claiming that you have to set this up as two separate applications are not accurate.

You have two primary architecture options:

  1. A completely decoupled client/server approach using something like create-react-app and Django REST Framework
  2. A hybrid architecture where you set up a React build pipeline (likely using webpack) and then include the compiled files as static files in your Django templates.

These might look something like this:

Option 1 (Client/Server Architecture):

Client / Server Architecture

Option 2 (Hybrid Architecture):

Hybrid Architecture

The decision between these two will depend on your / your team's experience, as well as the complexity of your UI. The first option is good if you have a lot of JS experience, want to keep your front-end / back-end developers separate, or want to write your entire application as a React single-page-app. The second option is generally better if you are more familiar with Django and want to move quickly while also using React for some parts of your app. I find it's a particularly good fit for full-stack solo-developers.

There is a lot more information in the series "Modern JavaScript for Django Developers", including choosing your architecture, integrating your JS build into a Django project and building a single-page React app.

Full disclosure, I'm the author of that series.

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

Are static methods inherited in Java?

All methods that are accessible are inherited by subclasses.

From the Sun Java Tutorials:

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.

From the page on the difference between overriding and hiding.

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

Convert integer to hexadecimal and back again

Try the following to convert it to hex

public static string ToHex(this int value) {
  return String.Format("0x{0:X}", value);
}

And back again

public static int FromHex(string value) {
  // strip the leading 0x
  if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
    value = value.Substring(2);
  }
  return Int32.Parse(value, NumberStyles.HexNumber);
}

Why do python lists have pop() but not push()

Because it appends an element to a list? Push is usually used when referring to stacks.

Installing Google Protocol Buffers on mac

For v3 users.

http://google.github.io/proto-lens/installing-protoc.html

PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP

What tool can decompile a DLL into C++ source code?

There are no decompilers which I know about. W32dasm is good Win32 disassembler.

CryptographicException 'Keyset does not exist', but only through WCF

I hit this in my service fabric project after the cert used to authenticate against our key vault expired and was rotated, which changed the thumbprint. I got this error because I had missed updating the thumbprint in the applicationManifest.xml file in this block which precisely does what other answers have suggested - to given NETWORK SERVICE (which all my exes run as, standard config for azure servicefabric cluster) permissions to access the LOCALMACHINE\MY cert store location.

Note the "X509FindValue" attribute value.

_x000D_
_x000D_
<!-- this block added to allow low priv processes (such as service fabric processes) that run as NETWORK SERVICE to read certificates from the store -->_x000D_
  <Principals>_x000D_
    <Users>_x000D_
      <User Name="NetworkService" AccountType="NetworkService" />_x000D_
    </Users>_x000D_
  </Principals>_x000D_
  <Policies>_x000D_
    <SecurityAccessPolicies>_x000D_
      <SecurityAccessPolicy ResourceRef="AzureKeyvaultClientCertificate" PrincipalRef="NetworkService" GrantRights="Full" ResourceType="Certificate" />_x000D_
    </SecurityAccessPolicies>_x000D_
  </Policies>_x000D_
  <Certificates>_x000D_
    <SecretsCertificate X509FindValue="[[THIS KEY ALSO NEEDS TO BE UPDATED]]" Name="AzureKeyvaultClientCertificate" />_x000D_
  </Certificates>_x000D_
  <!-- end block -->
_x000D_
_x000D_
_x000D_

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

How to create a data file for gnuplot?

I had the same issue when tried to open the file using Plot->Data filename... option provided in the version for Windows 7 (by the way, it worked fine on another computer with the same version of the OP system).

Then I tried to change directory and save the .plt file, but it didn't work either. Finally, I tried to tape manually as it was showed for Linux earlier in this queue of posts:

gnuplot > plot "./datafile.dat"

and it worked!

How to drop all user tables?

The simplest way is to drop the user that owns the objects with the cascade command.

DROP USER username CASCADE

Detect If Browser Tab Has Focus

Surprising to see nobody mentioned document.hasFocus

if (document.hasFocus()) console.log('Tab is active')

MDN has more information.

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

Ruby max integer

FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))

Limit String Length

In Laravel, there is a string util function for this, and it is implemented this way:

public static function limit($value, $limit = 100, $end = '...')
{
    if (mb_strwidth($value, 'UTF-8') <= $limit) {
        return $value;
    }

    return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
}

How can I detect browser type using jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    alert('sdfsd');_x000D_
    checkOperatingSystem();_x000D_
   });_x000D_
   function checkOperatingSystem(){_x000D_
       var  userAgent = navigator.userAgent || navigator.vendor || window.opera;_x000D_
_x000D_
       _x000D_
       if (/android/i.test(userAgent)) {_x000D_
           alert('android');_x000D_
       }_x000D_
_x000D_
       _x000D_
       if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {_x000D_
           alert('ios');_x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Win")!=-1)_x000D_
       {_x000D_
           _x000D_
       }_x000D_
_x000D_
      _x000D_
       if (navigator.appVersion.indexOf("Mac")!=-1)_x000D_
       {_x000D_
           _x000D_
       }  _x000D_
   }
_x000D_
_x000D_
_x000D_

.do extension in web pages?

Using apache's rewrite_module can change your script extensions. Give this thread a good read.

"Sources directory is already netbeans project" error when opening a project from existing sources

In my case my project root directory consists ".project". This contain the XML reference of the project name.

By removing this, i am able to create a project.

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }
    }
</style>

....

<div id="wrapper">
    <!-- your html for your website -->
</div>
<div id="warning-message">
    this website is only viewable in landscape mode
</div>

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.

Update

I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

How to convert an XML file to nice pandas dataframe?

Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records. xmltodict handling xml load

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

std::thread thread([&thread]() {
    sleep(3);
    thread.detach();
});

while(thread.joinable())
    sleep(1);

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

I was in same problem.

Below command solved my problem

pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-none-any.whl

to find the list of all the urls based on the python version and CPU or GPU only refer to: https://www.tensorflow.org/install/pip

creating a table in ionic

Simply, for me, I used ion-row and ion-col to achieve it. You can make it more neater by doing some changes by CSS.

<ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
  </ion-row>
  <ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>
  <ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>
  <ion-row >
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

As c-smile mentioned: Just need to remove the apostrophes in the url():

<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>

Demo here

Comparing the contents of two files in Sublime Text

There's a BeyondCompare plugin as well. It opens the 2 files in a BeyondCompare window. Pretty convenient to open files from the sublime window.

You will need BC3 installation present in the system. After installing the plugin, you will have to provide the path to the installation.

Example:

{
    //Define a custom path to beyond compare
    "beyond_compare_path": "G:/Softwares/Beyond Compare 3/BCompare.exe"
}

How to change target build on Android project?

  1. You can change your the Build Target for your project at any time:

    Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.

  2. Edit the following elements in the AndroidManifest.xml file (it is in your project root directory)

    In this case, that will be:

    <uses-sdk android:minSdkVersion="3" />
    <uses-sdk android:targetSdkVersion="8" />
    

    Save it

  3. Rebuild your project.

    Click the Project on the menu bar, select Clean...

  4. Now, run the project again.

    Right Click Project name, move on Run as, and select Android Application

By the way, reviewing Managing Projects from Eclipse with ADT will be helpful. Especially the part called Creating an Android Project.

How to align td elements in center

The best way to center content in a table (for example <video> or <img>) is to do the following:

_x000D_
_x000D_
<table width="100%" border="0" cellspacing="0" cellpadding="100%">
<tr>
<td>Video Tag 1 Here</td>
<td>Video Tag 2 Here</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

PHPMailer character encoding issues

If you are 100% sure $message contain ISO-8859-1 you can use utf8_encode as David says. Otherwise use mb_detect_encoding and mb_convert_encoding on $message.

Also take note that

$mail -> charSet = "UTF-8"; 

Should be replaced by:

$mail->CharSet = 'UTF-8';

And placed after the instantiation of the class (after the new). The properties are case sensitive! See the PHPMailer doc fot the list & exact spelling.

Also the default encoding of PHPMailer is 8bit which can be problematic with UTF-8 data. To fix this you can do:

$mail->Encoding = 'base64';

Take note that 'quoted-printable' would probably work too in these cases (and maybe even 'binary'). For more details you can read RFC1341 - Content-Transfer-Encoding Header Field.

Visibility of global variables in imported modules

This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don't work for you if you made the same thing I did below.

Namely, I have a module which contains global/shared variables (as suggested above):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

Then I had the main module which imports the shared stuff with:

import sharedstuff as shared

and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:

from globals import *

it worked (the arrays were populated).

Just sayin'

Split string into strings by length?

The string splitting is required in many cases like where you have to sort the characters of the string given, replacing a character with an another character etc. But all these operations can be performed with the following mentioned string splitting methods.

The string splitting can be done in two ways:

  1. Slicing the given string based on the length of split.

  2. Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list. Then do the required operation and join them with 'specified character between the characters of the original string'.join(list) to get a new processed string.

Uses of content-disposition in an HTTP response header

This header is defined in RFC 2183, so that would be the best place to start reading.

Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

Detect if a page has a vertical scrollbar?

Other solutions didn't work in one of my projects and I've ending up checking overflow css property

function haveScrollbar() {
    var style = window.getComputedStyle(document.body);
    return style["overflow-y"] != "hidden";
}

but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

in C#:

new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)

How to debug in Android Studio using adb over WiFi

I'm using AS 3.2.1, and was about to try some of the plugins, but was hesitant realizing the plugins are able to monitor any data..

It's actually really simple doing it via the Terminal tab in AS:

  1. Turn on debugging over WiFi in your phone
    • Go to developer options and turn on "ADB over network"
    • You'll see the exact address and port to use when connecting
  2. Go to the Terminal tab in Android Studio
  3. Type adb tcpip 5555
  4. Type your ip address as seen in developer options i.e. adb connect 192.168.1.101
  5. Now you'll see your device in AS "Select deployment target" dialog

Sending an Intent to browser to open specific URL

Is there also a way to pass coords directly to google maps to display?

You can use the geo URI prefix:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + latitude + "," + longitude));
startActivity(intent);

PHP multidimensional array search by value

you can use this function ; https://github.com/serhatozles/ArrayAdvancedSearch

<?php 
include('ArraySearch.php');

$query = "a='Example World' and b>='2'";

$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);

$Result = ArraySearch($Array,$query,1);

echo '<pre>';
print_r($Result);
echo '</pre>'; 

// Output:
// Array
// (
//    [0] => Array
//        (
//            [a] => Example World
//            [b] => 2
//        )
//
// )

Changing Jenkins build number

For multibranch pipeline projects, do this in the script console:

def project = Jenkins.instance.getItemByFullName("YourMultibranchPipelineProjectName")    
project.getAllJobs().each{ item ->   
    
    if(item.name == 'jobName'){ // master, develop, feature/......
      
      item.updateNextBuildNumber(#Number);
      item.saveNextBuildNumber();
      
      println('new build: ' + item.getNextBuildNumber())
    }
}

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Usually, best is to see a character in his context.

Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others.

This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases.

By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard.

_x000D_
_x000D_
var i = 0
    do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++
    while (i<136690)
window.stop() 


//  From https://codepen.io/Nico_KraZhtest/pen/mWzXqy
_x000D_
_x000D_
_x000D_

The same snippet as a bookmarklet:

javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}();

To generate that list from php:

for ($x = 0; $x < 136690; $x++) {
  echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8');
}

To generate that list into the console, using php:

php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}'

Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/

Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters.

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????


Hey, did you notice the plain html <details> element has a drop down arrow? This is sometimes all what we need.

_x000D_
_x000D_
<details>
  <summary>Morning</summary>
  <p>Hello world!</p>
</details>
<details>
  <summary>Evening</summary>
  <p>How sweat?</p>
</details>
_x000D_
_x000D_
_x000D_

How to send a header using a HTTP request through a curl call?

You can also send multiple headers, data (JSON for example), and specify Call method (POST,GET) into a single CUrl call like this:

curl -X POST(Get or whatever) \
  http://your_url.com/api/endpoint \
  -H 'Content-Type: application/json' \
  -H 'header-element1: header-data1' \
  -H 'header-element2: header-data2' \

......more headers................

  -d '{
  "JsonExArray": [
    {
      "json_prop": "1",
    },
    {
      "json_prop": "2",
    }
  ]
}'

How to send email attachments?

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import mimetypes
import email.mime.application

smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)


msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = email_user
msg['To'] = email_user

txt = MIMEText('I just bought a new camera.')
msg.attach(txt)

filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
fo=open(filename,'rb')
attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
fo.close()
attach.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(attach)
s.send_message(msg)
s.quit()

For explanation, you can use this link it explains properly https://medium.com/@sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623

T-SQL substring - separating first and last name

validate last name is blank

SELECT  
person.fullName,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    then  person.fullName 
    ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,  
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    THEN ''  
    ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name

FROM person

Export a graph to .eps file with R

If you are using ggplot2 to generate a figure, then a ggsave(file="name.eps") will also work.

A terminal command for a rooted Android to remount /System as read/write

I had the same problem. So here is the real answer: Mount the system under /proc. Here is my command:

mount -o rw,remount /proc /system

It works, and in fact is the only way I can overcome the Read-only System problem.

ActivityCompat.requestPermissions not showing dialog box

Don't forget to write the permissions without extra spaces in the manifest. In my case i had:

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

But look, at the end, there's an extra space. Just write it the right way

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

And it's working now

powershell - list local users and their groups

try this one :),

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Recording video feed from an IP camera over a network

I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.

Andrew

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Insert text into textarea with jQuery

It works good for me in Chrome 20.0.11

var startPos = this[0].selectionStart;
var endPos = this[0].selectionEnd;
var scrollTop = this.scrollTop;
this[0].value = this[0].value.substring(0, startPos) + myVal + this[0].value.substring(endPos, this[0].value.length);
this.focus();
this.selectionStart = startPos + myVal.length;
this.selectionEnd = startPos + myVal.length;
this.scrollTop = scrollTop;

POI setting Cell Background to a Custom Color

See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

Custom colors

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();

//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");

XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

How to find day of week in php in a specific timezone

$dw = date( "w", $timestamp);

Where $dw will be 0 (for Sunday) through 6 (for Saturday) as you can see here: http://www.php.net/manual/en/function.date.php

How can I delete multiple lines in vi?

d5d "cuts" five lines

I usually just throw the number in the middle like:

d7l = delete 7 letters

Fastest way to update 120 Million records

set rowcount 1000000
Update table set int_field = -1 where int_field<>-1

see how fast that takes, adjust and repeat as necessary

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Move

Random pp = new Random();
int a1 = pp.nextInt(10);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(a1);

To inside onCreate(), and change tv.setText(a1); to tv.setText(String.valueOf(a1)); :

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Random pp = new Random();
  int a1 = pp.nextInt(10);

  TextView tv = (TextView)findViewById(R.id.tv);
  tv.setText(String.valueOf(a1));

}   

First issue: findViewById() was called before onCreate(), which would throw an NPE.

Second issue: Passing an int directly to a TextView calls the overloaded method that looks for a String resource (from R.string). Therefore, we want to use String.valueOf() to force the String overloaded method.

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

get url content PHP

original answer moved to this topic .

How to mark a build unstable in Jenkins when running shell scripts

I find the most flexible way to do this is by reading a file in the groovy post build plugin. enter image description here

import hudson.FilePath
import java.io.InputStream

def build = Thread.currentThread().executable

String unstable = null
if(build.workspace.isRemote()) {
    channel = build.workspace.channel;
    fp = new FilePath(channel, build.workspace.toString() + "/build.properties")
    InputStream is = fp.read()
    unstable = is.text.trim()
} else {
    fp = new FilePath(new File(build.workspace.toString() + "/build.properties"))
    InputStream is = fp.read()
    unstable = is.text.trim()
}

manager.listener.logger.println("Build status file: " + unstable)
if (unstable.equalsIgnoreCase('true')) {
    manager.listener.logger.println('setting build to unstable')
    manager.buildUnstable()
}

If the file contents are 'true' the build will be set to unstable. This will work on the local master and on any slaves you run the job on, and for any kind of scripts that can write to disk.

How to install MySQLdb package? (ImportError: No module named setuptools)

#!/usr/bin/env python

import os
import sys
from **distutils.core** import setup, Extension

if sys.version_info < (2, 3):
    raise Error("Python-2.3 or newer is required")

if os.name == "posix":
    from setup_posix import get_config
else: # assume windows
    from setup_windows import get_config

metadata, options = get_config()
metadata['ext_modules'] = [Extension(sources=['_mysql.c'], **options)]
metadata['long_description'] = metadata['long_description'].replace(r'\n', '')
setup(**metadata)

Drawing rotated text on a HTML5 canvas

Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

Hope this helps!

_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_

How to put an image in div with CSS?

With Javascript/Jquery:

  • load image with hidden img
  • when image has been loaded, get width and height
  • dynamically create a div and set width, height and background
  • remove the original img

      $(document).ready(function() {
        var image = $("<img>");
        var div = $("<div>")
        image.load(function() {
          div.css({
            "width": this.width,
            "height": this.height,
            "background-image": "url(" + this.src + ")"
          });
          $("#container").append(div);
        });
        image.attr("src", "test0.png");
      });
    

Skip a submodule during a Maven build

The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.

Suppose your project is structured as:

project-root
  |
  + --- ci
  |
  + --- client
  |
  + --- server

The project-root/pom.xml defines modules

<modules>
  <module>ci</module>
  <module>client</module>
  <module>server</module>
</modules>

The ci/pom.xml defines profiles such as:

... 
<profiles>
  <profile>
    <id>default</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>true</skip>
       </configuration>
     </plugin>
  </profile>
  <profile>
    <id>CI</id>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>false</skip>
       </configuration>
     </plugin>
  </profile>
</profiles>

This will result in Maven skipping tests in this module except when the profile named CI is active. Your CI server must be instructed to execute mvn clean package -P CI. The Maven web site has an in-depth explanation of the profiling mechanism.

How to do a https request with bad certificate?

Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.

In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.

Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.

RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

Update query using Subquery in Sql Server

Here is a nice explanation of update operation with some examples. Although it is Postgres site, but the SQL queries are valid for the other DBs, too. The following examples are intuitive to understand.

-- Update contact names in an accounts table to match the currently assigned salesmen:

UPDATE accounts SET (contact_first_name, contact_last_name) =
    (SELECT first_name, last_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);

-- A similar result could be accomplished with a join:

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM salesmen WHERE salesmen.id = accounts.sales_id;

However, the second query may give unexpected results if salesmen.id is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple id matches. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all.

Hence for the given example, the most reliable query is like the following.

UPDATE tempDataView SET (marks) =
    (SELECT marks FROM tempData
     WHERE tempDataView.Name = tempData.Name);

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

Getting String Value from Json Object Android

Include org.json.jsonobject in your project.

You can then do this:

JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");

Assuming, responseString holds the response you receive.

If you need to know how to convert the received response to a String, here's how to do it:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();

How to use php serialize() and unserialize()

preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

Run the following to get the right NVIDIA driver :

sudo ubuntu-drivers devices

Then pick the right and run:

sudo apt install <version>

How can I generate an HTML report for Junit results?

There are multiple options available for generating HTML reports for Selenium WebDriver scripts.

1. Use the JUNIT TestWatcher class for creating your own Selenium HTML reports

The TestWatcher JUNIT class allows overriding the failed() and succeeded() JUNIT methods that are called automatically when JUNIT tests fail or pass.

The TestWatcher JUNIT class allows overriding the following methods:

  • protected void failed(Throwable e, Description description)

failed() method is invoked when a test fails

  • protected void finished(Description description)

finished() method is invoked when a test method finishes (whether passing or failing)

  • protected void skipped(AssumptionViolatedException e, Description description)

skipped() method is invoked when a test is skipped due to a failed assumption.

  • protected void starting(Description description)

starting() method is invoked when a test is about to start

  • protected void succeeded(Description description)

succeeded() method is invoked when a test succeeds

See below sample code for this case:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TestClass2 extends WatchManClassConsole {

    @Test public void testScript1() {
        assertTrue(1 < 2); >
    }

    @Test public void testScript2() {
        assertTrue(1 > 2);
    }

    @Test public void testScript3() {
        assertTrue(1 < 2);
    }

    @Test public void testScript4() {
        assertTrue(1 > 2);
    }
}

import org.junit.Rule; 
import org.junit.rules.TestRule; 
import org.junit.rules.TestWatcher; 
import org.junit.runner.Description; 
import org.junit.runners.model.Statement; 

public class WatchManClassConsole {

    @Rule public TestRule watchman = new TestWatcher() { 

        @Override public Statement apply(Statement base, Description description) { 
            return super.apply(base, description); 
        } 

        @Override protected void succeeded(Description description) { 
            System.out.println(description.getDisplayName() + " " + "success!"); 
        } 

        @Override protected void failed(Throwable e, Description description) { 
            System.out.println(description.getDisplayName() + " " + e.getClass().getSimpleName()); 
        }
    }; 
}

2. Use the Allure Reporting framework

Allure framework can help with generating HTML reports for your Selenium WebDriver projects.

The reporting framework is very flexible and it works with many programming languages and unit testing frameworks.

You can read everything about it at http://allure.qatools.ru/.

You will need the following dependencies and plugins to be added to your pom.xml file

  1. maven surefire
  2. aspectjweaver
  3. allure adapter

See more details including code samples on this article: http://test-able.blogspot.com/2015/10/create-selenium-html-reports-with-allure-framework.html

How to iterate through two lists in parallel?

Here's how to do it with list comprehension:

a = (1, 2, 3)
b = (4, 5, 6)
[print('f:', i, '; b', j) for i, j in zip(a, b)]

prints:

f: 1 ; b 4
f: 2 ; b 5
f: 3 ; b 6

Listing files in a specific "folder" of a AWS S3 bucket

As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)

AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));

Please note that I'm using ProfileCredentialsProvider so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.

In a unix shell, how to get yesterday's date into a variable?

$var=$TZ;
TZ=$TZ+24;
date;
TZ=$var;

Will get you yesterday in AIX and set back the TZ variable back to original

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

Can't install any packages in Node.js using "npm install"

If you happened to run npm install command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.

How to make a form close when pressing the escape key?

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

Pressing Ctrl + A in Selenium WebDriver

The simplest answer in C# (if you are C# inclined).

Actions action = new Actions(); 
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();

This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.

I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.

Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.

Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

ESLint not working in VS Code?

In my case setting eslint validate to : "eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ], did the job.

How to reload the datatable(jquery) data?

// Get the url from the Settings of the table: oSettings.sAjaxSource

function refreshTable(oTable) {
    table = oTable.dataTable();
    oSettings = table.fnSettings();

    //Retrieve the new data with $.getJSON. You could use it ajax too
    $.getJSON(oSettings.sAjaxSource, null, function( json ) {
        table.fnClearTable(this);

        for (var i=0; i<json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

What does --net=host option in Docker command really do?

After the docker installation you have 3 networks by default:

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
f3be8b1ef7ce        bridge              bridge              local
fbff927877c1        host                host                local
023bb5940080        none                null                local

I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.

$ docker run -d jenkins
1498e581cdba        jenkins             "/bin/tini -- /usr..."   3 minutes ago       Up 3 minutes        8080/tcp, 50000/tcp   friendly_bell

In the dockerfile of jenkins the ports 8080 and 50000 are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080 and 50000. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16", If you want to access them from the outside you have to map the ports with -p 8080:8080. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080 will route to your bridgenetwork on port 8080.

Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
1efd834949b2        jenkins             "/bin/tini -- /usr..."   6 minutes ago       Up 6 minutes                              eloquent_panini
1498e581cdba        jenkins             "/bin/tini -- /usr..."   10 minutes ago      Up 10 minutes       8080/tcp, 50000/tcp   friendly_bell

The difference is with the ports. Your container is now inside your host network. So if you open port 8080 on your host you will acces the container immediately.

$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT

I've opened port 8080 in my firewall and when I'm now accesing my server on port 8080 I'm accessing my jenkins. I think this blog is also useful to understand it better.

`&mdash;` or `&#8212;` is there any difference in HTML output?

SGML parsers (or XML parsers in the case of XHTML) can handle &#8212; without having to process the DTD (which doesn't matter to browsers as they just slurp tag soup), while &mdash; is easier for humans to read and write in the source code.

Personally, I would stick to a literal em-dash and ensure that my character encoding settings were consistent.

pandas get rows which are NOT in other dataframe

you can do it using isin(dict) method:

In [74]: df1[~df1.isin(df2.to_dict('l')).all(1)]
Out[74]:
   col1  col2
3     4    13
4     5    14

Explanation:

In [75]: df2.to_dict('l')
Out[75]: {'col1': [1, 2, 3], 'col2': [10, 11, 12]}

In [76]: df1.isin(df2.to_dict('l'))
Out[76]:
    col1   col2
0   True   True
1   True   True
2   True   True
3  False  False
4  False  False

In [77]: df1.isin(df2.to_dict('l')).all(1)
Out[77]:
0     True
1     True
2     True
3    False
4    False
dtype: bool

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

Splitting applicationContext to multiple files

Mike Nereson has this to say on his blog at:

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

There are a couple of ways to do this.

1. web.xml contextConfigLocation

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

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

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

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

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

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

2. applicationContext.xml import resource

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

In applicationContext.xml you might have…

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

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

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

Which strategy should you use?

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

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

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

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593

So Basically Just make sure that the Plugin Column contains "mysql_native_password".

Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.

Installing pip packages to $HOME folder

While you can use a virtualenv, you don't need to. The trick is passing the PEP370 --user argument to the setup.py script. With the latest version of pip, one way to do it is:

pip install --user mercurial

This should result in the hg script being installed in $HOME/.local/bin/hg and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/.

Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local to $HOME/Library/Python. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg and $HOME/Library/Python/x.y/lib/python/site-packages.

How to set a variable to be "Today's" date in Python/Pandas

i got the same problem so tried so many things but finally this is the solution.

import time 

print (time.strftime("%d/%m/%Y"))

Can we set a Git default to fetch all tags during a remote pull?

The --force option is useful for refreshing the local tags. Mainly if you have floating tags:

git fetch --tags --force

The git pull option has also the --force options, and the description is the same:

When git fetch is used with <rbranch>:<lbranch> refspec, it refuses to update the local branch <lbranch> unless the remote branch <rbranch> it fetches is a descendant of <lbranch>. This option overrides that check.

but, according to the doc of --no-tags:

By default, tags that point at objects that are downloaded from the remote repository are fetched and stored locally.

If that default statement is not a restriction, then you can also try

git pull --force

How to generate random positive and negative numbers in Java

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

How to get the size of a varchar[n] field in one SQL statement?

For t-SQL I use the following query for varchar columns (shows the collation and is_null properties):

SELECT
    s.name
    , o.name as table_name
    , c.name as column_name
    , t.name as type
    , c.max_length
    , c.collation_name
    , c.is_nullable
FROM
    sys.columns c
    INNER JOIN sys.objects o ON (o.object_id = c.object_id)
    INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
    INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
    s.name = 'dbo'
    AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
    o.name, c.name

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.

In my case the solution was as follows:

Script - stringify the original array (without using a named property)

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: mycontrolleraction,
        data: JSON.stringify(things)
    });

And in the controller method, use [FromBody]

    [HttpPost]
    public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }

Failures include:

  • Naming the content

    data: { content: nodes }, // Server error 500

  • Not having the contentType = Server error 500

Notes

  • dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
  • List<Thing> also works in the controller method

Fastest JavaScript summation

You should be able to use reduce.

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);

Source

And with arrow functions introduced in ES6, it's even simpler:

sum = array.reduce((pv, cv) => pv + cv, 0);

jQuery - select all text from a textarea

I ended up using this:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

postgresql COUNT(DISTINCT ...) very slow

You can use this:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

This is much faster than:

COUNT(DISTINCT column_name)

Adding a Method to an Existing Object Instance

Module new is deprecated since python 2.6 and removed in 3.0, use types

see http://docs.python.org/library/new.html

In the example below I've deliberately removed return value from patch_me() function. I think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.

import types

class A(object):#but seems to work for old style objects too
    pass

def patch_me(target):
    def method(target,x):
        print "x=",x
        print "called from", target
    target.method = types.MethodType(method,target)
    #add more if needed

a = A()
print a
#out: <__main__.A object at 0x2b73ac88bfd0>  
patch_me(a)    #patch instance
a.method(5)
#out: x= 5
#out: called from <__main__.A object at 0x2b73ac88bfd0>
patch_me(A)
A.method(6)        #can patch class too
#out: x= 6
#out: called from <class '__main__.A'>

Difference between Eclipse Europa, Helios, Galileo

The Eclipse (software) page on Wikipedia summarizes it pretty well:

Releases

Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.

So far, each Simultaneous Release has occurred at the end of June.

Release         Main Release   Platform version      Projects
Photon          27 June 2018     4.8
Oxygen          28 June 2017     4.7                 
Neon            22 June 2016     4.6                 
Mars            24 June 2015     4.5                 Mars Projects
Luna            25 June 2014     4.4                 Luna Projects
Kepler          26 June 2013     4.3                 Kepler Projects
Juno            27 June 2012     4.2                 Juno Projects
Indigo          22 June 2011     3.7                 Indigo projects
Helios          23 June 2010     3.6                 Helios projects
Galileo         24 June 2009     3.5                 Galileo projects
Ganymede        25 June 2008     3.4                 Ganymede projects
Europa          29 June 2007     3.3                 Europa projects
Callisto        30 June 2006     3.2                 Callisto projects
Eclipse 3.1     28 June 2005     3.1  
Eclipse 3.0     28 June 2004     3.0  

To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").

On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).

To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).