Programs & Examples On #Webview

Elements in graphical user interfaces that host HTML content. For Android, please look at the android-webview tag. For iOS, look under uiwebview or wkwebview.

Android WebView progress bar

here is the easiest way to add progress bar in android Web View.

Add a boolean field in your activity/fragment

private boolean isRedirected;

This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.

private void startWebView(WebView webView,String url) {

    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            isRedirected = true;
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            isRedirected = false;
        }

        public void onLoadResource (WebView view, String url) {
            if (!isRedirected) {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                    progressDialog.setMessage("Loading...");
                    progressDialog.show();
                }
            }

        }
        public void onPageFinished(WebView view, String url) {
            try{
                isRedirected=true;

                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }



            }catch(Exception exception){
                exception.printStackTrace();
            }
        }

    });

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
}

Here when start loading it will call onPageStarted. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected) in onLoadResource()

in onPageFinished() method before dismissing the Progress Dialog you can write your 10 second time delay code

That's it. Happy coding :)

Android Calling JavaScript functions in WebView

From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript("enable();", null);
    } else {
        webView.loadUrl("javascript:enable();");
    }

Android Webview - Completely Clear the Cache

I found an even elegant and simple solution to clearing cache

WebView obj;
obj.clearCache(true);

http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29

I have been trying to figure out the way to clear the cache, but all we could do from the above mentioned methods was remove the local files, but it never clean the RAM.

The API clearCache, frees up the RAM used by the webview and hence mandates that the webpage be loaded again.

How can I display a pdf document into a Webview?

Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.

Solution after API 21

Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap. I've never used it but is seems easy enough.

Solution for any api level

Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.

Use this code to download and open the PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}

}

For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.

Here is how you implement it: In your Manifest:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>

Finally create a file_paths.xml file in the resources foler

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>

Hope this helps =)

Android webview slow

The solution for us was the opposite. We disabled hardware acceleration on the WebView only (rather than on the entire app in the manifest) by using this code:

if (Build.VERSION.SDK_INT >= 11){
    webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

CSS3 animations are smoother now. We are using Android 4.0.

More info here: https://code.google.com/p/android/issues/detail?id=17352

Android Webview - Webpage should fit the device screen

I had video in html string, and width of web view was larger that screen width and this is working for me.

Add these lines to HTML string.

<head>
<meta name="viewport" content="width=device-width">
</head>

Result after adding above code to HTML string:

<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width">
</head>


</html>

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

Is there a better way to refresh WebView?

Override onFormResubmission in WebViewClient

@Override
public void onFormResubmission(WebView view, Message dontResend, Message resend){
   resend.sendToTarget();
}

How to enable zoom controls and pinch zoom in a WebView?

Inside OnCreate, add:

 webview.getSettings().setSupportZoom(true);
 webview.getSettings().setBuiltInZoomControls(true);
 webview.getSettings().setDisplayZoomControls(false);

Inside the html document, add:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2, user-scalable=yes">
</head>
</html>

Inside javascript, omit:

//event.preventDefault ? event.preventDefault() : (event.returnValue = false);

Android WebView style background-color:transparent ignored on android 2.2

This is how you do it:

First make your project base on 11, but in AndroidManifest set minSdkVersion to 8

android:hardwareAccelerated="false" is unnecessary, and it's incompatible with 8

wv.setBackgroundColor(0x00000000);
if (Build.VERSION.SDK_INT >= 11) wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

this.wv.setWebViewClient(new WebViewClient()
{
    @Override
    public void onPageFinished(WebView view, String url)
    {
        wv.setBackgroundColor(0x00000000);
        if (Build.VERSION.SDK_INT >= 11) wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }
});

For safety put this in your style:

BODY, HTML {background: transparent}

worked for me on 2.2 and 4

Android WebView not loading an HTTPS URL

I followed the answers above but still it seems not to be working for me below code did a trick for me when integrating payment gatways which are usually https requests :

public class MainActivity extends Activity {

    WebView webView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView1);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        String postData = "amount=1000&firstname=mtetno&[email protected]&phone=2145635784&productinfo=android&surl=success.php"
                + "&furl=failure.php&lastname=qwerty&curl=dsdsd.com&address1=dsdsds&address2=dfdfd&city=dsdsds&state=dfdfdfd&"
                + "country=fdfdf&zipcode=123456&udf1=dsdsds&udf2=fsdfdsf&udf3=jhghjg&udf4=fdfd&udf5=fdfdf&pg=dfdf";
        webView.postUrl(
                "http://host/payment.php",
                EncodingUtils.getBytes(postData, "BASE64"));

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                SslError error) {
            handler.proceed();
        }
    }
}

Above code is doing a post request in webview and redirecting to payment gateway.

Setting settings.setDomStorageEnabled(true); did a trick for me Hope this helps .

Rendering HTML in a WebView with custom CSS

It's as simple as is:

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");

And your some.html needs to contain something like:

<link rel="stylesheet" type="text/css" href="style.css" />

Android Webview gives net::ERR_CACHE_MISS message

Use

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }

It should solve the error.

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

Swift Open Link in Safari

Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

How to force keyboard with numbers in mobile website in Android

inputmode according to WHATWG spec is the the default method.

For iOS devices adding pattern could also help.

For backward compatibility use type as well since Chrome use these as of version 66.

<input
  inputmode="numeric"
  pattern="[0-9]*"
  type="number"
/>

Android WebView Cookie Problem

My working code

public View onCreateView(...){
    mWebView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

        ...
        ...
        ...

    CookieSyncManager.createInstance(mWebView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    //cookieManager.removeSessionCookie(); // remove
    cookieManager.removeAllCookie(); //remove
    // Recommended "hack" with a delay between the removal and the installation of "Cookies"
    SystemClock.sleep(1000);

    cookieManager.setCookie("https://my.app.site.com/", "cookiename=" + value + "; path=/registration" + "; secure"); // ;
    CookieSyncManager.getInstance().sync();

    mWebView.loadUrl(sp.getString("url", "") + end_url);

    return view;
}

To debug the query, "cookieManager.setCookie (....);" I recommend you to look through the contents of the database webviewCookiesChromium.db (stored in "/data/data/my.app.webview/database") There You can see the correct settings.

Disabling "cookieManager.removeSessionCookie();" and/or "cookieManager.removeAllCookie();"

//cookieManager.removeSessionCookie();
// and/or
//cookieManager.removeAllCookie();"

Compare the set value with those that are set by the browser. Adjust the request for the installation of the cookies before until "flags" browser is not installed will fit with what You decide. I found that a query can be "flags":

// You may want to add the secure flag for https:
+ "; secure"
// In case you wish to convert session cookies to have an expiration:
+ "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// These flags I found in the database:
+ "; path=/registration"
+ "; domain=my.app.site.com"

WebView and HTML5 <video>

On honeycomb use hardwareaccelerated=true and pluginstate.on_demand seems to work

Download file inside WebView

Try this out. After going through a lot of posts and forums, I found this.

mWebView.setDownloadListener(new DownloadListener() {       

    @Override
    public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();

        }
    });

Do not forget to give this permission! This is very important! Add this in your Manifest file(The AndroidManifest.xml file)

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <!-- for your file, say a pdf to work -->

Hope this helps. Cheers :)

How to set the initial zoom/width for a webview

I'm working with loading images for this answer and I want them to be scaled to the device's width. I find that, for older phones with versions less than API 19 (KitKat), the behavior for Brian's answer isn't quite as I like it. It puts a lot of whitespace around some images on older phones, but works on my newer one. Here is my alternative, with help from this answer: Can Android's WebView automatically resize huge images? The layout algorithm SINGLE_COLUMN is deprecated, but it works and I feel like it is appropriate for working with older webviews.

WebSettings settings = webView.getSettings();

// Image set to width of device. (Must be done differently for API < 19 (kitkat))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    if (!settings.getLayoutAlgorithm().equals(WebSettings.LayoutAlgorithm.SINGLE_COLUMN))
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
    if (!settings.getLoadWithOverviewMode()) settings.setLoadWithOverviewMode(true);
    if (!settings.getUseWideViewPort()) settings.setUseWideViewPort(true);
}

File Upload in WebView

I'm new to Andriod and struggled with this also. According to Google Reference Guide WebView.

By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored. If your goal is only to display some HTML as a part of your UI, this is probably fine; the user won't need to interact with the web page beyond reading it, and the web page won't need to interact with the user. If you actually want a full-blown web browser, then you probably want to invoke the Browser application with a URL Intent rather than show it with a WebView.

Example code I executed in MainActvity.java.

 Uri uri = Uri.parse("https://www.example.com");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);

Excuted

package example.com.myapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;
import android.net.Uri;

public class MainActivity extends AppCompatActivity {

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

        Uri uri = Uri.parse("http://www.example.com/");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        getSupportActionBar().hide();
    }}

How to pass html string to webview on android

To load your data in WebView. Call loadData() method of WebView

webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

Android. WebView and loadData

As I understand it, loadData() simply generates a data: URL with the data provide it.

Read the javadocs for loadData():

If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):

String data = ...;  // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");

how to display progress while loading a url to webview in android?

You need to set an own WebViewClient for your WebView by extending the WebViewClient class.

You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).

More guidance for this topic can be found in Google's WebView tutorial

how to get html content from a webview?

above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code

AssetManager mgr = mContext.getAssets();
             try {
InputStream in = null;              
if(condition)//you have a local html saved in assets
                            {
                            in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
                           }
                            else if(condition)//you have an url
                            {
                            URL feedURL = new URL(sURL);
                  in = feedURL.openConnection().getInputStream();}

                            // here you will get your html
                 String sHTML = streamToString(in);
                 in.close();

                 //display this html in the browser or web view              


             } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             }
        public static String streamToString(InputStream in) throws IOException {
            if(in == null) {
                return "";
            }

            Writer writer = new StringWriter();
            char[] buffer = new char[1024];

            try {
                Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }

            } finally {

            }

            return writer.toString();
        }

How to check if a file exists in Documents folder?

NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath =  [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);

//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
    NSLog("File not exist");
} else {
    NSLog("File exist");
}

//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
    cell.photoImageView.image = image;//Display image
}

How do I scroll the UIScrollView when the keyboard appears?

The following is my solutions which works ( 5 steps )

Step1: Add an observer to catch which UITEXTFIELD or UITEXTVIEW ShoudBeginEditing ( where object is inited or ViewDidLoad.

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(updateActiveField:)
                                             name:@"UPDATE_ACTIVE_FIELD" object:nil];

Step2: Post a notification when ..ShouldBeginEditing with OBJECT of UITEXTFIELD or UITEXTVIEW

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {

[[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATE_ACTIVE_FIELD" 
                                                    object:textView];
return YES;
}

Step3: The method that (Step1 calles ) assigns the current UITEXTFIELD or UITEXTVIEW

-(void) updateActiveField: (id) sender {
    activeField = [sender object];
}

Step4: Add Keyboard observer UIKeyboardWillShowNotification ( same place as Step1 )

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

and method:

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

    _currentEdgeInsets = self.layoutPanel.contentInset; // store current insets to restore them later
    self.layoutPanel.contentInset = contentInsets;
    self.layoutPanel.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    CGRect aRect =  self.view.frame;
    aRect.size.height -= kbSize.height;

    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    CGPoint p = [activeField convertPoint:activeField.bounds.origin toView:window];

    if (!CGRectContainsPoint(aRect, p) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y +kbSize.height);
       [self.layoutPanel setContentOffset:scrollPoint animated:YES];
       self.layoutPanel.scrollEnabled = NO;
    }
}

Step5: Add Keyboard observer UIKeyboardWillHideNotification ( same place as step 1 )

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];

and method:

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    self.layoutPanel.contentInset = _currentEdgeInsets;
    self.layoutPanel.scrollIndicatorInsets = _currentEdgeInsets;
    self.layoutPanel.scrollEnabled = YES;
}

Remember to remove observers!

MSSQL Regular expression

Disclaimer: The original question was about MySQL. The SQL Server answer is below.

MySQL

In MySQL, the regex syntax is the following:

SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$') 

Use the REGEXP clause instead of LIKE. The latter is for pattern matching using % and _ wildcards.


SQL Server

Since you made a typo, and you're using SQL Server (not MySQL), you'll have to create a user-defined CLR function to expose regex functionality.

Take a look at this article for more details.

Automate scp file transfer using a shell script

You can do it with ssh public/private keys only. Or use putty in which you can set the password. scp doesn't support giving password in command line.

You can find the instructions for public/private keys here: http://www.softpanorama.org/Net/Application_layer/SSH/scp.shtml

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

From the looks of things you haven't passed enough data to Spring Boot to configure the datasource

Create/In your existing application.properties add the following

spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=

making sure you append a value for each of properties.

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

SQL Server - Create a copy of a database table and place it in the same database?

This is another option:

select top 0 * into <new_table> from <original_table>

How to use unicode characters in Windows command line?

As I haven't seen any full answers for Python 2.7, I'll outline the two important steps and an optional step that is quite useful.

  1. You need a font with Unicode support. Windows comes with Lucida Console which may be selected by right-clicking the title bar of command prompt and clicking the Defaults option. This also gives access to colours. Note that you can also change settings for command windows invoked in certain ways (e.g, open here, Visual Studio) by choosing Properties instead.
  2. You need to set the code page to cp65001, which appears to be Microsoft's attempt to offer UTF-7 and UTF-8 support to command prompt. Do this by running chcp 65001 in command prompt. Once set, it remains this way until the window is closed. You'll need to redo this every time you launch cmd.exe.

For a more permanent solution, refer to this answer on Super User. In short, create a REG_SZ (String) entry using regedit at HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor and name it AutoRun. Change the value of it to chcp 65001. If you don't want to see the output message from the command, use @chcp 65001>nul instead.

Some programs have trouble interacting with this encoding, MinGW being a notable one that fails while compiling with a nonsensical error message. Nonetheless, this works very well and doesn't cause bugs with the majority of programs.

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

You may also get this warning for MS Fakes assemblies which isn't as easy to resolve since the f.csproj is build on command. Luckily the Fakes xml allows you to add it in there.

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

Detecting a mobile browser


// Function returns true if current device is phone
function isMobile() {

    // regex from http://detectmobilebrowsers.com/mobile
    return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(navigator.userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent)
}

console.log({
    isMobile: isMobile()
});

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

How to vertically center <div> inside the parent element with CSS?

The best approach in modern browsers is to use flexbox:

#Login {
    display: flex;
    align-items: center;
}

Some browsers will need vendor prefixes. For older browsers without flexbox support (e.g. IE 9 and lower), you'll need to implement a fallback solution using one of the older methods.

Recommended Reading

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

How to use pip with Python 3.x alongside Python 2.x

The approach you should take is to install pip for Python 3.2.

You do this in the following way:

$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py

Then, you can install things for Python 3.2 with pip-3.2, and install things for Python 2-7 with pip-2.7. The pip command will end up pointing to one of these, but I'm not sure which, so you will have to check.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I got a sign_and_send_pubkey: signing failed: agent refused operation error as well. But in my case the problem was a wrong pinentry path.

In my ${HOME}/.gnupg/gpg-agent.conf the pinentry-program property was pointing to an old pinentry path. Correcting the path there and restarting the gpg-agent fixed it for me.

I discovered it by following the logs with journalctl -f. There where log lines like the following containing the wrong path:

Jul 02 08:37:50 my-host gpg-agent[12677]: ssh sign request failed: No pinentry <GPG Agent>
Jul 02 08:37:57 my-host gpg-agent[12677]: can't connect to the PIN entry module '/usr/local/bin/pinentry': IPC connect call failed

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

The issue is in your registration app. It seems django-registration calls get_user_module() in models.py at a module level (when models are still being loaded by the application registration process). This will no longer work:

try:
    from django.contrib.auth import get_user_model
    User = get_user_model()
except ImportError:
    from django.contrib.auth.models import User    

I'd change this models file to only call get_user_model() inside methods (and not at module level) and in FKs use something like:

user = ForeignKey(settings.AUTH_USER_MODEL)

BTW, the call to django.setup() shouldn't be required in your manage.py file, it's called for you in execute_from_command_line. (source)

Java: how to initialize String[]?

String[] errorSoon = new String[n];

With n being how many strings it needs to hold.

You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

How do I add button on each row in datatable?

well, i just added button in data. For Example, i should code like this:

$(target).DataTable().row.add(message).draw()

And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!

Component is not part of any NgModule or the module has not been imported into your module

If your are not using lazy loading, you need to import your HomeComponent in app.module and mention it under declarations. Also, don't forget to remove from imports

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http'

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    // add HomeComponent here
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    HomeModule  // remove this

  ],
  providers: [MRDBGlobalConstants],
  bootstrap: [AppComponent]
})
export class AppModule { }

How do I deal with certificates using cURL while trying to access an HTTPS url?

If anyone is still having trouble, try this, it worked for me. Delete the files in your /etc/ssl/certs/ directory then reinstall ca-certificates:

sudo apt install ca-certificates --reinstall

Did this when I tried installing Linuxbrew.

Sequelize OR condition object

Seems there is another format now

where: {
    LastName: "Doe",
    $or: [
        {
            FirstName: 
            {
                $eq: "John"
            }
        }, 
        {
            FirstName: 
            {
                $eq: "Jane"
            }
        }, 
        {
            Age: 
            {
                $gt: 18
            }
        }
    ]
}

Will generate

WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)

See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

How do you change text to bold in Android?

editText.setTypeface(Typeface.createFromAsset(getAssets(), ttfFilePath));
etitText.setTypeface(et.getTypeface(), Typeface.BOLD);

will set both typface as well as style to Bold.

How to use wget in php?

I understand you want to open a xml file using php. That's called to parse a xml file. The best reference is here.

http://php.net/manual/de/function.xml-parse.php

Node.js project naming conventions for files & folders

There are no conventions. There are some logical structure.

The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:

var isHidden = require('./lib/isHidden');

But sadly I created a file with full of lowercase: lib/ishidden.js. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:

Error: Cannot find module './lib/isHidden'

Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.

So use underscore (_) or dash (-) separator if you need.

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

Update a column in MySQL

This is what I did for bulk update:

UPDATE tableName SET isDeleted = 1 where columnName in ('430903GW4j683537882','430903GW4j667075431','430903GW4j658444015')

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

pyplot scatter plot marker size

Because other answers here claim that s denotes the area of the marker, I'm adding this answer to clearify that this is not necessarily the case.

Size in points^2

The argument s in plt.scatter denotes the markersize**2. As the documentation says

s : scalar or array_like, shape (n, ), optional
size in points^2. Default is rcParams['lines.markersize'] ** 2.

This can be taken literally. In order to obtain a marker which is x points large, you need to square that number and give it to the s argument.

So the relationship between the markersize of a line plot and the scatter size argument is the square. In order to produce a scatter marker of the same size as a plot marker of size 10 points you would hence call scatter( .., s=100).

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot([0],[0], marker="o",  markersize=10)
ax.plot([0.07,0.93],[0,0],    linewidth=10)
ax.scatter([1],[0],           s=100)

ax.plot([0],[1], marker="o",  markersize=22)
ax.plot([0.14,0.86],[1,1],    linewidth=22)
ax.scatter([1],[1],           s=22**2)

plt.show()

Connection to "area"

So why do other answers and even the documentation speak about "area" when it comes to the s parameter?

Of course the units of points**2 are area units.

  • For the special case of a square marker, marker="s", the area of the marker is indeed directly the value of the s parameter.
  • For a circle, the area of the circle is area = pi/4*s.
  • For other markers there may not even be any obvious relation to the area of the marker.

enter image description here

In all cases however the area of the marker is proportional to the s parameter. This is the motivation to call it "area" even though in most cases it isn't really.

Specifying the size of the scatter markers in terms of some quantity which is proportional to the area of the marker makes in thus far sense as it is the area of the marker that is perceived when comparing different patches rather than its side length or diameter. I.e. doubling the underlying quantity should double the area of the marker.

enter image description here

What are points?

So far the answer to what the size of a scatter marker means is given in units of points. Points are often used in typography, where fonts are specified in points. Also linewidths is often specified in points. The standard size of points in matplotlib is 72 points per inch (ppi) - 1 point is hence 1/72 inches.

It might be useful to be able to specify sizes in pixels instead of points. If the figure dpi is 72 as well, one point is one pixel. If the figure dpi is different (matplotlib default is fig.dpi=100),

1 point == fig.dpi/72. pixels

While the scatter marker's size in points would hence look different for different figure dpi, one could produce a 10 by 10 pixels^2 marker, which would always have the same number of pixels covered:

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

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

If you are interested in a scatter in data units, check this answer.

what exactly is device pixel ratio?

Short answer

The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.

  • Physical resolution: 960 x 640
  • Logical resolution: 480 x 320

The formula is:

linres_p/linres_l

Where:

linres_p is the physical linear resolution

and:

linres_l is the logical linear resolution

Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.

Discussion

The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of 0.0213° viewing angle, which is approximately 1/96 of an inch at arm's length. Source: CSS Absolute Lengths

This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.

If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover or explicitly set the background-size to percentage values.

Example

#element { background-image: url('lores.png'); }

@media only screen and (min-device-pixel-ratio: 2) {
    #element { background-image: url('hires.png'); }
}

@media only screen and (min-device-pixel-ratio: 3) {
    #element { background-image: url('superhires.png'); }
}

This way, each device type only loads the correct image resource. Also keep in mind that the px unit in CSS always operates on logical pixels.

A case for vector graphics

As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).

If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

import ReactDOM from 'react-dom';
import {
    HashRouter,
    Route
} from 'react-router-dom';


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

I had a similar problem, trying to capture a 'shift+click' but since I was using a third party control with a callback rather than the standard click handler, I didn't have access to the event object and its associated e.shiftKey.

I ended up handling the mouse down event to record the shift-ness and then using it later in my callback.

    var shiftHeld = false;
    $('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

Posted just in case someone else ends up here searching for a solution to this problem.

How to display a confirmation dialog when clicking an <a> link?

Most browsers don't display the custom message passed to confirm().

With this method, you can show a popup with a custom message if your user changed the value of any <input> field.

You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  let unsaved = false;_x000D_
  // detect changes in all input fields and set the 'unsaved' flag_x000D_
  $(":input").change(() => unsaved = true);_x000D_
  // trigger popup on click_x000D_
  $('.dangerous-link').click(function() {_x000D_
    if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {_x000D_
      return; // user didn't confirm_x000D_
    }_x000D_
    // either there are no unsaved changes or the user confirmed_x000D_
    window.location.href = $(this).data('destination');_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="text" placeholder="Nuclear code here" />_x000D_
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">_x000D_
    Launch nuke!_x000D_
</a>
_x000D_
_x000D_
_x000D_

Try changing the input value in the example to get a preview of how it works.

How to get current route

Inject Location to your component and read location.path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location. You need to add import: [RouterModule] to the module.

Update

In the V3 (RC.3) router you can inject ActivatedRoute and access more details using its snapshot property.

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

See also Angular 2 router event listener

UILabel is not auto-shrinking text to fit label size

minimumFontSize is deprecated in iOS 6.

So use minimumScaleFactor instead of minmimumFontSize.

lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5

Swift 5

lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5

Find if value in column A contains value from column B?

You can use VLOOKUP, but this requires a wrapper function to return True or False. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.

Fill down this formula in column K next to the existing values in column I (from I1 to I2691):

=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0

You can also use MATCH:

=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))

Importing Maven project into Eclipse

Using mvn eclipse:eclipse will just generate general eclipse configuration files, this is fine if you have a simple project; but in case of a web-based project such as servlet/jsp you need to manually add Java EE features to eclipse (WTP).

To make the project runnable via eclipse servers portion, Configure Apache for Eclipse: Download and unzip Apache Tomcat somewhere. In Eclipse Windows -> Preferences -> Servers -> Runtime Environments add (Create local server), select your version of Tomcat, Next, Browse to the directory of the Tomcat you unzipped, click Finish.

Window -> Show View -> Servers Add the project to the server list

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

What regular expression will match valid international phone numbers?

For iOS SWIFT I found this helpful,

let phoneRegEx = "^((\\+)|(00)|(\\*)|())[0-9]{3,14}((\\#)|())$"

What is the difference between a static and const variable?

static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the same name and no name conflicts.

const is just constant, meaning can't be modified.

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

How to append rows to an R data frame

A more generic solution for might be the following.

    extendDf <- function (df, n) {
    withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
    nr          <- nrow (df)
    colNames    <- names(df)
    for (c in 1:length(colNames)) {
        if (is.factor(df[,c])) {
            col         <- vector (mode='character', length = nr+n) 
            col[1:nr]   <- as.character(df[,c])
            col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
            col         <- as.factor(col)
        } else {
            col         <- vector (mode=mode(df[1,c]), length = nr+n)
            class(col)  <- class (df[1,c])
            col[1:nr]   <- df[,c] 
        }
        if (c==1) {
            newDf       <- data.frame (col ,stringsAsFactors=withFactors)
        } else {
            newDf[,c]   <- col 
        }
    }
    names(newDf) <- colNames
    newDf
}

The function extendDf() extends a data frame with n rows.

As an example:

aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
#      l i n c                   t
# 1  TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00

system.time (eDf <- extendDf (aDf, 100000))
#    user  system elapsed 
#   0.009   0.002   0.010
system.time (eDf <- extendDf (eDf, 100000))
#    user  system elapsed 
#   0.068   0.002   0.070

Remove portion of a string after a certain character

One method would be:

$str = 'Posted On April 6th By Some Dude';
echo strtok($str, 'By'); // Posted On April 6th

Java: Retrieving an element from a HashSet

If you know the order of elements in your Set, you can retrieve them by converting the Set to an Array. Something like this:

Set mySet = MyStorageObject.getMyStringSet();
Object[] myArr = mySet.toArray();
String value1 = myArr[0].toString();
String value2 = myArr[1].toString();

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Doing below (Swift) solves the problem, but this works when you don't need a header.

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.min
}

If you do, you'll have to abandon the very first section and use other for content.

UITableViewDataSource implementation:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return <number_of_data_sections>+1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // the first section we don't use for data
    if section == 0 {
        return 0
    }

    // starting from 1, there are sections we use
    if section == 1 { 
        let dataSection = section - 1

        // use dataSection for your content (useful, when data provided by fetched result controller). For example:
       if let sectionInfo = myFRC!.sections![dataSection] as? NSFetchedResultsSectionInfo {
            return sectionInfo.numberOfObjects
        }
    }

    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let dataIndexPath = NSIndexPath(forRow: indexPath.row, inSection: (indexPath.section - 1) )
    // return cell using transformed dataIndexPath
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 1 {
        // return your header height
    }
    return CGFloat.min
}


func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 1 {
        // return your header view
    }
    return nil
}

func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    // in my case, even when 1st section header was of zero heigh, I saw the space, an that was a footer. I did not need footer at all, so always gave zero height
    return CGFloat.min
}

And that's it. Model does not know anything about the change, because we transforms the section number upon accessing the data.

How to restore SQL Server 2014 backup in SQL Server 2008

Not really as far as I know but here are couple things you can try.

Third party tools: Create empty database on 2008 instance and use third party tools such as ApexSQL Diff and Data Diff to synchronize schema and tables.

Just use these (or any other on the market such as Red Gate, Idera, Dev Art, there are many similar) in trial mode to get the job done.

Generate scripts: Go to Tasks -> Generate Scripts, select option to script the data too and execute it on 2008 instance. Works just fine but note that script order is something you must be careful about. By default scripts are not ordered to take dependencies into account.

Insert line after first match using sed

Sed command that works on MacOS (at least, OS 10) and Unix alike (ie. doesn't require gnu sed like Gilles' (currently accepted) one does):

sed -e '/CLIENTSCRIPT="foo"/a\'$'\n''CLIENTSCRIPT2="hello"' file

This works in bash and maybe other shells too that know the $'\n' evaluation quote style. Everything can be on one line and work in older/POSIX sed commands. If there might be multiple lines matching the CLIENTSCRIPT="foo" (or your equivalent) and you wish to only add the extra line the first time, you can rework it as follows:

sed -e '/^ *CLIENTSCRIPT="foo"/b ins' -e b -e ':ins' -e 'a\'$'\n''CLIENTSCRIPT2="hello"' -e ': done' -e 'n;b done' file

(this creates a loop after the line insertion code that just cycles through the rest of the file, never getting back to the first sed command again).

You might notice I added a '^ *' to the matching pattern in case that line shows up in a comment, say, or is indented. Its not 100% perfect but covers some other situations likely to be common. Adjust as required...

These two solutions also get round the problem (for the generic solution to adding a line) that if your new inserted line contains unescaped backslashes or ampersands they will be interpreted by sed and likely not come out the same, just like the \n is - eg. \0 would be the first line matched. Especially handy if you're adding a line that comes from a variable where you'd otherwise have to escape everything first using ${var//} before, or another sed statement etc.

This solution is a little less messy in scripts (that quoting and \n is not easy to read though), when you don't want to put the replacement text for the a command at the start of a line if say, in a function with indented lines. I've taken advantage that $'\n' is evaluated to a newline by the shell, its not in regular '\n' single-quoted values.

Its getting long enough though that I think perl/even awk might win due to being more readable.

Changing SqlConnection timeout

You can set the connection timeout to the connection level and command level.

Add "Connection Timeout=10" to the connection string. Now connection timeout is 10 seconds.

var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;Connection Timeout=10";
using (var con = new SqlConnection(connectionString))
{

}

Set the of CommandTimeout property to SqlCommand

var connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword";
using (var con = new SqlConnection(connectionString))
{

    using (var cmd =new SqlCommand())
    {
        cmd.CommandTimeout = 10;
    }

}

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

How to send SMS in Java

You Can Do this With A GSM Modem and Java Communications Api [Tried And Tested]

  1. First You Need TO Set Java Comm Api

    This Article Describes In Detail How to Set Up Communication Api

  2. Next You Need A GSM Modem (preferably sim900 Module )

  3. Java JDK latest version preferable

  4. AT Command Guide

    Code

    package sample;

        import java.io.*;
        import java.util.*;
    
        import gnu.io.*;
    
        import java.io.*;
    
    
        import org.apache.log4j.chainsaw.Main;
    
        import sun.audio.*;
    
        public class GSMConnect implements SerialPortEventListener, 
         CommPortOwnershipListener {
    
         private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
         private String messageString = "";
         private CommPortIdentifier portId = null;
         private Enumeration portList;
         private InputStream inputStream = null;
         private OutputStream outputStream = null;
         private SerialPort serialPort;
         String readBufferTrial = "";
         /** Creates a new instance of GSMConnect */
         public GSMConnect(String comm) {
    
           this.comPort = comm;
    
         }
    
         public boolean init() {
           portList = CommPortIdentifier.getPortIdentifiers();
           while (portList.hasMoreElements()) {
             portId = (CommPortIdentifier) portList.nextElement();
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
               if (portId.getName().equals(comPort)) {
                   System.out.println("Got PortName");
                 return true;
               }
             }
           }
           return false;
         }
    
         public void checkStatus() {
           send("AT+CREG?\r\n");
         }
    
    
    
         public void send(String cmd) {
           try {
             outputStream.write(cmd.getBytes());
           } catch (IOException e) {
             e.printStackTrace();
           }
         }
    
         public void sendMessage(String phoneNumber, String message) {
               char quotes ='"';
           send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
           try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            //   send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
           send(message + '\032');
           System.out.println("Message Sent");
         }
    
         public void hangup() {
           send("ATH\r\n");
         }
    
         public void connect() throws NullPointerException {
           if (portId != null) {
             try {
               portId.addPortOwnershipListener(this);
    
               serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
               serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
             } catch (PortInUseException | UnsupportedCommOperationException e) {
               e.printStackTrace();
             }
    
             try {
               inputStream = serialPort.getInputStream();
               outputStream = serialPort.getOutputStream();
    
             } catch (IOException e) {
               e.printStackTrace();
             }
    
             try {
               /** These are the events we want to know about*/
               serialPort.addEventListener(this);
               serialPort.notifyOnDataAvailable(true);
               serialPort.notifyOnRingIndicator(true);
             } catch (TooManyListenersException e) {
               e.printStackTrace();
             }
    
        //Register to home network of sim card
    
             send("ATZ\r\n");
    
           } else {
             throw new NullPointerException("COM Port not found!!");
           }
         }
    
         public void serialEvent(SerialPortEvent serialPortEvent) {
           switch (serialPortEvent.getEventType()) {
             case SerialPortEvent.BI:
             case SerialPortEvent.OE:
             case SerialPortEvent.FE:
             case SerialPortEvent.PE:
             case SerialPortEvent.CD:
             case SerialPortEvent.CTS:
             case SerialPortEvent.DSR:
             case SerialPortEvent.RI:     
             case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
             case SerialPortEvent.DATA_AVAILABLE:
    
               byte[] readBuffer = new byte[2048];
               try {
                 while (inputStream.available() > 0) 
                 {
                   int numBytes = inputStream.read(readBuffer);
    
                   System.out.print(numBytes);
                   if((readBuffer.toString()).contains("RING")){
                   System.out.println("Enter Inside if RING Loop");    
    
    
    
                   }
                 }
    
                 System.out.print(new String(readBuffer));
               } catch (IOException e) {
               }
               break;
           }
         }
         public void outCommand(){
             System.out.print(readBufferTrial);
         }
         public void ownershipChange(int type) {
           switch (type) {
             case CommPortOwnershipListener.PORT_UNOWNED:
               System.out.println(portId.getName() + ": PORT_UNOWNED");
               break;
             case CommPortOwnershipListener.PORT_OWNED:
               System.out.println(portId.getName() + ": PORT_OWNED");
               break;
             case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
               System.out.println(portId.getName() + ": PORT_INUSED");
               break;
           }
    
         }
         public void closePort(){
    
            serialPort.close(); 
         }
    
         public static void main(String args[]) {
           GSMConnect gsm = new GSMConnect(comPort);
           if (gsm.init()) {
             try {
                 System.out.println("Initialization Success");
               gsm.connect();
               Thread.sleep(5000);
               gsm.checkStatus();
               Thread.sleep(5000);
    
               gsm.sendMessage("+91XXXXXXXX", "Trial Success");
    
               Thread.sleep(1000);
    
               gsm.hangup();
               Thread.sleep(1000);
               gsm.closePort();
               gsm.outCommand();
               System.exit(1);
    
    
             } catch (Exception e) {
               e.printStackTrace();
             }
           } else {
             System.out.println("Can't init this card");
           }
         }
    
    
            }
    

Multiple argument IF statement - T-SQL

You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)

DECLARE @StartDate AS DATETIME

DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        print 'yoyoyo'
    END

IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2) 
    BEGIN
        print 'Oh hey there'
    END

Build Eclipse Java Project from Command Line

After 27 years, I too, am uncomfortable developing in an IDE. I tried these suggestions (above) - and probably just didn't follow everything right -- so I did a web-search and found what worked for me at 'http://incise.org/android-development-on-the-command-line.html'.

The answer seemed to be a combination of all the answers above (please tell me if I'm wrong and accept my apologies if so).

As mentioned above, eclipse/adt does not create the necessary ant files. In order to compile without eclipse IDE (and without creating ant scripts):

1) Generate build.xml in your top level directory:

android list targets  (to get target id used below)

android update project --target target_id --name project_name  --path top_level_directory

   ** my sample project had a target_id of 1 and a project name of 't1', and 
   I am building from the top level directory of project
   my command line looks like android update project --target 1 --name t1 --path `pwd`

2) Next I compile the project. I was a little confused by the request to not use 'ant'. Hopefully -- requester meant that he didn't want to write any ant scripts. I say this because the next step is to compile the application using ant

 ant target

    this confused me a little bit, because i thought they were talking about the
    android device, but they're not.  It's the mode  (debug/release)
    my command line looks like  ant debug

3) To install the apk onto the device I had to use ant again:

 ant target install

    ** my command line looked like  ant debug install

4) To run the project on my android phone I use adb.

 adb shell 'am start -n your.project.name/.activity'

    ** Again there was some confusion as to what exactly I had to use for project 
    My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'
    I also found that if you type 'adb shell' you get put to a cli shell interface
    where you can do just about anything from there.

3A) A side note: To view the log from device use:

 adb logcat

3B) A second side note: The link mentioned above also includes instructions for building the entire project from the command.

Hopefully, this will help with the question. I know I was really happy to find anything about this topic here.

MySql difference between two timestamps in days?

CREATE TABLE t (d1 timestamp, d2 timestamp);

INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 05:00:00');
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-11 00:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-04-01 13:00:00');

SELECT d2, d1, DATEDIFF(d2, d1) AS diff FROM t;

+---------------------+---------------------+------+
| d2                  | d1                  | diff |
+---------------------+---------------------+------+
| 2010-03-30 05:00:00 | 2010-03-11 12:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-11 12:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-11 00:00:00 |   19 |
| 2010-03-30 13:00:00 | 2010-03-10 12:00:00 |   20 |
| 2010-04-01 13:00:00 | 2010-03-10 12:00:00 |   22 |
+---------------------+---------------------+------+
5 rows in set (0.00 sec)

How can I make window.showmodaldialog work in chrome 37?

Create a cross browser ModalDialog

function _showModalDialog(url, width, height, closeCallback) {
    var modalDiv,
        dialogPrefix = window.showModalDialog ? 'dialog' : '',
        unit = 'px',
        maximized = width === true || height === true,
        w = width || 600,
        h = height || 500,
        border = 5,
        taskbar = 40, // windows taskbar
        header = 20,
        x,
        y;

    if (maximized) {
        x = 0;
        y = 0;
        w = screen.width;
        h = screen.height;
    } else {
        x = window.screenX + (screen.width / 2) - (w / 2) - (border * 2);
        y = window.screenY + (screen.height / 2) - (h / 2) - taskbar - border;
    }

    var features = [
            'toolbar=no',
            'location=no',
            'directories=no',
            'status=no',
            'menubar=no',
            'scrollbars=no',
            'resizable=no',
            'copyhistory=no',
            'center=yes',
            dialogPrefix + 'width=' + w + unit,
            dialogPrefix + 'height=' + h + unit,
            dialogPrefix + 'top=' + y + unit,
            dialogPrefix + 'left=' + x + unit
        ],
        showModal = function (context) {
            if (context) {
                modalDiv = context.document.createElement('div');
                modalDiv.style.cssText = 'top:0;right:0;bottom:0;left:0;position:absolute;z-index:50000;';
                modalDiv.onclick = function () {
                    if (context.focus) {
                        context.focus();
                    }
                    return false;
                }
                window.top.document.body.appendChild(modalDiv);
            }
        },
        removeModal = function () {
            if (modalDiv) {
                modalDiv.onclick = null;
                modalDiv.parentNode.removeChild(modalDiv);
                modalDiv = null;
            }
        };

    // IE
    if (window.showModalDialog) {
        window.showModalDialog(url, null, features.join(';') + ';');

        if (closeCallback) {
            closeCallback();
        }
    // Other browsers
    } else {
        var win = window.open(url, '', features.join(','));
        if (maximized) {
            win.moveTo(0, 0);
        }

        // When charging the window.
        var onLoadFn = function () {
                showModal(this);
            },
            // When you close the window.
            unLoadFn = function () {
                window.clearInterval(interval);
                if (closeCallback) {
                    closeCallback();
                }
                removeModal();
            },
            // When you refresh the context that caught the window.
            beforeUnloadAndCloseFn = function () {
                try {
                    unLoadFn();
                }
                finally {
                    win.close();
                }
            };

        if (win) {
            // Create a task to check if the window was closed.
            var interval = window.setInterval(function () {
                try {
                    if (win == null || win.closed) {
                        unLoadFn();
                    }
                } catch (e) { }
            }, 500);

            if (win.addEventListener) {
                win.addEventListener('load', onLoadFn, false);
            } else {
                win.attachEvent('load', onLoadFn);
            }

            window.addEventListener('beforeunload', beforeUnloadAndCloseFn, false);
        }
    }
}

How to style readonly attribute with CSS?

If you select the input by the id and then add the input[readonly="readonly"] tag in the css, something like:

 #inputID input[readonly="readonly"] {
     background-color: #000000;
 }

That will not work. You have to select a parent class or id an then the input. Something like:

 .parentClass, #parentID input[readonly="readonly"] {
     background-color: #000000;
 }

My 2 cents while waiting for new tickets at work :D

Check file size before upload

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

ImportError: No module named sqlalchemy

I just experienced the same problem. Apparently, there is a new distribution method, the extension code is no longer stored under flaskext.

Source: Flask CHANGELOG This worked for me:

from flask_sqlalchemy import SQLAlchemy

How do I hide a menu item in the actionbar?

Try this:

MenuItem myitem = menu.findItem(R.id.my_item);
myitem.setVisible(false);

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Declare and assign multiple string variables at the same time

Fairly old question but incase someone goes back.
This isn't as compact as the other answers above, but fairly readable and easier to type using Visual Studio Multi-Line selection shortcut [Alt+ Shift + ?] (or other directions)

string Camnr = string.Empty;
string Klantnr = string.Empty;

Type out all variable names on new lines. Multi-Select in front of them an type "string". Multi-Select behind them and type "= string.Empty;".

How to create module-wide variables in Python?

Explicit access to module level variables by accessing them explicity on the module


In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

# db.py
import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = "Locally scoped db_name variable. Doesn't do anything here."
    else:
        msg = "Database is already initialized to {0}."
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
import db

if (db.db_name == 'mongo'):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value 
# that "db.db_name" has at import time of "client_c".

if (db_name == 'mongo'):  # checking is fine if "db.db_name" doesn't change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

While using formControl, you have to import ReactiveFormsModule to your imports array.

Example:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  ...
})
export class AppModule {}

How can I check if a checkbox is checked?

Try This

<script type="text/javascript">
window.onload = function () {
    var input = document.querySelector('input[type=checkbox]');

    function check() {
        if (input.checked) {
            alert("checked");
        } else {
            alert("You didn't check it.");
        }
    }
    input.onchange = check;
    check();
}
</script>

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

About the server can deliver to the clients the root cert or not, extracted from the RFC-5246 'The Transport Layer Security (TLS) Protocol Version 1.2' doc it says:

certificate_list
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY be omitted from the chain, under the
assumption that the remote end must already possess it in order to validate it in any case.

About the term 'MAY', extracted from the RFC-2119 "Best Current Practice" says:

5.MAY
This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a
particular marketplace requires it or because the vendor feels that
it enhances the product while another vendor may omit the same item.
An implementation which does not include a particular option MUST be
prepared to interoperate with another implementation which does
include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option
MUST be prepared to interoperate with another implementation which
does not include the option (except, of course, for the feature the
option provides.)

In conclusion, the root may be at the certification path delivered by the server in the handshake.

A practical use.
Think about, not in navigator user terms, but on a transfer tool at a server in a militarized zone with limited internet access.
The server, playing the client role at the transfer, receives all the certs path from the server.
All the certs in the chain should be checked to be trusted, root included.
The only way to check this is the root be included at the certs path in transfer time, being matched against a previously declared as 'trusted' local copy of them.

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

How to pretty-print a numpy.array without scientific notation and with given precision?

numpy.char.mod may also be useful, depending on the details of your application e.g.:numpy.char.mod('Value=%4.2f', numpy.arange(5, 10, 0.1)) will return a string array with elements "Value=5.00", "Value=5.10" etc. (as a somewhat contrived example).

Binary search (bisection) in Python

This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):

Sorted Lists

  • O( n log n) to initially create the list (if it's unsorted data. O(n), if it's sorted )
  • O( log n) lookups (this is the binary search part)
  • O( n ) insert / delete (might be O(1) or O(log n) average case, depending on your pattern)

Whereas with a set(), you're incurring

  • O(n) to create
  • O(1) lookup
  • O(1) insert / delete

The thing a sorted list really gets you are "next", "previous", and "ranges" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index. If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall. set() incurs very little additional overhead in python.

Differences between SP initiated SSO and IDP initiated SSO

https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso

There is much more to this but this is a high level overview on which is which.

Procore supports both SP- and IdP-initiated SSO:

Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

Select multiple value in DropDownList using ASP.NET and C#

Dropdown list wont allows multiple item select in dropdown.

If you need , you can use listbox control..

ASP.NET List Box

Making text background transparent but not text itself

Don't use opacity for this, set the background to an RGBA-value instead to only make the background semi-transparent. In your case it would be like this.

.content {
    padding:20px;
    width:710px;
    position:relative;
    background: rgb(204, 204, 204); /* Fallback for older browsers without RGBA-support */
    background: rgba(204, 204, 204, 0.5);
}

See http://css-tricks.com/rgba-browser-support/ for more info and samples of rgba-values in css.

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

How to declare a type as nullable in TypeScript?

i had this same question a while back.. all types in ts are nullable, because void is a subtype of all types (unlike, for example, scala).

see if this flowchart helps - https://github.com/bcherny/language-types-comparison#typescript

Rebase array keys after unsetting elements

I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.

IllegalArgumentException or NullPointerException for a null parameter?

If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

How do I find duplicate values in a table in Oracle?

You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1

How to convert WebResponse.GetResponseStream return into a string?

You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.

Write a file in external storage in Android

You can find these method usefull in reading and writing data in android.

 public void saveData(View view) {
    String text = "This is the text in the file, this is the part of the issue of the name and also called the name od the college ";
    FileOutputStream fos = null;
    try {
        fos = openFileOutput("FILE_NAME", MODE_PRIVATE);
        fos.write(text.getBytes());
        Toast.makeText(this, "Data is saved "+ getFilesDir(), Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fos!= null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

public void logData(View view) {
    FileInputStream fis = null;

    try {
        fis = openFileInput("FILE_NAME");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb=  new StringBuilder();
        String text;
        while((text = br.readLine()) != null){
            sb.append(text).append("\n");
            Log.e("TAG", text
            );
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

How to get the contents of a webpage in a shell variable?

You can use wget command to download the page and read it into a variable as:

content=$(wget google.com -q -O -)
echo $content

We use the -O option of wget which allows us to specify the name of the file into which wget dumps the page contents. We specify - to get the dump onto standard output and collect that into the variable content. You can add the -q quiet option to turn off's wget output.

You can use the curl command for this aswell as:

content=$(curl -L google.com)
echo $content

We need to use the -L option as the page we are requesting might have moved. In which case we need to get the page from the new location. The -L or --location option helps us with this.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Thanks for the answers here!! helped me come up with these helper functions for some interaction with the Google Sheets API that i'm working on in Elixir/Phoenix

here's what i came up with (could probably use some extra validation and error handling)

In Elixir:

def number_to_column(number) do
  cond do
    (number > 0 && number <= 26) ->
      to_string([(number + 64)])
    (number > 26) ->
      div_col = number_to_column(div(number - 1, 26))
      remainder = rem(number, 26)
      rem_col = cond do
        (remainder == 0) ->
          number_to_column(26)
        true ->
          number_to_column(remainder)
      end
      div_col <> rem_col
    true ->
      ""
  end
end

And the inverse function:

def column_to_number(column) do
  column
    |> to_charlist
    |> Enum.reverse
    |> Enum.with_index
    |> Enum.reduce(0, fn({char, idx}, acc) ->
      ((char - 64) * :math.pow(26,idx)) + acc
    end)
    |> round
end

And some tests:

describe "test excel functions" do
  @excelTestData [{"A", 1}, {"Z",26}, {"AA", 27}, {"AB", 28}, {"AZ", 52},{"BA", 53}, {"AAA", 703}]

  test "column to number" do
    Enum.each(@excelTestData, fn({input, expected_result}) ->
      actual_result = BulkOnboardingController.column_to_number(input)
      assert actual_result == expected_result
    end)
  end

  test "number to column" do
    Enum.each(@excelTestData, fn({expected_result, input}) ->
      actual_result = BulkOnboardingController.number_to_column(input)
      assert actual_result == expected_result
    end)
  end
end

android: how to use getApplication and getApplicationContext from non activity / service class

Casting a Context object to an Activity object compiles fine.

Try this:

((Activity) mContext).getApplication(...)

Find files in a folder using Java

Consider Apache Commons IO, it has a class called FileUtils that has a listFiles method that might be very useful in your case.

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Illegal mix of collations MySQL Error

My user account did not have the permissions to alter the database and table, as suggested in this solution.

If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:

SET collation_connection = 'latin1_swedish_ci';

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Is it possible to install another version of Python to Virtualenv?

You may use pyenv.

There are a lot of different versions anaconda, jython, pypy and so on...

https://github.com/yyuu/pyenv

Installation as simple as pyenv install 3.2.6

pyenv install --list
Available versions:
  2.1.3
  2.2.3
  2.3.7
  2.4
  2.4.1
  2.4.2
  2.4.3
  2.4.4
  2.4.5
  2.4.6
  2.5
  2.5.1
  2.5.2
  2.5.3
  2.5.4
  2.5.5
  2.5.6
  2.6.6

...

How to remove a TFS Workspace Mapping?

From VS:

  1. Open Team Explorer
  2. Click Source Control Explorer
  3. In the nav bar of the tool window there is a drop down labeled "Workspaces".
  4. Extend it and click on the "Workspaces..." option (yeah, a bit un-intuitive)
  5. The "Manage Workspaces" window comes up. Click edit and you can add / remove / edit your workspace

source control explorer

From VS on a different machine

You don't need VS to be on the same machine as the enlistment as you can edit remote enlistments! In the dialog that comes up when you press the "Workspaces..." item there is a check box stating "Show Remote Workspaces" - just tick that and you'll get a list of all your enlistments:

show remote workspaces

From the command line

Call "tf workspace" from a developer command prompt. It will bring up the "Manage Workspaces" directly!

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

I had similar issue, the actual reason was that there was mongod session running already from my previous attempt.

I ran

killall mongod

and everything else ran just as expected.

killall command would send a TERM signal to all processes with a real UID. So this kills all the running instances of mongod so that you could start your own.

jquery animate background position

In your jQuery code there is a comma after the backgroundPosition portion:

backgroundPosition: '-20px 0px',

However, when listing the various properties you want to change in the .animate() method (and similar methods), the last argument listed between curly braces should not have a comma after it. I can't say if that's why the background position isn't getting changed, but it is an error and one I'd suggest fixing.

UPDATE: In the limited testing I've done just now, entering purely numerical values (without "px") works for backgroundPosition in the .animate() method. In other words, this works:

backgroundPosition: '-20 0'

However, this does not:

backgroundPosition: '-20px 0'

Hope this helps.

Using Pip to install packages to Anaconda Environment

I know the original question was about conda under MacOS. But I would like to share the experience I've had on Ubuntu 20.04.

In my case, the issue was due to an alias defined in ~/.bashrc: alias pip='/usr/bin/pip3'. That alias was taking precedence on everything else.

So for testing purposes I've removed the alias running unalias pip command. Then the corresponding pip of the active conda environment has been executed properly.

The same issue was applicable to python command.

Formatting a float to 2 decimal places

The first thing you need to do is use the decimal type instead of float for the prices. Using float is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.

Once you have done that, Decimal.Round() can be used to round to 2 places.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Origin http://localhost is not allowed by Access-Control-Allow-Origin

By localhost you have to use the null origin. I recommend you to create a list of allowed hosts and check the request's Host header. If it is contained by the list, then by localhost send back an

res.header('Access-Control-Allow-Origin', "null");

by any other domain an

res.header('Access-Control-Allow-Origin', hostSentByTheRequestHeader);

If it is not contained by the list, then send back the servers host name, so the browser will hide the response by those requests.

This is much more secure, because by allow origin * and allow credentials everybody will be capable of for example stealing profile data of a logged in user, etc...

So to summarize something like this:

if (reqHost in allowedHosts)
    if (reqHost == "http://localhost")
        res.header('Access-Control-Allow-Origin', "null");
    else
        res.header('Access-Control-Allow-Origin', reqHost);
else
    res.header('Access-Control-Allow-Origin', serverHost);

is the most secure solution if you want to allow multiple other domains to access your page. (I guess you can figure out how the get the host request header and the server host by node.js.)

Segmentation Fault - C

char *s  does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;

This would not lead to segmentation fault error as you will not be refering to an unknown location anymore

JAX-RS — How to return JSON and HTTP status code together?

Also, notice that by default Jersey will override the response body in case of an http code 400 or more.

In order to get your specified entity as the response body, try to add the following init-param to your Jersey in your web.xml configuration file :

    <init-param>
        <!-- used to overwrite default 4xx state pages -->
        <param-name>jersey.config.server.response.setStatusOverSendError</param-name>
        <param-value>true</param-value>
    </init-param>

How do I manually configure a DataSource in Java?

The javadoc for DataSource you refer to is of the wrong package. You should look at javax.sql.DataSource. As you can see this is an interface. The host and port name configuration depends on the implementation, i.e. the JDBC driver you are using.

I have not checked the Derby javadocs but I suppose the code should compile like this:

ClientDataSource ds = org.apache.derby.jdbc.ClientDataSource()
ds.setHost etc....

Are multiple `.gitignore`s frowned on?

As a tangential note, one case where the ability to have multiple .gitignore files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore (containing just a single asterisk) in that directory and it will never show up in git status etc.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).

Once you find the htaccess file add the following line:

  1. Header set Access-Control-Allow-Origin "*" Just to see if it works. Warning: Do not use this line on a production server

It should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.

  1. Once you do have the above working change the * to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.

SQL Server: IF EXISTS ; ELSE

Try this:

Update TableB Set
  Code = Coalesce(
    (Select Max(Value)
    From TableA 
    Where Id = b.Id), 123)
From TableB b

Sublime Text 2: How to delete blank/empty lines

To find extra spaces and blank lines press Ctrl+Shift+F Select Regular Expressions Find

[\n\r]{2,}

and then replace with

\n

to remove all kind of spaces in sublime and dreamviewr

How to encode the plus (+) symbol in a URL

In order to encode + value using JavaScript, you can use encodeURIComponent function.

Example:

_x000D_
_x000D_
var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)
_x000D_
_x000D_
_x000D_

Selecting with complex criteria from pandas.DataFrame

Another solution is to use the query method:

import pandas as pd

from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
                   'B': [randint(1, 9) * 10 for x in xrange(10)],
                   'C': [randint(1, 9) * 100 for x in xrange(10)]})
print df

   A   B    C
0  7  20  300
1  7  80  700
2  4  90  100
3  4  30  900
4  7  80  200
5  7  60  800
6  3  80  900
7  9  40  100
8  6  40  100
9  3  10  600

print df.query('B > 50 and C != 900')

   A   B    C
1  7  80  700
2  4  90  100
4  7  80  200
5  7  60  800

Now if you want to change the returned values in column A you can save their index:

my_query_index = df.query('B > 50 & C != 900').index

....and use .iloc to change them i.e:

df.iloc[my_query_index, 0] = 5000

print df

      A   B    C
0     7  20  300
1  5000  80  700
2  5000  90  100
3     4  30  900
4  5000  80  200
5  5000  60  800
6     3  80  900
7     9  40  100
8     6  40  100
9     3  10  600

Python: Removing spaces from list objects

Presuming that you don't want to remove internal spaces:

def normalize_space(s):
    """Return s stripped of leading/trailing whitespace
    and with internal runs of whitespace replaced by a single SPACE"""
    # This should be a str method :-(
    return ' '.join(s.split())

replacement = [normalize_space(i) for i in hello]

jQuery Form Validation before Ajax submit

You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.

You should validate the form:

if ($(this).validate().form()) {
  // do ajax stuff
}

https://jqueryvalidation.org/Validator.form/#validator-form()

Find a line in a file and remove it

    public static void deleteLine() throws IOException {
        RandomAccessFile file = new RandomAccessFile("me.txt", "rw");
        String delete;
        String task="";
        byte []tasking;
        while ((delete = file.readLine()) != null) {
            if (delete.startsWith("BAD")) {
                continue;
            }
            task+=delete+"\n";
        }
        System.out.println(task);
        BufferedWriter writer = new BufferedWriter(new FileWriter("me.txt"));
        writer.write(task);
        file.close();
        writer.close();
    }

Finding the position of the max element

std::max_element takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.

CSS display:inline property with list-style-image: property on <li> tags

You want style image and Nav with float to each other then use like this

ol.widgets ul
{
list-style-image:url('some-img.gif');
}
ol.widgets ul li
{
float:left;
}

From a Sybase Database, how I can get table description ( field names and types)?

You can search for column in all tables in database using:

SELECT so.name 
FROM sysobjects so
INNER JOIN syscolumns sc ON so.id = sc.id 
WHERE sc.name = 'YOUR_COLUMN_NAME'

DD/MM/YYYY Date format in Moment.js

This worked for me

var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP

moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

jQuery add class .active on menu

Wasim's answer a few posts up from here works as advertised:

http://jsfiddle.net/Realto619/jKf3F/1/

Python list / sublist selection -1 weirdness

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Removing elements from an array in C

There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.

Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:

void remove_element(array_type *array, int index, int array_length)
{
   int i;
   for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}

Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:

remove_element(array, index, array_length);  /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
   /* No memory available */
   exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;

realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.

Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.

Bootstrap button - remove outline on Chrome OS X

I see .btn:focus has an outline on it:

.btn:focus {
  outline: thin dotted;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}

Try changing this to:

.btn:focus {
  outline: none !important;
}

Basically, look for any instances of outline on :focused elements — that's what's causing it.

Update - For Bootstrap v4:

.btn:focus {
  box-shadow: none;
}

How can I check for NaN values?

math.isnan()

or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.

Draw an X in CSS

I love this question! You could easily adapt my code below to be a white × on an orange square:

enter image description here

Demo fiddle here

Here is the SCSS (which could easily be converted to CSS):

$pFontSize: 18px;
p {
  font-size: $pFontSize;
}
span{
  font-weight: bold;
}
.x-overlay,
.x-emoji-overlay {
  position: relative;
}

.x-overlay,
.x-emoji-overlay {
  &:after {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    color: red;
    text-align: center;
  }
}

.x-overlay:after {
  content: '\d7';
  font-size: 3 * $pFontSize;
  line-height: $pFontSize;
  opacity: 0.7;
}

.x-emoji-overlay:after {
  content: "\274c";
  padding: 3px;
  font-size: 1.5 * $pFontSize;
  line-height: $pFontSize;
  opacity: 0.5;
}

.strike {
  position: relative;
  display: inline-block;
}

.strike::before {
  content: '';
  border-bottom: 2px solid red;
  width: 110%;
  position: absolute;
  left: -2px;
  top: 46%;
}

.crossed-out {
  /*inspired by https://www.tjvantoll.com/2013/09/12/building-custom-text-strikethroughs-with-css/*/
  position: relative;
  display: inline-block;
  &::before,
  &::after {
    content: '';
    width: 110%;
    position: absolute;
    left: -2px;
    top: 45%;
    opacity: 0.7;
  }
  &::before {
    border-bottom: 2px solid red;
    -webkit-transform: skewY(-20deg);
    transform: skewY(-20deg);
  }
  &::after {
    border-bottom: 2px solid red;
    -webkit-transform: skewY(20deg);
    transform: skewY(20deg);
  }
}

Understanding the Gemfile.lock file

It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is . because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is rubygems.org, since that's where it had to go to find out what belongs in GEM::spec.

In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH.

As for DEPENDENCIES, gembundler.com states:

Runtime dependencies in your gemspec are treated like base dependencies, 
and development dependencies are added by default to the group, :development

The Gemfile generated by rails plugin new my_plugin says something similar:

# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.

What this means is that the difference between

s.add_development_dependency "july" # (1)

and

s.add_dependency "july" # (2)

is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install from a production environment (i.e. in some other gem that includes yours as a dependency), not only development.

These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments.

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Bootstrap >= v4.0 dropped glyphicon support

Dropped the Glyphicons icon font. If you need icons, some options are:

the upstream version of Glyphicons

Octicons

Font Awesome

Source: https://v4-alpha.getbootstrap.com/migration/#components

If you are using Bootstrap >= v4.0 or newer, you can use existing style classes of bootstrap such as text-success,text-warning etc.

For example, if you are using fontawesome:

<i class="fa fa-tag text-danger" aria-hidden="true"></i>

Display the binary representation of a number in C?

You have to write your own transformation. Only decimal, hex and octal numbers are supported with format specifiers.

FCM getting MismatchSenderId

For me the problem was that I was using the phonegap-plugin-push in cordova, testing the app with the phonegap app.

The problem with this is that for some reason with this plugin, the phonegap app intercepts it and returns a dummy registration key, no matter what sender ID you have.

So to make it work (as long as you have all your keys right) is to test your program some other way, with an emulator, or android emulation via usb. And your keys will match.

Hopefully this saves someone some time.

Bower: ENOGIT Git is not installed or not in the PATH

1.Set the Path of Git in environment variables. 2.From Windows command prompt, run cd Project\folder\Path\ run the command: bower install

How to change the button text of <input type="file" />?

<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
    <span>Your name</span>
    <input id="uploadBtn" type="file" class="upload" />
</div>

JS

document.getElementById("uploadBtn").onchange = function () {
    document.getElementById("uploadFile").value = this.value;
 };

more http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

How to validate a file upload field using Javascript/jquery

Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.

<script>
var valid = false;

function validate_fileupload(input_element)
{
    var el = document.getElementById("feedback");
    var fileName = input_element.value;
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop(); 
    for(var i = 0; i < allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            valid = true; // valid file extension
            el.innerHTML = "";
            return;
        }
    }
    el.innerHTML="Invalid file";
    valid = false;
}

function valid_form()
{
    return valid;
}
</script>

<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
  <input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
  <input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>

css3 text-shadow in IE9

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

Some projects cannot be imported because they already exist in the workspace error in Eclipse

It has just happened to me too. Finally I realized that the project was already open in my workspace but it was not visible because of the selected working set. You have just to deselect the active working set and all opened projects will become visible.

What's the difference between using CGFloat and float?

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// The native type used to store the CGFloat, which is Float on
    /// 32-bit architectures and Double on 64-bit architectures.
    public typealias NativeType = Double

MySQL Daemon Failed to Start - centos 6

try

netstat -a -t -n | grep 3306 

to see any one listening to the 3306 port then kill it

I was having this problem for 2 days. Trying out the solutions posted on forums I accidentally ran into a situation where my log was getting this error

check that you do not already have another mysqld process

how to change text in Android TextView

per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").

TextView t; 
private String sText;

private Handler mHandler = new Handler();

private Runnable mWaitRunnable = new Runnable() {
    public void run() {
        t.setText(sText);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mMonster = BitmapFactory.decodeResource(getResources(),
            R.drawable.monster1);

    t=new TextView(this); 
    t=(TextView)findViewById(R.id.TextView01); 

    sText = "Step One: unpack egg";
    t.setText(sText);

    sText = "Step Two: fry egg";        
    mHandler.postDelayed(mWaitRunnable, 3000);

    sText = "Step three: serve egg";
    mHandler.postDelayed(mWaitRunnable, 4000);      
    ...
}

Replace forward slash "/ " character in JavaScript string?

Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -

Get value from input (AngularJS)

If you want to get values in Javascript on frontend, you can use the native way to do it by using :

document.getElementsByName("movie")[0].value;

Where "movie" is the name of your input <input type="text" name="movie">

If you want to get it on angular.js controller, you can use;

$scope.movie

Select query to remove non-numeric characters

 Declare @MainTable table(id int identity(1,1),TextField varchar(100))
  INSERT INTO @MainTable (TextField)
 VALUES
 ('6B32E')
 declare @i int=1
  Declare @originalWord varchar(100)=''
  WHile @i<=(Select count(*) from @MainTable)
  BEGIN
  Select @originalWord=TextField from @MainTable where id=@i

 Declare @r varchar(max) ='', @len int ,@c char(1), @x int = 0

    Select @len = len(@originalWord)
    declare @pn varchar(100)=@originalWord
    while @x <= @len 
    begin

      Select @c = SUBSTRING(@pn,@x,1)
    if(@c!='')
    BEGIN
            if ISNUMERIC(@c) = 0 and @c <> '-'
    BEGIN
     Select @r = cast(@r as varchar) + cast(replace((SELECT ASCII(@c)-64),'-','') as varchar)

   end
   ELSE
   BEGIN
    Select @r = @r + @c


   END

END


    Select @x = @x +1

    END
    Select @r
  Set @i=@i+1
  END

How to Create a circular progressbar in Android which rotates on it?

@Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml code to this:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="270"
    android:toDegrees="270">
    <shape
        android:innerRadiusRatio="2.5"
        android:shape="ring"
        android:thickness="1dp"
        android:useLevel="true"> <!-- Just add this line -->
        <gradient
            android:angle="0"
            android:endColor="#007DD6"
            android:startColor="#007DD6"
            android:type="sweep"
            android:useLevel="false" />
    </shape>
</rotate>

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How to create a directory using Ansible

Directory can be created using file module only, as directory is nothing but a file.

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755
    owner: foo
    group: foo

How to represent empty char in Java Character class

You can do something like this:

mystring.replace(""+ch, "");

How to convert an int array to String with toString method in Java

Here's an example of going from a list of strings, to a single string, back to a list of strings.

Compiling:

$ javac test.java
$ java test

Running:

    Initial list:

        "abc"
        "def"
        "ghi"
        "jkl"
        "mno"

    As single string:

        "[abc, def, ghi, jkl, mno]"

    Reconstituted list:

        "abc"
        "def"
        "ghi"
        "jkl"
        "mno"

Source code:

import java.util.*;
public class test {

    public static void main(String[] args) {
        List<String> listOfStrings= new ArrayList<>();
        listOfStrings.add("abc");
        listOfStrings.add("def");
        listOfStrings.add("ghi");
        listOfStrings.add("jkl");
        listOfStrings.add("mno");

        show("\nInitial list:", listOfStrings);

        String singleString = listOfStrings.toString();

        show("As single string:", singleString);

        List<String> reconstitutedList = Arrays.asList(
             singleString.substring(0, singleString.length() - 1)
                  .substring(1).split("[\\s,]+"));

        show("Reconstituted list:", reconstitutedList);
    }

    public static void show(String title, Object operand) {
        System.out.println(title + "\n");
        if (operand instanceof String) {
            System.out.println("    \"" + operand + "\"");
        } else {
            for (String string : (List<String>)operand)
                System.out.println("    \"" + string + "\"");
        }
        System.out.println("\n");
    }
}

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I liked the (C#) code in the following which sets the registry settings for your app. Not sure if it will cut it after installation though if permissions are required. For me it solved an issue with WebSocket not being available inside a WebBrowser control in WPF.

C# webbrowser Ajax call

Connecting to local SQL Server database using C#

If you use SQL authentication, use this:

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "User Id=UserName;" + 
     "Password=Secret;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

If you use Windows authentication, use this:

using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "Integrated Security=true;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

How to split a string to 2 strings in C

You can do:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

Laravel is there a way to add values to a request array

you can use laravel helper and request() magic method ...

request()->request->add(['variable1'=>'value1','variable2'=>'value2']);

Android: remove notification from notification bar

Please try this,

public void removeNotification(Context context, int notificationId) {      
    NotificationManager nMgr = (NotificationManager) context.getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancel(notificationId);
}

jquery clear input default value

Try that:

  var defaultEmailNews = "Email address";
  $('input[name=email]').focus(function() {
    if($(this).val() == defaultEmailNews) $(this).val("");
  });

  $('input[name=email]').focusout(function() {
    if($(this).val() == "") $(this).val(defaultEmailNews);
  });

How to get name of dataframe column in pyspark?

The only way is to go an underlying level to the JVM.

df.col._jc.toString().encode('utf8')

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

How to get the client IP address in PHP

Here's a simple one liner

$ip = $_SERVER['HTTP_X_FORWARDED_FOR']?: $_SERVER['HTTP_CLIENT_IP']?: $_SERVER['REMOTE_ADDR'];

EDIT:

Above code may return reserved addresses (like 10.0.0.1), a list of addresses of all proxy servers on the way, etc. To handle these cases use the following code:

function valid_ip($ip) {
    // for list of reserved IP addresses, see https://en.wikipedia.org/wiki/Reserved_IP_addresses
    return $ip && substr($ip, 0, 4) != '127.' && substr($ip, 0, 4) != '127.' && substr($ip, 0, 3) != '10.' && substr($ip, 0, 2) != '0.' ? $ip : false;
}

function get_client_ip() {
    // using explode to get only client ip from list of forwarders. see https://en.wikipedia.org/wiki/X-Forwarded-For
    return
    @$_SERVER['HTTP_X_FORWARDED_FOR'] ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2)[0] :
    @$_SERVER['HTTP_CLIENT_IP'] ? explode(',', $_SERVER['HTTP_CLIENT_IP'], 2)[0] :
    valid_ip(@$_SERVER['REMOTE_ADDR']) ?:
    'UNKNOWN';
}

echo get_client_ip();

Force IE compatibility mode off using tags

This is due to the setting within IE Compatibility settings which says that all Intranet sites should run in compatibility mode. You can untick this via a group policy (or just plain unticking it in IE), or you can set the following:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Apparently it is not possible to change the compatibility view settings as a group policy but it is something that can perhaps be changed in the registry, this meta tag works fine for me, I had to make the required attribute work as part of a html form, it worked in chrome and firefox but not IE.

Here is a nice visual of what browsers support each individual html 5 element.

http://html5readiness.com/

Notice the one common denominator Google Chrome, it supports everything. Hope this is of help

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

Calling onclick on a radiobutton list using javascript

_x000D_
_x000D_
Hi, I think all of the above might work. In case what you need is simple, I used:_x000D_
_x000D_
<body>_x000D_
    <div class="radio-buttons-choice" id="container-3-radio-buttons-choice">_x000D_
        <input type="radio" name="one" id="one-variable-equations" onclick="checkRadio(name)"><label>Only one</label><br>_x000D_
        <input type="radio" name="multiple" id="multiple-variable-equations" onclick="checkRadio(name)"><label>I have multiple</label>_x000D_
    </div>_x000D_
_x000D_
<script>_x000D_
function checkRadio(name) {_x000D_
    if(name == "one"){_x000D_
    console.log("Choice: ", name);_x000D_
        document.getElementById("one-variable-equations").checked = true;_x000D_
        document.getElementById("multiple-variable-equations").checked = false;_x000D_
_x000D_
    } else if (name == "multiple"){_x000D_
        console.log("Choice: ", name);_x000D_
        document.getElementById("multiple-variable-equations").checked = true;_x000D_
        document.getElementById("one-variable-equations").checked = false;_x000D_
    }_x000D_
}_x000D_
</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

When would you use the Builder Pattern?

Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult()
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior,
            MaxJsonLength = Int32.MaxValue
        };
    }

Was the fix for me in MVC 4.

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

How to delete columns in a CSV file?

Using a dict to grab headings then looping through gets you what you need cleanly.

import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
    rdr = csv.reader( source )
    with open("result","wb") as result:
        wtr = csv.writer( result )
        for row in rdr:
            if ct == 0:
              cc = 0
              for col in row:
                for ciw in cols_i_want: 
                  if col == ciw:
                    cols_i_want[ciw] = cc
                cc += 1
            wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
            ct += 1

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Showing percentages above bars on Excel column graph

In Excel for Mac 2016 at least,if you place the labels in any spot on the graph and are looking to move them anywhere else (in this case above the bars), select:

Chart Design->Add Chart Element->Data Labels -> More Data Label Options

then you can grab each individual label and pull it where you would like it.

Using 24 hour time in bootstrap timepicker

<input type="text" name="time" data-provide="timepicker"  id="time" class="form-control" placeholder="Start Time" value="" />


$('#time').timepicker({
        timeFormat: 'H:i',
        'scrollDefaultNow'      : 'true',
        'closeOnWindowScroll'   : 'true',
        'showDuration'          : false,
        'ignoreReadonly'        : true,

})

work for me.

Best practices with STDIN in Ruby?

Quick and simple:

STDIN.gets.chomp == 'YES'

What is lexical scope?

In simple language, lexical scope is a variable defined outside your scope or upper scope is automatically available inside your scope which means you don't need to pass it there.

Example:

let str="JavaScript";

const myFun = () => {
    console.log(str);
}

myFun();

// Output: JavaScript

How set background drawable programmatically in Android

Try this code:

Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);

Increment value in mysql update query

"UPDATE member_profile SET points = points + 1 WHERE user_id = '".$userid."'"

Margin-Top not working for span element?

span element is display:inline; by default you need to make it inline-block or block

Change your CSS to be like this

span.first_title {
    margin-top: 20px;
    margin-left: 12px;
    font-weight: bold;
    font-size:24px;
    color: #221461;
    /*The change*/
    display:inline-block; /*or display:block;*/
}

How to import JSON File into a TypeScript file?

In angular7, I simply used

let routesObject = require('./routes.json');

My routes.json file looks like this

{

    "routeEmployeeList":    "employee-list",
    "routeEmployeeDetail":      "employee/:id"
}

You access json items using

routesObject.routeEmployeeList

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Applying .gitignore to committed files

to leave the file in the repo but ignore future changes to it:

git update-index --assume-unchanged <file>

and to undo this:

git update-index --no-assume-unchanged <file>

to find out which files have been set this way:

git ls-files -v|grep '^h'

credit for the original answer to http://blog.pagebakers.nl/2009/01/29/git-ignoring-changes-in-tracked-files/

How to remove files from git staging area?

As noted in other answers, you should use git reset. This will undo the action of the git add -A.

Note: git reset is equivalent to git reset --mixed which does this

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action. [ git reset ]

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

jQuery: serialize() form and other parameters

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}

jquery click event not firing?

I was wasting my time on this for hours. Fortunately, I found the solution. If you are using bootstrap admin templates (AdminLTE), this problem may show up. Thing is we have to use adminLTE framework plugins.

example: ifChecked event:

$('input').on('ifChecked', function(event){
   alert(event.type + ' callback');
});

For more information click here.

Hope it helps you too.

How do I calculate tables size in Oracle

First, gather optimiser stats on the table (if you haven't already):

begin
   dbms_stats.gather_table_stats('MYSCHEMA','MYTABLE');
end;
/

WARNING: As Justin says in his answer, gathering optimiser stats affects query optimisation and should not be done without due care and consideration!

Then find the number of blocks occupied by the table from the generated stats:

select blocks, empty_blocks, num_freelist_blocks
from   all_tables
where  owner = 'MYSCHEMA'
and    table_name = 'MYTABLE';
  • The total number of blocks allocated to the table is blocks + empty_blocks + num_freelist_blocks.

  • blocks is the number of blocks that actually contain data.

Multiply the number of blocks by the block size in use (usually 8KB) to get the space consumed - e.g. 17 blocks x 8KB = 136KB.

To do this for all tables in a schema at once:

begin
    dbms_stats.gather_schema_stats ('MYSCHEMA');
end;
/

select table_name, blocks, empty_blocks, num_freelist_blocks
from   user_tables;

Note: Changes made to the above after reading this AskTom thread

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If you're in a Browser-Only environment, use SridharR's solution.

If you're in a Node/CommonJS + Browser environment (e.g. electron, node-webkit, etc..); the reason for this error is that jQuery's export logic first checks for module, not window:

if (typeof module === "object" && typeof module.exports === "object") {
    // CommonJS/Node
} else {
    // window
}

Note that it exports itself via module.exports in this case; so jQuery and $ are not assigned to window.

So to resolve this, instead of <script src="path/to/jquery.js"></script>;

Simply assign it yourself by a require statement:

<script>
    window.jQuery = window.$ = require('jquery');
</script>

NOTE: If your electron app does not need nodeIntegration, set it to false so you won't need this workaround.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

Could not load the Tomcat server configuration

You can install tomcat7 in ~/tomcat7 instead of /usr/share/tomcat7.

  1. Close Eclipse.
  2. Delete org.eclipse.wst.server.core.prefs and org.eclipse.jst.server.tomcat.core.prefs in {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings.
  3. Launch Eclipse.
  4. Go to Window->Show View->Other... and choose the Servers.
  5. Select Tomcat v7.0 Server from the server type and press Next.
  6. Enter /home/user/tomcat7 (not /usr/share/tomcat7) into the "Tomcat installation directory" and press Download.
  7. Wait a few minutes and press Finish.

tomcat7 worked correctly with Eclipse 4.4 on my Ubuntu 15.04 in this way.

Deploy a project using Git push

Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.

C# Remove object from list of objects

If ChunkList is List<Chunk>, you can use the RemoveAll method:

ChunkList.RemoveAll(chunk => chunk.UniqueID == ChunkID);

Java - Writing strings to a CSV file

Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this

public void writeAudit(String actionName) {
    String whereWrite = "./csvFiles/audit.csv";

    try {
        FileWriter fw = new FileWriter(whereWrite, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        Date date = new Date();

        pw.println(actionName + "," + date.toString());
        pw.flush();
        pw.close();

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This happened to me, and once I removed this: enctype="multipart/form-data" It started working without the warning

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

Performing a Stress Test on Web Application?

I've used The Grinder. It's open source, pretty easy to use, and very configurable. It is Java based and uses Jython for the scripts. We ran it against a .NET web application, so don't think it's a Java only tool (by their nature, any web stress tool should not be tied to the platform it uses).

We did some neat stuff with it... we were a web based telecom application, so one cool use I set up was to mimick dialing a number through our web application, then used an auto answer tool we had (which was basically a tutorial app from Microsoft to connect to their RTC LCS server... which is what Microsoft Office Communicator connects to on a local network... then modified to just pick up calls automatically). This then allowed us to use this instead of an expensive telephony tool called The Hammer (or something like that).

Anyways, we also used the tool to see how our application held up under high load, and it was very effective in finding bottlenecks. The tool has built in reporting to show how long requests are taking, but we never used it. The logs can also store all the responses and whatnot, or custom logging.

I highly recommend this tool, very useful for the price... but expect to do some custom setup with it (it has a built in proxy to record a script, but it may need customization for capturing something like sessions... I know I had to customize it to utilize a unique session per thread).

How to check if click event is already bound - JQuery

As of June 2019, I've updated the function (and it's working for what I need)

$.fn.isBound = function (type) {
    var data = $._data($(this)[0], 'events');

    if (data[type] === undefined || data.length === 0) {
        return false;
    }
    return true;
};

How to save a figure in MATLAB from the command line?

If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

I tried this simple thing and it seems to be working.

file.setWritable(true);
file.delete();

It works for me.

If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.

SELECT INTO a table variable in T-SQL

One reason to use SELECT INTO is that it allows you to use IDENTITY:

SELECT IDENTITY(INT,1,1) AS Id, name
INTO #MyTable 
FROM (SELECT name FROM AnotherTable) AS t

This would not work with a table variable, which is too bad...

symfony2 : failed to write cache directory

Maybe you forgot to change the permissions of app/cache app/log

I'm using Ubuntu so

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs

Hope it helps..

Query to get the names of all tables in SQL Server 2008 Database

Try this:

SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

it will display the schema+table name for all tables in the current database.

Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1

set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.

How to share data between different threads In C# using AOP?

You can pass an object as argument to the Thread.Start and use it as a shared data storage between the current thread and the initiating thread.

You can also just directly access (with the appropriate locking of course) your data members, if you started the thread using the instance form of the ThreadStart delegate.

You can't use attributes to create shared data between threads. You can use the attribute instances attached to your class as a data storage, but I fail to see how that is better than using static or instance data members.

PHPMailer AddAddress()

Some great answers above, using that info here is what I did today to solve the same issue:

$to_array = explode(',', $to);
foreach($to_array as $address)
{
    $mail->addAddress($address, 'Web Enquiry');
}

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(