Programs & Examples On #Intrusive containers

How to automatically redirect HTTP to HTTPS on Apache servers?

I have actually followed this example and it worked for me :)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

Then do:

/etc/init.d/httpd restart

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

R: rJava package install failing

On Arch Linux, I needed to install openjdk-src to get a JNI path working.

In other words, these are the packages I needed to install before sudo R CMD javareconf ran successfully:

local/jdk-openjdk 14.0.2.u12-1
    OpenJDK Java 14 development kit
local/jre-openjdk 14.0.2.u12-1
    OpenJDK Java 14 full runtime environment
local/jre-openjdk-headless 14.0.2.u12-1
    OpenJDK Java 14 headless runtime environment
local/openjdk-src 14.0.2.u12-1
    OpenJDK Java 14 sources

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

How to cherry pick a range of commits and merge into another branch?

When it comes to a range of commits, cherry-picking is was not practical.

As mentioned below by Keith Kim, Git 1.7.2+ introduced the ability to cherry-pick a range of commits (but you still need to be aware of the consequence of cherry-picking for future merge)

git cherry-pick" learned to pick a range of commits
(e.g. "cherry-pick A..B" and "cherry-pick --stdin"), so did "git revert"; these do not support the nicer sequencing control "rebase [-i]" has, though.

damian comments and warns us:

In the "cherry-pick A..B" form, A should be older than B.
If they're the wrong order the command will silently fail.

If you want to pick the range B through D (including B) that would be B^..D (instead of B..D).
See "Git create branch from range of previous commits?" as an illustration.

As Jubobs mentions in the comments:

This assumes that B is not a root commit; you'll get an "unknown revision" error otherwise.

Note: as of Git 2.9.x/2.10 (Q3 2016), you can cherry-pick a range of commit directly on an orphan branch (empty head): see "How to make existing branch an orphan in git".


Original answer (January 2010)

A rebase --onto would be better, where you replay the given range of commit on top of your integration branch, as Charles Bailey described here.
(also, look for "Here is how you would transplant a topic branch based on one branch to another" in the git rebase man page, to see a practical example of git rebase --onto)

If your current branch is integration:

# Checkout a new temporary branch at the current location
git checkout -b tmp

# Move the integration branch to the head of the new patchset
git branch -f integration last_SHA-1_of_working_branch_range

# Rebase the patchset onto tmp, the old location of integration
git rebase --onto tmp first_SHA-1_of_working_branch_range~1 integration

That will replay everything between:

  • after the parent of first_SHA-1_of_working_branch_range (hence the ~1): the first commit you want to replay
  • up to "integration" (which points to the last commit you want to replay, from the working branch)

to "tmp" (which points to where integration was pointing before)

If there is any conflict when one of those commits is replayed:

  • either solve it and run "git rebase --continue".
  • or skip this patch, and instead run "git rebase --skip"
  • or cancel the all thing with a "git rebase --abort" (and put back the integration branch on the tmp branch)

After that rebase --onto, integration will be back at the last commit of the integration branch (that is "tmp" branch + all the replayed commits)

With cherry-picking or rebase --onto, do not forget it has consequences on subsequent merges, as described here.


A pure "cherry-pick" solution is discussed here, and would involve something like:

If you want to use a patch approach then "git format-patch|git am" and "git cherry" are your options.
Currently, git cherry-pick accepts only a single commit, but if you want to pick the range B through D that would be B^..D in git lingo, so

git rev-list --reverse --topo-order B^..D | while read rev 
do 
  git cherry-pick $rev || break 
done 

But anyway, when you need to "replay" a range of commits, the word "replay" should push you to use the "rebase" feature of Git.

How to log SQL statements in Spring Boot?

Log in to standard output

Add to application.properties

### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.

Using Logging Framework

Add to application.properties

### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.

How do you migrate an IIS 7 site to another server?

use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.

What's the best way to add a drop shadow to my UIView

The trick is defining the masksToBounds property of your view's layer properly:

view.layer.masksToBounds = NO;

and it should work.

(Source)

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I had a similar issue, and discovered that option arguments must be in a certain order. I am only aware of the two arguments that were required to get this working on my Ubuntu 18 machine. This sample code worked on my end:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

d = webdriver.Chrome(executable_path=r'/home/PycharmProjects/chromedriver', chrome_options=options)
d.get('https://www.google.nl/')

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

What is the MySQL JDBC driver connection string?

The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.

The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.

Shown Below shows a connection string with the retrieval of the connection:

public class Database {
   
    private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
    private String username = ""; //database username
    private String password = ""; //database password
    private static Database theDatabase = new Database(); 
    private Connection theConnection;
    
    private Database(){
        try{
              Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
              this.theConnection = DriverManager.getConnection(URL, username, password);
        } catch(Exception ex){
            System.out.println("Error Connecting to Database: "+ex);
        }
    }

    public static Database getDatabaseInstance(){
        return theDatabase;
    }
    
    public Connection getTheConnectionObject(){
        return theConnection;
    }
}

Writing a large resultset to an Excel file using POI

Unless you have to write formulas or formatting you should consider writing out a .csv file. Infinitely simpler, infinitely faster, and Excel will do the conversion to .xls or .xlsx automatically and correctly by definition.

How do I change tab size in Vim?

:set tabstop=4
:set shiftwidth=4
:set expandtab

This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Get week number (in the year) from a date PHP

$date_string = "2012-10-18";
echo "Weeknummer: " . date("W", strtotime($date_string));

How to test that no exception is thrown?

If you are unlucky enough to catch all errors in your code. You can stupidly do

class DumpTest {
    Exception ex;
    @Test
    public void testWhatEver() {
        try {
            thisShouldThrowError();
        } catch (Exception e) {
            ex = e;
        }
        assertEquals(null,ex);
    }
}

How do I find the maximum of 2 numbers?

max(number_one, number_two)

Angular2 disable button

Yes you can

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
 </div>

https://angular.io/docs/ts/latest/api/common/NgClass-directive.html

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

Why am I getting tree conflicts in Subversion?

In my experience, SVN creates a tree conflict WHENEVER I delete a folder. There appears to be no reason.

I'm the only one working on my code -> delete a directory -> commit -> conflict!

I can't wait to switch to Git.

I should clarify - I use Subclipse. That's probably the problem! Again, I can't wait to switch...

How to Bootstrap navbar static to fixed on scroll?

hey all everyone is over thinking this all you need to do is wrap the nav in a like below:

csscode:

#navwrap {  
    height: 100px;   (change dependant on hight of nav)
    width: 100%;
    margin: 0;
    padding-top: 5px;
}

HTML:

<div id="navwrap">
    nav code inside
</div>

How does OAuth 2 protect against things like replay attacks using the Security Token?

Here is perhaps the simplest explanation of how OAuth2 works for all 4 grant types, i.e., 4 different flows where the app can acquire the access token.

Similarity

All grant type flows have 2 parts:

  • Get access token
  • Use access token

The 2nd part 'use access token' is the same for all flows

Difference

The 1st part of the flow 'get access token' for each grant type varies.

However, in general the 'get access token' part can be summarized as consisting 5 steps:

  1. Pre-register your app (client) with OAuth provider, e.g., Twitter, etc. to get client id/secret
  2. Create a social login button with client id & required scopes/permissions on your page so when clicked user gets redirected to OAuth provider to be authenticated
  3. OAuth provider request user to grant permission to your app (client)
  4. OAuth provider issues code
  5. App (client) acquires access token

Here is a side-by-side diagram comparing how each grant type flow is different based on the 5 steps.

This diagram is from https://blog.oauth.io/introduction-oauth2-flow-diagrams/

enter image description here

Each have different levels of implementation difficulty, security, and uses cases. Depending on your needs and situation, you will have to use one of them. Which to use?

Client Credential: If your app is only serving a single user

Resource Owner Password Crendential: This should be used only as last resort as the user has to hand over his credentials to the app, which means the app can do everything the user can

Authorization Code: The best way to get user authorization

Implicit: If you app is mobile or single-page app

There is more explanation of the choice here: https://blog.oauth.io/choose-oauth2-flow-grant-types-for-app/

How to split long commands over multiple lines in PowerShell

Ah, and if you have a very long string that you want to break up, say of HTML, you can do it by putting a @ on each side of the outer " - like this:

$mystring = @"
Bob
went
to town
to buy
a fat
pig.
"@

You get exactly this:

Bob
went
to town
to buy
a fat
pig.

And if you are using Notepad++, it will even highlight correctly as a string block.

Now, if you wanted that string to contain double quotes, too, just add them in, like this:

$myvar = "Site"
$mystring = @"
<a href="http://somewhere.com/somelocation">
Bob's $myvar
</a>
"@

You would get exactly this:

<a href="http://somewhere.com/somelocation">
Bob's Site
</a>

However, if you use double-quotes in that @-string like that, Notepad++ doesn't realize that and will switch out the syntax colouring as if it were not quoted or quoted, depending on the case.

And what's better is this: anywhere you insert a $variable, it DOES get interpreted! (If you need the dollar sign in the text, you escape it with a tick mark like this: ``$not-a-variable`.)

NOTICE! If you don't put the final "@ at the very start of the line, it will fail. It took me an hour to figure out that I could not indent that in my code!

Here is MSDN on the subject: Using Windows PowerShell “Here-Strings”

How to join entries in a set into one string?

I think you just have it backwards.

print ", ".join(set_3)

Django request.GET

since your form has a field called 'q', leaving it blank still sends an empty string.

try

if 'q' in request.GET and request.GET['q'] != "" :
     message
else
     error message

Make HTML5 video poster be same size as video itself

You can use a transparent poster image in combination with a CSS background image to achieve this (example); however, to have a background stretched to the height and the width of a video, you'll have to use an absolutely positioned <img> tag (example).

It is also possible to set background-size to 100% 100% in browsers that support background-size (example).


Update

A better way to do this would be to use the object-fit CSS property as @Lars Ericsson suggests.

Use

object-fit: cover;

if you don't want to display those parts of the image that don't fit the video's aspect ratio, and

object-fit: fill;

to stretch the image to fit your video's aspect ratio

Example

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

Can I create a One-Time-Use Function in a Script or Stored Procedure?

The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:

IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
GO
CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
BEGIN
    SELECT Division =
        CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND  @Numerator != 0 AND @Numerator is NOT NULL THEN
        @Numerator / @Denominator
        ELSE
            0
        END
    RETURN
END
GO

Exec ##fn_Divide 6,4

This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.

How to cast ArrayList<> from List<>

Because in the first one , you're trying to convert a collection to an ArrayList. In the 2nd one , you just use the built in constructor of ArrayList

Redis: Show database size/size for keys

You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY commands followed by a TYPE on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.

I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.

Reset all the items in a form

If you have some panels or groupboxes reset fields should be recursive.

public class Utilities
{
    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            RecursiveResetForm(control);
        }
    }

    private void RecursiveResetForm(Control control)
    {            
        if (control.HasChildren)
        {
            foreach (Control subControl in control.Controls)
            {
                RecursiveResetForm(subControl);
            }
        }
        switch (control.GetType().Name)
        {
            case "TextBox":
                TextBox textBox = (TextBox)control;
                textBox.Text = null;
                break;

            case "ComboBox":
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
                break;

            case "CheckBox":
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = false;
                break;

            case "ListBox":
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
                break;

            case "NumericUpDown":
                NumericUpDown numericUpDown = (NumericUpDown)control;
                numericUpDown.Value = 0;
                break;
        }
    }        
}

Change default text in input type="file"?

I'd use a button to trigger the input:

<button onclick="document.getElementById('fileUpload').click()">Open from File...</button>
<input type="file" id="fileUpload" name="files" style="display:none" />

Quick and clean.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

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

I have got the same issue when tried to get users information without auth.

Check if you have loggen in before any request.

 $uid = $facebook->getUser();

 if ($uid){
      $me = $facebook->api('/me');
 }

The code above should solve your issue.

In Java, how do I get the difference in seconds between 2 dates?

You can use org.apache.commons.lang.time.DateUtils to make it cleaner:

(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND

How to download a file with Node.js (without using third-party libraries)?

Maybe node.js has changed, but it seems there are some problems with the other solutions (using node v8.1.2):

  1. You don't need to call file.close() in the finish event. Per default the fs.createWriteStream is set to autoClose: https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
  2. file.close() should be called on error. Maybe this is not needed when the file is deleted (unlink()), but normally it is: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  3. Temp file is not deleted on statusCode !== 200
  4. fs.unlink() without a callback is deprecated (outputs warning)
  5. If dest file exists; it is overridden

Below is a modified solution (using ES6 and promises) which handles these problems.

const http = require("http");
const fs = require("fs");

function download(url, dest) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest, { flags: "wx" });

        const request = http.get(url, response => {
            if (response.statusCode === 200) {
                response.pipe(file);
            } else {
                file.close();
                fs.unlink(dest, () => {}); // Delete temp file
                reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
            }
        });

        request.on("error", err => {
            file.close();
            fs.unlink(dest, () => {}); // Delete temp file
            reject(err.message);
        });

        file.on("finish", () => {
            resolve();
        });

        file.on("error", err => {
            file.close();

            if (err.code === "EEXIST") {
                reject("File already exists");
            } else {
                fs.unlink(dest, () => {}); // Delete temp file
                reject(err.message);
            }
        });
    });
}

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

Fastest way to serialize and deserialize .NET objects

Protobuf is very very fast.

See http://code.google.com/p/protobuf-net/wiki/Performance for in depth information concerning the performance of this system, and an implementation.

Node.js: Difference between req.query[] and req.params

Suppose you have defined your route name like this:

https://localhost:3000/user/:userid

which will become:

https://localhost:3000/user/5896544

Here, if you will print: request.params

{
userId : 5896544
}

so

request.params.userId = 5896544

so request.params is an object containing properties to the named route

and request.query comes from query parameters in the URL eg:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

so

request.query.userId = 5896544

Eclipse cannot load SWT libraries

I'm on debian linux amd64. I installed oracle's Java 11 from oracle's java download page. Installed eclipse from eclipse.org. Running eclipse produced the "cannot load swt" error. I followed ATorras's advice and did apt install libswt-gtk-4-jni (which also installed a ton of other things) and after that eclipse started. Although it started I did get the following errors/warnings:

org.eclipse.m2e.logback.configuration: The org.eclipse.m2e.logback.configuration bundle was activated before the state location was initialized.  Will retry after the state location is initialized.
SWT SessionManagerDBus: Failed to connect to org.gnome.SessionManager: Failed to execute child process “dbus-launch” (No such file or directory)
SWT SessionManagerDBus: Failed to connect to org.xfce.SessionManager: Failed to execute child process “dbus-launch” (No such file or directory)
org.eclipse.m2e.logback.configuration: Logback config file: /home/rusty/eclipse-workspace/.metadata/.plugins/org.eclipse.m2e.logback.configuration/logback.1.16.0.20200318-1040.xml
org.eclipse.m2e.logback.configuration: Initializing logback
SWT Webkit: Warning, You are using an old version of webkitgtk. (pre 2.4) BrowserFunction functionality will not be avaliable
SWT WebKit: error initializing DBus server, dBusServer == 0
SWT.CHROMIUM style was used but chromium.swt gtk (or CEF binaries) fragment/jar is missing.

I think I can ignore most if not all of that. I'm doing an ssh into the linux box using mobaXterm on my windows pc, so it's displaying its window on my pc. My linux box is headless.

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

Try this one:

self.GetHierarchyNodeList = function (data, index, event)
{
    debugger;
    if (event.type != "change") {
        return;
    }        
} 

event.type == "change"
event.type == "load" 

Change package name for Android in React Native

I've renamed the project' subfolder from: "android/app/src/main/java/MY/APP/OLD_ID/" to: "android/app/src/main/java/MY/APP/NEW_ID/"

Then manually switched the old and new package ids:

In: android/app/src/main/java/MY/APP/NEW_ID/MainActivity.java:

package MY.APP.NEW_ID;

In android/app/src/main/java/MY/APP/NEW_ID/MainApplication.java:

package MY.APP.NEW_ID;

In android/app/src/main/AndroidManifest.xml:

package="MY.APP.NEW_ID"

And in android/app/build.gradle:

applicationId "MY.APP.NEW_ID"

In android/app/BUCK:

android_build_config(
  package="MY.APP.NEW_ID"
)
android_resource(
  package="MY.APP.NEW_ID"
)

Gradle' cleaning in the end (in /android folder):

./gradlew clean

Can an AWS Lambda function call another

here's a sample code for python,

from boto3 import client as boto3_client
from datetime import datetime
import json

lambda_client = boto3_client('lambda')

def lambda_handler(event, context):
    msg = {"key":"new_invocation", "at": datetime.now()}
    invoke_response = lambda_client.invoke(FunctionName="another_lambda_",
                                           InvocationType='Event',
                                           Payload=json.dumps(msg))
    print(invoke_response)

Btw, you would need to add a policy like this to your lambda role as well

   {
        "Sid": "Stmt1234567890",
        "Effect": "Allow",
        "Action": [
            "lambda:InvokeFunction"
        ],
        "Resource": "*"
    }

force Maven to copy dependencies into target/lib

Try something like this:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
    <archive>
        <manifest>  
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>MainClass</mainClass>
        </manifest>
    </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <id>copy</id>
            <phase>install</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>
                    ${project.build.directory}/lib
                </outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

ng-if check if array is empty

Verify the length property of the array to be greater than 0:

<p ng-if="post.capabilities.items.length > 0">
   <strong>Topics</strong>: 
   <span ng-repeat="topic in post.capabilities.items">
     {{topic.name}}
   </span>
</p>

Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items"> evaluates always to true, even if the array is empty.

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

For IntelliJ IDEA or Android Studio:

Add this to app.gradle build file

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
} 

Replace -v:xx.0+, with your build target, if you have 19 platform then it must be like:

dependencies {
    compile "com.android.support:appcompat-v7:19.0.+"
}

How to use NULL or empty string in SQL

my best solution :

 WHERE  
 COALESCE(char_length(fieldValue), 0) = 0

COALESCE returns the first non-null expr in the expression list().

if the fieldValue is null or empty string then: we will return the second element then 0.

so 0 is equal to 0 then this fieldValue is a null or empty string.

in python for exemple:

def coalesce(fieldValue):
    if fieldValue in (null,''):
        return 0

good luck

How does the keyword "use" work in PHP and can I import classes with it?

Can I use it to import classes?

You can't do it like that besides the examples above. You can also use the keyword use inside classes to import traits, like this:

trait Stuff {
    private $baz = 'baz';
    public function bar() {
        return $this->baz;
    }
}

class Cls {
    use Stuff;  // import traits like this
}

$foo = new Cls;
echo $foo->bar(); // spits out 'baz'

Json.NET serialize object with root name

I hope this help.

//Sample of Data Contract:

[DataContract(Name="customer")]
internal class Customer {
  [DataMember(Name="email")] internal string Email { get; set; }
  [DataMember(Name="name")] internal string Name { get; set; }
}

//This is an extension method useful for your case:

public static string JsonSerialize<T>(this T o)
{
  MemoryStream jsonStream = new MemoryStream();
  var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
  serializer.WriteObject(jsonStream, o);

  var jsonString = System.Text.Encoding.ASCII.GetString(jsonStream.ToArray());

  var props = o.GetType().GetCustomAttributes(false);
  var rootName = string.Empty;
  foreach (var prop in props)
  {
    if (!(prop is DataContractAttribute)) continue;
    rootName = ((DataContractAttribute)prop).Name;
    break;
  }
  jsonStream.Close();
  jsonStream.Dispose();

  if (!string.IsNullOrEmpty(rootName)) jsonString = string.Format("{{ \"{0}\": {1} }}", rootName, jsonString);
  return jsonString;
}

//Sample of usage

var customer = new customer { 
Name="John",
Email="[email protected]"
};
var serializedObject = customer.JsonSerialize();

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

There is a compiler switch which enables C99 mode, which amongst other things allows declaration of a variable inside the for loop. To turn it on use the compiler switch -std=c99

Or as @OysterD says, declare the variable outside the loop.

Remove '\' char from string c#

Why not simply this?

resultString = Regex.Replace(subjectString, @"\\", "");

ES6 class variable alternatives

Well, you can declare variables inside the Constructor.

class Foo {
    constructor() {
        var name = "foo"
        this.method = function() {
            return name
        }
    }
}

var foo = new Foo()

foo.method()

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

What you really want to do is bind the event handler for the capture phase of the event. However, that isn't supported in IE as far as I know, so that might not be all that useful.

http://www.quirksmode.org/js/events_order.html

Related questions:

Android customized button; changing text color

Changing text color of button

Because this method is now deprecated

button.setTextColor(getResources().getColor(R.color.your_color));

I use the following:

button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));

Failed to resolve: com.google.firebase:firebase-core:9.0.0

If using command line tools, do

sdkmanager 'extras;google;m2repository'
sdkmanager 'extras;android;m2repository'

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

Remove leading and trailing spaces?

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

How can I let a user download multiple files when a button is clicked?

You can either:

  1. Zip the selected files and return the one zipped file.
  2. Open multiple pop-ups each prompting for a download.

Note - option one is objectively better.

Edit Found an option three: https://stackoverflow.com/a/9425731/1803682

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

I can't install intel HAXM

I've figured out. Try to disable Security Boot Control in BIOS options: http://remontka.pro/secure-boot-disable/ (sorry for russian examples) Or try to start system without Digital signature (only for one loading). I had had many unlucky attempts with 'HAXM installer, before I disabled this line. At the beginning I thought that's because Windows 10 Home was installed, and there're many limits.

Get width in pixels from element with style set with %?

You can use offsetWidth. Refer to this post and question for more.

_x000D_
_x000D_
console.log("width:" + document.getElementsByTagName("div")[0].offsetWidth + "px");
_x000D_
div {border: 1px solid #F00;}
_x000D_
<div style="width: 100%; height: 10px;"></div>
_x000D_
_x000D_
_x000D_

Clear History and Reload Page on Login/Logout Using Ionic Framework

I found that JimTheDev's answer only worked when the state definition had cache:false set. With the view cached, you can do $ionicHistory.clearCache() and then $state.go('app.fooDestinationView') if you're navigating from one state to the one that is cached but needs refreshing.

See my answer here as it requires a simple change to Ionic and I created a pull request: https://stackoverflow.com/a/30224972/756177

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

Set language for syntax highlighting in Visual Studio Code

Press Ctrl + KM and then type in (or click) the language you want.

Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:

enter image description here

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Reference excel worksheet by name?

The best way is to create a variable of type Worksheet, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet.

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range("A1:C10").Sort Key1:=Range("A2") is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")... and find out that it still doesn't work.

Here is the correct way:

Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

how do I check in bash whether a file was created more than x time ago?

I always liked using date -r /the/file +%s to find its age.

You can also do touch --date '2015-10-10 9:55' /tmp/file to get extremely fine-grained time on an arbitrary date/time.

Windows 8.1 gets Error 720 on connect VPN

Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:

why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.

Solution:

  1. check write permissions on registers

    a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it

    b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log

    c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"

    d. run the following command netsh int ipv6 reset reset.log and repeat step c)

  2. unistall all not-working miniports

    a. go to device managers (windows+x -> device manager)

    b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)

    c. unistall these not working devices

    d. reboot your computer

    e. Repeat steps a) - d) until you will not see any yellow mark on miniports

  3. delete your vpn connection and create a new one.

that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)

references:

http://en.remontka.pro/error-720-windows-8-and-8-1-solved/

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

How to get full path of a file?

the easiest way I found is

for i in `ls`; do echo "`pwd`/$i"; done

it works well for me

Choosing a file in Python with simple Dialog

With EasyGui:

import easygui
print(easygui.fileopenbox())

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()

Parse strings to double with comma and point

You want to treat dot (.) like comma (,). So, replace

if (double.TryParse(values[i, j], out tmp))

with

if (double.TryParse(values[i, j].Replace('.', ','), out tmp))

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

Count the cells with same color in google spreadsheet

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = book.getActiveSheet();
 var range_input = sheet.getRange("B3:B4");
 var range_output = sheet.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for(var r = 0; r < cell_colors.length; r++) {
   for(var c = 0; c < cell_colors[0].length; c++) {
     if(cell_colors[r][c] == color) {
       count = count + 1;
     }
   }
 }
    range_output.setValue(count);
 }

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.

In production this error will not happen, since the request and the api will be in the same domain.

I hope it helps!

Vim clear last search highlighting

To turn off highlighting until the next search

:noh

Visual Illustration

log4j configuration via JVM argument(s)?

Late to the party as since 2015, Log4J 1.x has reached EOL.

Log4J 2.x onwards the JVM option should be -Dlog4j.configurationFile=<filename>


P.S. <filename> could be a file relative to the class path without the file: as suggested in the other answers.

Gulp command not found after install

If you want to leave your prefix intact, just export it's bin dir to your PATH variable:
export PATH=$HOME/your-path/bin:$PATH
I added this line to my $HOME/.profile and sourced it.

Setting prefix to /usr/local makes you use sudo, so I like to have it in my user dir. You can check your prefix with npm prefix -g.

javac option to compile all java files under a given directory recursively

I've been using this in an Xcode JNI project to recursively build my test classes:

find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

Create Excel files from C# without office

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

Relative URLs in WordPress

I think this is the kind of question only a core developer could/should answer. I've researched and found the core ticket #17048: URLs delivered to the browser should be root-relative. Where we can find the reasons explained by Andrew Nacin, lead core developer. He also links to this [wp-hackers] thread. On both those links, these are the key quotes on why WP doesn't use relative URLs:

Core ticket:

  • Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] thread

  • Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


And, on a personal note, more than once I've found theme and plugins bad coded that simply break when WP_CONTENT_URL is defined.
They don't know this can be set and assume that this is true: WP.URL/wp-content/WhatEver, and it's not always the case. And something will break along the way.


The plugin Relative URLs (linked in edse's Answer), applies the function wp_make_link_relative in a series of filters in the action hook template_redirect. It's quite a simple code and seems a nice option.

How do I combine 2 select statements into one?

Thanks for the input. Tried the stuff that has been mentioned here and these are the 2 I got to work:

(
select 'OK', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'
AND (BoolField05=1)
)
UNION
(
select 'DEL', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
)

AND

select 
    case
        when
            (BoolField05=1)
    then 'OK'
    else 'DEL'
        end,
        *
from WorkItems t1
Where
            exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
            AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
            AND TimeStamp>'2009-02-12 18:00:00'

Which would be the most efficient of these (edit: the second as it only scans the table once), and is it possible to make it even more efficient? (The BoolField=1) is really a variable (dyn sql) that can contain any where statement on the table.

I am running on MS SQL 2005. Tried Quassnoi examples but did not work as expected.

This compilation unit is not on the build path of a Java project

If it is a Maven project then sometimes re-importing of it helps:

  1. Right-click the project in the Project Explorer and choose Delete.
  2. File > Import... > Maven > Existing Maven Projects > Next > Root Directory > Browse your project from Disk.

Hope it will resolve the issue.

binning data in python with scipy/numpy

Not sure why this thread got necroed; but here is a 2014 approved answer, which should be far faster:

import numpy as np

data = np.random.rand(100)
bins = 10
slices = np.linspace(0, 100, bins+1, True).astype(np.int)
counts = np.diff(slices)

mean = np.add.reduceat(data, slices[:-1]) / counts
print mean

Can't bind to 'ngModel' since it isn't a known property of 'input'

In the module you are willing to use ngModel you have to import FormsModule

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
  ],

})
export class AbcModule { }

smooth scroll to top

Here is my proposal implemented with ES6

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();

Tip: for slower motion of the scrolling, increase the hardcoded number 8. The bigger the number - the smoother/slower the scrolling.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

How to find the path of Flutter SDK

All you need to do is to find a folder called "flutter" (lowecase), which is located inside a folder called "Flutter" (uppercase), select it, and browse it.

In my case it is located at:

C:\Users\Administrator\Flutter\flutter_windows_v1.12.13+hotfix.5-stable\flutter

enter image description here

Also make sure that your Flutter and Dart are of the latest version. If they are not, upgrade them and re-start the IDE.

Detect changed input text box

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How can I append a query parameter to an existing URL?

I suggest an improvement of the Adam's answer accepting HashMap as parameter

/**
 * Append parameters to given url
 * @param url
 * @param parameters
 * @return new String url with given parameters
 * @throws URISyntaxException
 */
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
    URI uri = new URI(url);
    String query = uri.getQuery();

    StringBuilder builder = new StringBuilder();

    if (query != null)
        builder.append(query);

    for (Map.Entry<String, String> entry: parameters.entrySet())
    {
        String keyValueParam = entry.getKey() + "=" + entry.getValue();
        if (!builder.toString().isEmpty())
            builder.append("&");

        builder.append(keyValueParam);
    }

    URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
    return newUri.toString();
}

Make child visible outside an overflow:hidden parent

This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>

CSS to hide INPUT BUTTON value text

Applying font-size: 0.1px; to the button works for me in Firefox, Internet Explorer 6, Internet Explorer 7, and Safari. None of the other solutions I've found worked across all of the browsers.

Tool to generate JSON schema from JSON data

For node.js > 6.0.0 there is also the json-schema-by-example module.

Checking if a variable is initialized

With C++-11 or Boost libs you could consider storing the variable using smart pointers. Consider this MVE where toString() behaviour depends on bar being initialized or not:

#include <memory>
#include <sstream>

class Foo {

private:
    std::shared_ptr<int> bar;

public:
    Foo() {}
    void setBar(int bar) {
        this->bar = std::make_shared<int>(bar);
    }
    std::string toString() const {
        std::ostringstream ss;
        if (bar)           // bar was set
            ss << *bar;
        else               // bar was never set
            ss << "unset";
        return ss.str();
    }
};

Using this code

Foo f;
std::cout << f.toString() << std::endl;
f.setBar(42);
std::cout << f.toString() << std::endl;

produces the output

unset
42

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

Round double value to 2 decimal places

You can use the below code to format it to two decimal places

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];

NSLog(@"Result...%@",numberString);//Result 22.37

Swift 4:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .up

let str = String(describing: formatter.string(from: 12.2345)!)

print(str)

How to get $HOME directory of different user in bash script?

I was also looking for this, but didn't want to impersonate a user to simply acquire a path!

user_path=$(grep $username /etc/passwd|cut -f6 -d":");

Now in your script, you can refer to $user_path in most cases would be /home/username

Assumes: You have previously set $username with the value of the intended users username. Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html

jQuery: Return data after ajax call success

Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:

If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.

Generally, instead of:

function testAjax() {
  $.ajax({
    url: "getvalue.php",  
    success: function(data) {
      return data; 
    }
  });
}

you can write your testAjax function like this:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

Then you can get your promise like this:

var promise = testAjax();

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:

promise.success(function (data) {
  alert(data);
});

(See updates below for simplified syntax.)

If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.

The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.

See this DEMO.

UPDATE (2015)

Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.

However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.

What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.

But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.

In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.

For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.

How to return a real promise

The function from my example above:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

returns a jqXHR object, which is a jQuery Deferred Object.

To make it return a real promise, you can change it to - using the method from the Q wiki:

function testAjax() {
  return Q($.ajax({
      url: "getvalue.php"
  }));
}

or, using the method from the HTML5 Rocks article:

function testAjax() {
  return Promise.resolve($.ajax({
      url: "getvalue.php"
  }));
}

This Promise.resolve($.ajax(...)) is also what is explained in the promise module documentation and it should work with ES6 Promise.resolve().

To use the ES6 Promises today you can use es6-promise module's polyfill() by Jake Archibald.

To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.

For more info see:

Future of jQuery

Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.

Interesting talks

UPDATE (2016)

There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.

Using the jQuery API, instead of:

promise.success(function (data) {
  alert(data);
});

you can write:

promise.success(data => alert(data));

or using the Promises/A+ API:

promise.then(data => alert(data));

Remember to always use rejection handlers either with:

promise.then(data => alert(data), error => alert(error));

or with:

promise.then(data => alert(data)).catch(error => alert(error));

See this answer to see why you should always use rejection handlers with promises:

Of course in this example you could use just promise.then(alert) because you're just calling alert with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:

promise.then(data => alert("x is " + data.x));

Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).

For the support of arrow functions, see:

UPDATE (2017)

There is an even newer syntax right now called async functions with a new await keyword that instead of this code:

functionReturningPromise()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

lets you write:

try {
    let data = await functionReturningPromise();
    console.log('Data:', data);
} catch (error) {
    console.log('Error:', error);
}

You can only use it inside of a function created with the async keyword. For more info, see:

For support in browsers, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

More info

Some other questions about promises for more details:

How to darken a background using CSS?

You can use a container for your background, placed as absolute and negative z-index : http://jsfiddle.net/2YW7g/

HTML

<div class="main">
    <div class="bg">         
    </div>
    Hello World!!!!
</div>

CSS

.main{
    width:400px;
    height:400px;
    position:relative;
    color:red;
    background-color:transparent;
    font-size:18px;
}
.main .bg{
    position:absolute;
      width:400px;
    height:400px;
    background-image:url("http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png");
    z-index:-1;
}

.main:hover .bg{
    opacity:0.5;
}

How do I speed up the gwt compiler?

You can add one option to your build for production:

-localWorkers 8 – Where 8 is the number of concurrent threads that calculate permutations. All you have to do is to adjust this number to the number that is more convenient to you. See GWT compilation performance (thanks to Dennis Ich comment).

If you are compiling to the testing environment, you can also use:

-draftCompile which enables faster, but less-optimized compilations

-optimize 0 which does not optimize your code (9 is the max optimization value)

Another thing that more than doubled the build and hosted mode performance was the use of an SSD disk (now hostedmode works like a charm). It's not an cheap solution, but depending on how much you use GWT and the cost of your time, it may worth it!

Hope this helps you!

How to create a notification with NotificationCompat.Builder?

simple way for make notifications

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher) //icon
            .setContentTitle("Test") //tittle
            .setAutoCancel(true)//swipe for delete
            .setContentText("Hello Hello"); //content
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, builder.build()
    );

Remove blank attributes from an Object in Javascript

Here is a comprehensive recursive function (originally based on the one by @chickens) that will:

  • recursively remove what you tell it to defaults=[undefined, null, '', NaN]
  • Correctly handle regular objects, arrays and Date objects
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
  if (!defaults.length) return obj
  if (defaults.includes(obj)) return

  if (Array.isArray(obj))
    return obj
      .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
      .filter(v => !defaults.includes(v))

  return Object.entries(obj).length 
    ? Object.entries(obj)
        .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
        .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) 
    : obj
}

USAGE:

_x000D_
_x000D_
// based off the recursive cleanEmpty function by @chickens. _x000D_
// This one can also handle Date objects correctly _x000D_
// and has a defaults list for values you want stripped._x000D_
_x000D_
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {_x000D_
  if (!defaults.length) return obj_x000D_
  if (defaults.includes(obj)) return_x000D_
_x000D_
  if (Array.isArray(obj))_x000D_
    return obj_x000D_
      .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)_x000D_
      .filter(v => !defaults.includes(v))_x000D_
_x000D_
  return Object.entries(obj).length _x000D_
    ? Object.entries(obj)_x000D_
        .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))_x000D_
        .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) _x000D_
    : obj_x000D_
}_x000D_
_x000D_
_x000D_
// testing_x000D_
_x000D_
console.log('testing: undefined \n', cleanEmpty(undefined))_x000D_
console.log('testing: null \n',cleanEmpty(null))_x000D_
console.log('testing: NaN \n',cleanEmpty(NaN))_x000D_
console.log('testing: empty string \n',cleanEmpty(''))_x000D_
console.log('testing: empty array \n',cleanEmpty([]))_x000D_
console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000)))_x000D_
console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }}))_x000D_
console.log('testing: comprehensive obj \n', cleanEmpty({_x000D_
  a: 5,_x000D_
  b: 0,_x000D_
  c: undefined,_x000D_
  d: {_x000D_
    e: null,_x000D_
    f: [{_x000D_
      a: undefined,_x000D_
      b: new Date(),_x000D_
      c: ''_x000D_
    }]_x000D_
  },_x000D_
  g: NaN,_x000D_
  h: null_x000D_
}))_x000D_
console.log('testing: different defaults \n', cleanEmpty({_x000D_
  a: 5,_x000D_
  b: 0,_x000D_
  c: undefined,_x000D_
  d: {_x000D_
    e: null,_x000D_
    f: [{_x000D_
      a: undefined,_x000D_
      b: '',_x000D_
      c: new Date()_x000D_
    }]_x000D_
  },_x000D_
  g: [0, 1, 2, 3, 4],_x000D_
  h: '',_x000D_
}, [undefined, null]))
_x000D_
_x000D_
_x000D_

Use tnsnames.ora in Oracle SQL Developer

This excellent answer to a similar question (that I could not find before, unfortunately) helped me solve the problem.

Copying Content from referenced answer :

SQL Developer will look in the following location in this order for a tnsnames.ora file

$HOME/.tnsnames.ora
$TNS_ADMIN/tnsnames.ora
TNS_ADMIN lookup key in the registry
/etc/tnsnames.ora ( non-windows )
$ORACLE_HOME/network/admin/tnsnames.ora
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME_KEY
LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME

If your tnsnames.ora file is not getting recognized, use the following procedure:

Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.

In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...
In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.

Confirm the os is recognizing this environmental variable

From the Windows command line: echo %TNS_ADMIN%

From linux: echo $TNS_ADMIN

Restart SQL Developer Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Best practice multi language website

Just a sub answer: Absolutely use translated urls with a language identifier in front of them: http://www.domain.com/nl/over-ons
Hybride solutions tend to get complicated, so I would just stick with it. Why? Cause the url is essential for SEO.

About the db translation: Is the number of languages more or less fixed? Or rather unpredictable and dynamic? If it is fixed, I would just add new columns, otherwise go with multiple tables.

But generally, why not use Drupal? I know everybody wants to build their own CMS cause it's faster, leaner, etc. etc. But that is just really a bad idea!

How to fix missing dependency warning when using useEffect React Hook?

This article is a good primer on fetching data with hooks: https://www.robinwieruch.de/react-hooks-fetch-data/

Essentially, include the fetch function definition inside useEffect:

useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theUrl"...
      // ...your fetch implementation
    );
  }

  fetchBusinesses();
}, []);

How to center links in HTML

Since you have a list of links, you should be marking them up as a list (and not as paragraphs).

Listamatic has a bunch of examples of how you can style lists of links, including a number that are vertical lists with each link being centred (which is what you appear to be after). It also has a tutorial which explains the principles.

That part of the styling essentially boils down to "Set text-align: center on an element that is displaying as a block which contains the link text" (that could be the anchor itself (if you make it display as a block) or the list item containing it.

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

There is problem with Bootstrap version and jQuery version in my case.. I fixeed it by changing the version of Bootstrap and jQuery. thank you!!

Java Reflection: How to get the name of a variable?

You can do like this:

Field[] fields = YourClass.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);         
for (Field field : fields) {
    //gives the names of the fields
    System.out.println(field.getName());   
}

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

Circle button css

For create circle button you are this codes:

_x000D_
_x000D_
.circle-right-btn {
    display: block;
    height: 50px;
    width: 50px;
    border-radius: 50%;
    border: 1px solid #fefefe;
    margin-top: 24px;
    font-size:22px;
}
_x000D_
<input  class="circle-right-btn" type="submit" value="<">
_x000D_
_x000D_
_x000D_

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

Set height of chart in Chart.js

You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options

//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>

<script>
new Chart(somechart, {
options: {
    responsive: true,
    maintainAspectRatio: false

/*, your other options*/

}
});
</script>

How can I lookup a Java enum from its String value?

with Java 8 you can achieve with this way:

public static Verbosity findByAbbr(final String abbr){
    return Arrays.stream(values()).filter(value -> value.abbr().equals(abbr)).findFirst().orElse(null);
}

How to to send mail using gmail in Laravel?

Note: Laravel 7 replaced MAIL_DRIVER by MAIL_MAILER

MAIL_MAILER=smtp    
MAIL_HOST=smtp.gmail.com   
MAIL_PORT=587      
MAIL_USERNAME=yourgmailaddress
MAIL_PASSWORD=yourgmailpassword
MAIL_ENCRYPTION=tls

Allow less secure apps from "Google Account" - https://myaccount.google.com/ - Settings - Less secure app access (Turn On)

Flush cache config:

php artisan config:cache

For Apache:

sudo service apache2 restart

no debugging symbols found when using gdb

Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.

How to auto import the necessary classes in Android Studio with shortcut?

Go on the missing declaration with cursor and press alt+enter enter image description here

Plotting time in Python with Matplotlib

7 years later and this code has helped me. However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly. enter image description here

All thanks to the community.

Compile error: package javax.servlet does not exist

Copy the file "servlet-api.jar" from location YOUR_INSTILLATION_PATH\tomcat\lib\servlet-api.jar and Paste the file into your Java Directory YOUR_INSTILLATION_PATH\Java\jdk1.8.0_121\jre\lib\ext

this will work (tested).

TypeError: Router.use() requires middleware function but got a Object

check your routes.js file

example my routes.js

_x000D_
_x000D_
    const express = require('express')_x000D_
    const router = express.Router()_x000D_
    _x000D_
    const usersController = require('../app/controllers/usersController')_x000D_
    const autheticateuser = require('../app/middlewares/authentication')_x000D_
    _x000D_
    router.post('/users/login', autheticateuser, usersController.login)_x000D_
    router.post('/users/register', autheticateuser, usersController.register)_x000D_
      
_x000D_
_x000D_
_x000D_

check end of routes.js

module.exports = router

if not there add and module.exports = router run again


If your Error is : "TypeError: Route.post() or Route.get() requires middleware function but got a Object"

goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers

_x000D_
_x000D_
const User = require('../models/user')_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
_x000D_
_x000D_
module.exports.register = (req, res) => {_x000D_
    const data = req.body_x000D_
    const user = new User(data)_x000D_
    user.save()_x000D_
        .then((user) => {_x000D_
            res.send(user)_x000D_
        })_x000D_
        .catch((err) => {_x000D_
            res.json(err)_x000D_
        })_x000D_
}
_x000D_
_x000D_
_x000D_

in routes.js i given two routes but in controllers i missed to define route for

router.post('/users/login')

this will make error **

"TypeError: route.post() requires middleware function but got a Object"

**

C Program to find day of week given date

#include<stdio.h>
static char day_tab[2][13] = {
        {0,31,28,31,30,31,30,31,31,30,31,30,31},
        {0,31,29,31,30,31,30,31,31,30,31,30,31}
        };
int main()
{
     int year,month;
     scanf("%d%d%d",&year,&month,&day);
     printf("%d\n",day_of_year(year,month,day));
     return 0;
}
int day_of_year(int year ,int month,int day)
{
        int i,leap;
        leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
        if(month < 1 || month >12)
        return -1;
        if (day <1 || day > day_tab[leap][month])
        return -1;
        for(i= 1;i<month ; i++)
        {
                day += day_tab[leap][year];
        }
        return day;
}

ModelState.AddModelError - How can I add an error that isn't for a property?

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

How to find difference between two Joda-Time DateTimes in minutes

This will get you the difference between two DateTime objects in milliseconds:

DateTime d1 = new DateTime();
DateTime d2 = new DateTime();

long diffInMillis = d2.getMillis() - d1.getMillis();

How to check for null in Twig?

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/

PDO closing connection

$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    // If this is your connection then you have to assign null
    // to your connection variable as follows:
$conn=null;
    // By this way you can close connection in PDO.

When a 'blur' event occurs, how can I find out which element focus went *to*?

As noted in this answer, you can check the value of document.activeElement. document is a global variable, so you don't have to do any magic to use it in your onBlur handler:

function myOnBlur(e) {
  if(document.activeElement ===
       document.getElementById('elementToCheckForFocus')) {
    // Focus went where we expected!
    // ...
  }
}

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

How can I add reflection to a C++ application?

I would like to advertise the existence of the automatic introspection/reflection toolkit "IDK". It uses a meta-compiler like Qt's and adds meta information directly into object files. It is claimed to be easy to use. No external dependencies. It even allows you to automatically reflect std::string and then use it in scripts. Please look at IDK

How to set the font size in Emacs?

This is another simple solution. Works in 24 as well

(set-default-font "Monaco 14")

Short cuts:

`C-+` increases font size
`C--` Decreases font size

Get a Windows Forms control by name in C#

string name = "the_name_you_know";

Control ctn = this.Controls[name];

ctn.Text = "Example...";

Determine whether an array contains a value

Since ECMAScript6, one can use Set:

var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false

How to find SQL Server running port?

SQL Server 2000 Programs | MS SQL Server | Client Network Utility | Select TCP_IP then Properties

SQL Server 2005 Programs | SQL Server | SQL Server Configuration Manager | Select Protocols for MSSQLSERVER or select Client Protocols and right click on TCP/IP

How do I get the number of elements in a list?

In terms of how len() actually works, this is its C implementation:

static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
    Py_ssize_t res;

    res = PyObject_Size(obj);
    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }
    return PyLong_FromSsize_t(res);
}

Py_ssize_t is the maximum length that the object can have. PyObject_Size() is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:

    if (res < 0) {
        assert(PyErr_Occurred());
        return NULL;
    }

And an exception is raised as a result. Otherwise, this code block will be executed:

    return PyLong_FromSsize_t(res);

res which is a C integer, is converted into a Python int (which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Konrad Rudolph has the right answer.

If it really bugs you, monkey patch the String class or add it to a class/module of your choice. It's really not a good practice to monkey patch core objects unless you have a really compelling reason though.

class String
  def self.nilorempty?(string)
    string.nil? || string.empty?
  end
end

Then you can do String.nilorempty? mystring

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Origin is not allowed by Access-Control-Allow-Origin

if you're under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

jQuery Call to WebService returns "No Transport" error

I too got this problem and all solutions given above either failed or were not applicable due to client webservice restrictions.

For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.

We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.

Hope it helps

<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
 </iframe>

//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');

//The iframe receives the data using the code:
window.onload = function () {
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        var origin = e.origin;
        //if origin not in pre-defined list, break and return
        var messageFromParent = JSON.parse(e.data);
        var json = messageFromParent.data;

        //send json to web service using AJAX   
        //return the response back to source
        e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
    }, false);
}

Firefox setting to enable cross domain Ajax request

Manually editing firefox's settings is the way to go, but it's inconvenient when you need to do it often.

Instead, you can install an add-on that will do it for you in one click.

I use CORS everywhere, which works great for me.

Here is a link to the installer

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Strip HTML from strings in Python

If you want to strip all HTML tags the easiest way I found is using BeautifulSoup:

from bs4 import BeautifulSoup  # Or from BeautifulSoup import BeautifulSoup

def stripHtmlTags(htmlTxt):
    if htmlTxt is None:
            return None
        else:
            return ''.join(BeautifulSoup(htmlTxt).findAll(text=True)) 

I tried the code of the accepted answer but I was getting "RuntimeError: maximum recursion depth exceeded", which didn't happen with the above block of code.

Days between two dates?

Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.

from datetime import timedelta, datetime

def cal_days_diff(a,b):

    A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    return (A - B).days

if __name__ == '__main__':

    x = datetime(2013, 06, 18, 16, 00)
    y = datetime(2013, 06, 19, 2, 00)

    print (y - x).days          # 0
    print cal_days_diff(y, x)   # 1 

    z = datetime(2013, 06, 20, 2, 00)

    print (z - x).days          # 1
    print cal_days_diff(z, x)   # 2 

jQuery scroll to element

In most cases, it would be best to use a plugin. Seriously. I'm going to tout mine here. Of course there are others, too. But please check if they really avoid the pitfalls for which you'd want a plugin in the first place - not all of them do.

I have written about the reasons for using a plugin elsewhere. In a nutshell, the one liner underpinning most answers here

$('html, body').animate( { scrollTop: $target.offset().top }, duration );

is bad UX.

  • The animation doesn't respond to user actions. It carries on even if the user clicks, taps, or tries to scroll.

  • If the starting point of the animation is close to the target element, the animation is painfully slow.

  • If the target element is placed near the bottom of the page, it can't be scrolled to the top of the window. The scroll animation stops abruptly then, in mid motion.

To handle these issues (and a bunch of others), you can use a plugin of mine, jQuery.scrollable. The call then becomes

$( window ).scrollTo( targetPosition );

and that's it. Of course, there are more options.

With regard to the target position, $target.offset().top does the job in most cases. But please be aware that the returned value doesn't take a border on the html element into account (see this demo). If you need the target position to be accurate under any circumstances, it is better to use

targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;

That works even if a border on the html element is set.

How to stick a footer to bottom in css?

I think a lot of folks are looking for a footer on the bottom that scrolls instead of being fixed, called a sticky footer. Fixed footers will cover body content when the height is too short. You have to set the html, body, and page container to a height of 100%, set your footer to absolute position bottom. Your page content container needs a relative position for this to work. Your footer has a negative margin equal to height of footer minus bottom margin of page content. See the example page I posted.

Example with notes: http://markbokil.com/code/bottomfooter/

How to convert string to double with proper cultureinfo

Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture

TryParse does not allway work as we would expect There are change request in .net in this area:

https://github.com/dotnet/runtime/issues/25868

How to extend / inherit components?

Alternative Solution:

This answer of Thierry Templier is an alternative way to get around the problem.

After some questions with Thierry Templier, I came to the following working example that meets my expectations as an alternative to inheritance limitation mentioned in this question:

1 - Create custom decorator:

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        // verify is annotation typeof function
        if(typeof annotation[key] === 'function'){
          annotation[key] = annotation[key].call(this, parentAnnotation[key]);
        }else if(
        // force override in annotation base
        !isPresent(annotation[key])
        ){
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    var metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

2 - Base Component with @Component decorator:

@Component({
  // create seletor base for test override property
  selector: 'master',
  template: `
    <div>Test</div>
  `
})
export class AbstractComponent {

}

3 - Sub component with @CustomComponent decorator:

@CustomComponent({
  // override property annotation
  //selector: 'sub',
  selector: (parentSelector) => { return parentSelector + 'sub'}
})
export class SubComponent extends AbstractComponent {
  constructor() {
  }
}

Plunkr with complete example.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        s += scan.nextLine();
        System.out.println("String: " + s);

    }
}

Getting ssh to execute a command in the background on target machine

I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on nohup, copied here for your convenience.

Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams:

nohup myprogram > foo.out 2> foo.err < /dev/null &

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

  1. This is because of the gradle version.

  2. Go to: gradle/wrapper/gradle-wrapper.properties.

  3. Change a version of the course by this:

distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip

The console outputs:

Welcome to Gradle 6.3!

Here are the highlights of this release:
 - Java 14 support
 - Improved error messages for unexpected failures

For more details see https://docs.gradle.org/6.3/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

What is the http-header "X-XSS-Protection"?

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

How can I override Bootstrap CSS styles?

Using !important is not a good option, as you will most likely want to override your own styles in the future. That leaves us with CSS priorities.

Basically, every selector has its own numerical 'weight':

  • 100 points for IDs
  • 10 points for classes and pseudo-classes
  • 1 point for tag selectors and pseudo-elements
  • Note: If the element has inline styling that automatically wins (1000 points)

Among two selector styles browser will always choose the one with more weight. Order of your stylesheets only matters when priorities are even - that's why it is not easy to override Bootstrap.

Your option is to inspect Bootstrap sources, find out how exactly some specific style is defined, and copy that selector so your element has equal priority. But we kinda loose all Bootstrap sweetness in the process.

The easiest way to overcome this is to assign additional arbitrary ID to one of the root elements on your page, like this: <body id="bootstrap-overrides">

This way, you can just prefix any CSS selector with your ID, instantly adding 100 points of weight to the element, and overriding Bootstrap definitions:

/* Example selector defined in Bootstrap */
.jumbotron h1 { /* 10+1=11 priority scores */
  line-height: 1;
  color: inherit;
}

/* Your initial take at styling */
h1 { /* 1 priority score, not enough to override Bootstrap jumbotron definition */
  line-height: 1;
  color: inherit;
}

/* New way of prioritization */
#bootstrap-overrides h1 { /* 100+1=101 priority score, yay! */
  line-height: 1;
  color: inherit;
}

Formatting code in Notepad++

there is such a plugin as UniversalIndentGUI, it can be installed right from the plugin manager and has possibilities to reindent the most used programming languages.

How to get current user who's accessing an ASP.NET application?

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

ASP.NET Web Site or ASP.NET Web Application?

In a web application you can create the layers of your project's functionality and can create inter-dependencies between them by dividing it into many projects, but you can never do this on a website.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

For a CSS-only (and icon-free) solution using Bootstrap 3 I had to do a bit of fiddling based on Martin Wickman's answer above.

I didn't use the accordion-* notation because it's done with panels in BS3.

Also, I had to include in the initial HTML aria-expanded="true" on the item that's open at page load.

Here is the CSS I used.

.accordion-toggle:hover { text-decoration: none; }
.accordion-toggle:hover span, .accordion-toggle:hover strong { text-decoration: underline; }
.accordion-toggle:before { font-size: 25px; }
.accordion-toggle[data-toggle="collapse"]:before { content: "+"; margin-right: 0px; }
.accordion-toggle[aria-expanded="true"]:before { content: "-"; margin-right: 0px; }

Here is my sanitized HTML:

<div id="acc1">    
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" aria-expanded="true" data-parent="#acc1" href="#acc1-1">Title 1
                    </a>
            </span>
        </div>
        <div id=“acc1-1” class="panel-collapse collapse in">
            <div class="panel-body">
                Text 1
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc1” href=“#acc1-2”>Title 2
                    </a>
            </span>
        </div>
        <div id=“acc1-2” class="panel-collapse collapse">
            <div class="panel-body">
                Text 2                  
            </div>
        </div>
    </div>
</div>

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

#!/bin/bash
ipcs -m | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -m
ipcs -s | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -s
ipcs -q | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -q

Is there any way to kill a Thread?

While it's rather old, this might be a handy solution for some:

A little module that extends the threading's module functionality -- allows one thread to raise exceptions in the context of another thread. By raising SystemExit, you can finally kill python threads.

import threading
import ctypes     

def _async_raise(tid, excobj):
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class Thread(threading.Thread):
    def raise_exc(self, excobj):
        assert self.isAlive(), "thread must be started"
        for tid, tobj in threading._active.items():
            if tobj is self:
                _async_raise(tid, excobj)
                return

        # the thread was alive when we entered the loop, but was not found 
        # in the dict, hence it must have been already terminated. should we raise
        # an exception here? silently ignore?

    def terminate(self):
        # must raise the SystemExit type, instead of a SystemExit() instance
        # due to a bug in PyThreadState_SetAsyncExc
        self.raise_exc(SystemExit)

So, it allows a "thread to raise exceptions in the context of another thread" and in this way, the terminated thread can handle the termination without regularly checking an abort flag.

However, according to its original source, there are some issues with this code.

  • The exception will be raised only when executing python bytecode. If your thread calls a native/built-in blocking function, the exception will be raised only when execution returns to the python code.
    • There is also an issue if the built-in function internally calls PyErr_Clear(), which would effectively cancel your pending exception. You can try to raise it again.
  • Only exception types can be raised safely. Exception instances are likely to cause unexpected behavior, and are thus restricted.
  • I asked to expose this function in the built-in thread module, but since ctypes has become a standard library (as of 2.5), and this
    feature is not likely to be implementation-agnostic, it may be kept
    unexposed.

How to center canvas in html5

Give the canvas the following css style properties:

canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}

Edit

Since this answer is quite popular, let me add a little bit more details.

The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.

However, if you want to type less, you could use whatever css shorthand properties you wish, such as

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
}

Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
    height: 600px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

The canvas will center itself based on the first parent element that has position set to relative or absolute, or the body if none is found.

Another approach would be to use display: flex, that is available in IE11

Also, make sure you use a recent doctype such as xhtml or html 5.

You need to use a Theme.AppCompat theme (or descendant) with this activity

In your app/build.gradle add this dependency:

implementation "com.google.android.material:material:1.1.0-alpha03"

Update your styles.xml AppTheme's parent:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"/>

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

for ORA-01031: insufficient privileges. Some of the more common causes are:

  1. You tried to change an Oracle username or password without having the appropriate privileges.
  2. You tried to perform an UPDATE to a table, but you only have SELECT access to the table.
  3. You tried to start up an Oracle database using CONNECT INTERNAL.
  4. You tried to install an Oracle database without having the appropriate privileges to the operating-system.

The option(s) to resolve this Oracle error are:

  1. You can have the Oracle DBA grant you the appropriate privileges that you are missing.
  2. You can have the Oracle DBA execute the operation for you.
  3. If you are having trouble starting up Oracle, you may need to add the Oracle user to the dba group.

For ORA-00942: table or view does not exist. You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name.

If this error occurred because the table or view does not exist, you will need to create the table or view.

You can check to see if the table exists in Oracle by executing the following SQL statement:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'OBJECT_NAME';

For example, if you are looking for a suppliers table, you would execute:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

OPTION #2

If this error occurred because you do not have access to the table or view, you will need to have the owner of the table/view, or a DBA grant you the appropriate privileges to this object.

OPTION #3

If this error occurred because the table/view belongs to another schema and you didn't reference the table by the schema name, you will need to rewrite your SQL to include the schema name.

For example, you may have executed the following SQL statement:

select *
from suppliers;

But the suppliers table is not owned by you, but rather, it is owned by a schema called app, you could fix your SQL as follows:

select *
from app.suppliers;

If you do not know what schema the suppliers table/view belongs to, you can execute the following SQL to find out:

select owner
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

This will return the schema name who owns the suppliers table.

Shortcut to create properties in Visual Studio?

Type P + Tab + Tab.

Change the datatype, press TAB, change the property name, and press End + Enter.

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

How to generate and validate a software license key?

I strongly believe, that only public key cryptography based licensing system is the right approach here, because you don't have to include essential information required for license generation into your sourcecode.

In the past, I've used Treek's Licensing Library many times, because it fullfills this requirements and offers really good price. It uses the same license protection for end users and itself and noone cracked that until now. You can also find good tips on the website to avoid piracy and cracking.

Converting java.sql.Date to java.util.Date

In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html

Validate select box

Just add a class of required to the select

<select id="select" class="required">

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

java.lang.NoClassDefFoundError in junit

When using in Maven, update artifact junit:junit from e.g. 4.8.2 to 4.11.

Java String new line

To make the code portable to any system, I would use:

public static String newline = System.getProperty("line.separator");

This is important because different OSs use different notations for newline: Windows uses "\r\n", Classic Mac uses "\r", and Mac and Linux both use "\n".

Commentors - please correct me if I'm wrong on this...

android - how to convert int to string and place it in a EditText?

Use +, the string concatenation operator:

ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);

or use String.valueOf(int):

ed.setText(String.valueOf(x));

or use Integer.toString(int):

ed.setText(Integer.toString(x));

Fatal error: Call to undefined function mysql_connect()

For CPanel users, if you see this error and you already have PHP 5.x selected for the site, there might be a CPanel update that disabled mysql and mysqli PHP extensions.

To check and enable the extensions:

  1. Go to Select PHP Version in CPanel
  2. Make sure you have PHP 5.x selected
  3. Make sure mysql and mysqli PHP extensions are checked

How to use vagrant in a proxy environment?

If you actually do want your proxy configurations and plugin installations to be in your Vagrantfile, for example if you're making a Vagrantfile just for your corporate environment and can't have users editing environment variables, this was the answer for me:

ENV['http_proxy']  = 'http://proxyhost:proxyport'
ENV['https_proxy'] = 'http://proxyhost:proxyport'

# Plugin installation procedure from http://stackoverflow.com/a/28801317
required_plugins = %w(vagrant-proxyconf)

plugins_to_install = required_plugins.select { |plugin| not Vagrant.has_plugin? plugin }
if not plugins_to_install.empty?
  puts "Installing plugins: #{plugins_to_install.join(' ')}"
  if system "vagrant plugin install #{plugins_to_install.join(' ')}"
    exec "vagrant #{ARGV.join(' ')}"
  else
    abort "Installation of one or more plugins has failed. Aborting."
  end
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.proxy.http     = "#{ENV['http_proxy']}"
  config.proxy.https    = "#{ENV['https_proxy']}"
  config.proxy.no_proxy = "localhost,127.0.0.1"
  # and so on

(If you don't, just set them as environment variables like the other answers say and refer to them from env in config.proxy.http(s) directives.)

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

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

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

Does this give you a hint?

How to convert a Java String to an ASCII byte array?

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

Change tab bar tint color on iOS 7

You can set your tint color and font as setTitleTextattribute:

UIFont *font= (kUIScreenHeight>KipadHeight)?[UIFont boldSystemFontOfSize:32.0f]:[UIFont boldSystemFontOfSize:16.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,
                            tintColorLight, NSForegroundColorAttributeName, nil];
[[UINavigationBar appearance] setTitleTextAttributes:attributes];

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

How to add multiple font files for the same font?

To have font variation working correctly, I had to reverse the order of @font-face in CSS.

@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}   
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Bold.ttf");
    font-weight: bold;
}
 @font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono.ttf");
}

Efficiency of Java "Double Brace Initialization"?

While this syntax can be convenient, it also adds a lot of this$0 references as these become nested and it can be difficult to step debug into the initializers unless breakpoints are set on each one. For that reason, I only recommend using this for banal setters, especially set to constants, and places where anonymous subclasses don't matter (like no serialization involved).

Link to reload current page

There is no global way of doing this unfortunately with only HTML. You can try doing <a href="">test</a> however it only works in some browsers.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

Best ways to teach a beginner to program?

Ask your brother if there's something he'd like to make a program do or invent a project for him that you think would interest him.

Something where he can know what the output is supposed to be and point him to the materials(on-line or in print) pertinent to the project. If he's coming into python or programming 'cold' be patient as he works his way through understanding the basics such as syntax, errors, scoping and be prepared to step aside and let him run and make his own mistakes when you start to see the light bulb go on over his head.

How to "properly" create a custom object in JavaScript?

A Pattern That Serves Me Well
var Klass = function Klass() {
    var thus = this;
    var somePublicVariable = x
      , somePublicVariable2 = x
      ;
    var somePrivateVariable = x
      , somePrivateVariable2 = x
      ;

    var privateMethod = (function p() {...}).bind(this);

    function publicMethod() {...}

    // export precepts
    this.var1 = somePublicVariable;
    this.method = publicMethod;

    return this;
};

First, you may change your preference of adding methods to the instance instead of the constructor's prototype object. I almost always declare methods inside of the constructor because I use Constructor Hijacking very often for purposes regarding Inheritance & Decorators.

Here's how I decide where which declarations are writ:

  • Never declare a method directly on the context object (this)
  • Let var declarations take precedence over function declarations
  • Let primitives take precedence over objects ({} and [])
  • Let public declarations take precedence over private declarations
  • Prefer Function.prototype.bind over thus, self, vm, etc
  • Avoid declaring a Class within another Class, unless:
    • It should be obvious that the two are inseparable
    • The Inner class implements The Command Pattern
    • The Inner class implements The Singleton Pattern
    • The Inner class implements The State Pattern
    • The Inner Class implements another Design Pattern that warrants this
  • Always return this from within the Lexical Scope of the Closure Space.

Here's why these help:

Constructor Hijacking
var Super = function Super() {
    ...
    this.inherited = true;
    ...
};
var Klass = function Klass() {
    ...
    // export precepts
    Super.apply(this);  // extends this with property `inherited`
    ...
};
Model Design
var Model = function Model(options) {
    var options = options || {};

    this.id = options.id || this.id || -1;
    this.string = options.string || this.string || "";
    // ...

    return this;
};
var model = new Model({...});
var updated = Model.call(model, { string: 'modified' });
(model === updated === true);  // > true
Design Patterns
var Singleton = new (function Singleton() {
    var INSTANCE = null;

    return function Klass() {
        ...
        // export precepts
        ...

        if (!INSTANCE) INSTANCE = this;
        return INSTANCE;
    };
})();
var a = new Singleton();
var b = new Singleton();
(a === b === true);  // > true

As you can see, I really have no need for thus since I prefer Function.prototype.bind (or .call or .apply) over thus. In our Singleton class, we don't even name it thus because INSTANCE conveys more information. For Model, we return this so that we can invoke the Constructor using .call to return the instance we passed into it. Redundantly, we assigned it to the variable updated, though it is useful in other scenarios.

Alongside, I prefer constructing object-literals using the new keyword over {brackets}:

Preferred
var klass = new (function Klass(Base) {
    ...
    // export precepts
    Base.apply(this);  //
    this.override = x;
    ...
})(Super);
Not Preferred
var klass = Super.apply({
    override: x
});

As you can see, the latter has no ability to override its Superclass's "override" property.

If I do add methods to the Class's prototype object, I prefer an object literal -- with or without using the new keyword:

Preferred
Klass.prototype = new Super();
// OR
Klass.prototype = new (function Base() {
    ...
    // export precepts
    Base.apply(this);
    ...
})(Super);
// OR
Klass.prototype = Super.apply({...});
// OR
Klass.prototype = {
    method: function m() {...}
};
Not Preferred
Klass.prototype.method = function m() {...};

How do I calculate the date in JavaScript three months prior to today?

This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.

function monthAdd(date, month) {
    var temp = date;
    temp = new Date(date.getFullYear(), date.getMonth(), 1);
    temp.setMonth(temp.getMonth() + (month + 1));
    temp.setDate(temp.getDate() - 1); 

    if (date.getDate() < temp.getDate()) { 
        temp.setDate(date.getDate()); 
    }

    return temp;    
}

Adding an onclick function to go to url in JavaScript?

If you would like to open link in a new tab, you can:

$("a#thing_to_click").on('click',function(){
    window.open('https://yoururl.com', '_blank');
});

Cross compile Go on OSX?

With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No ./make.bash-ing or brew-ing required. The process is described here but for the TLDR-ers (like me) out there: you just set the GOOS and the GOARCH environment variables and run the go build.

For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:

env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app

You even learned the env trick, which let you set environment variables for that command only, completely free of charge.

How to import module when module name has a '-' dash or hyphen in it?

Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path

For example if your structure is like this:

foo-bar
+-- barfoo.py
+-- __init__.py

import sys
sys.path.append('foo-bar')

import barfoo

How to implement OnFragmentInteractionListener

Just an addendum:

OnFragmentInteractionListener handle communication between Activity and Fragment using an interface (OnFragmentInteractionListener) and is created by default by Android Studio, but if you dont need to communicate with your activity, you can just get ride of it.

The goal is that you can attach your fragment to multiple activities and still reuse the same communication approach (Every activity could have its own OnFragmentInteractionListener for each fragment).

But and if im sure my fragment will be attached to only one type of activity and i want to communicate with that activity?

Then, if you dont want to use OnFragmentInteractionListener because of its verbosity, you can access your activity methods using:

((MyActivityClass) getActivity()).someMethod()

How can the size of an input text box be defined in HTML?

The size attribute works, as well

<input size="25" type="text">

Java balanced expressions check {[()]}

import java.util.Stack;

        public class StackParenthesisImplementation {
            public static void main(String[] args) {
                String Parenthesis = "[({})]";
                char[] charParenthesis  = Parenthesis.toCharArray();
                boolean evalParanthesisValue = evalParanthesis(charParenthesis);
                if(evalParanthesisValue == true)
                    System.out.println("Brackets are good");
                else
                    System.out.println("Brackets are not good");
            }
            static boolean evalParanthesis(char[] brackets)
            {       
                boolean IsBracesOk = false;
                boolean PairCount = false;
                Stack<Character> stack = new Stack<Character>();
                for(char brace : brackets)
                {                       
                    if(brace == '(' || brace == '{' || brace == '['){
                        stack.push(brace);  
                        PairCount = false;
                    }
                    else if(!stack.isEmpty())
                    {
                        if(brace == ')' || brace == '}' || brace == ']')
                        {
                            char CharPop = stack.pop();
                            if((brace == ')' && CharPop == '('))
                            {
                                IsBracesOk = true; PairCount = true;
                            }
                            else if((brace == '}') && (CharPop == '{'))
                            {
                                IsBracesOk = true; PairCount = true;
                            }
                            else if((brace == ']') && (CharPop == '['))
                            {
                                IsBracesOk = true; PairCount = true;
                            }
                            else 
                            {
                                IsBracesOk = false;
                                PairCount = false;
                                break;
                            }
                        }   
                    }
                }   
                if(PairCount == false)
                return IsBracesOk = false;
                else
                    return IsBracesOk = true;
            }
        }