Programs & Examples On #Jsse

JSSE is a Java implementation of Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols. Its functionality includes data encryption, server authentication, message integrity, and optional client authentication.

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

scp via java

This is high-level solution, no need to reinvent. Quick and dirty!

1) First, go to http://ant.apache.org/bindownload.cgi and download latest Apache Ant binary. (nowadays, apache-ant-1.9.4-bin.zip).

2) Extract the downloaded file and find the JAR ant-jsch.jar ("apache-ant-1.9.4/lib/ant-jsch.jar"). Add this JAR in your project. Also ant-launcher.jar and ant.jar.

3) Go to Jcraft jsch SouceForge Project and download the jar. Nowadays, jsch-0.1.52.jar. Also Add this JAR in your project.

Now, can you easyly use into java code the Ant Classes Scp for copy files over network or SSHExec for commands in SSH servers.

4) Code Example Scp:

// This make scp copy of 
// one local file to remote dir

org.apache.tools.ant.taskdefs.optional.ssh.Scp scp = new Scp();
int portSSH = 22;
String srvrSSH = "ssh.your.domain";
String userSSH = "anyuser"; 
String pswdSSH = new String ( jPasswordField1.getPassword() );
String localFile = "C:\\localfile.txt";
String remoteDir = "/uploads/";

scp.setPort( portSSH );
scp.setLocalFile( localFile );
scp.setTodir( userSSH + ":" + pswdSSH + "@" + srvrSSH + ":" + remoteDir );
scp.setProject( new Project() );
scp.setTrust( true );
scp.execute();

java - path to trustStore - set property doesn't work?

Both

-Djavax.net.ssl.trustStore=path/to/trustStore.jks

and

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

Java client certificates over HTTPS/SSL

If you are dealing with a web service call using the Axis framework, there is a much simpler answer. If all want is for your client to be able to call the SSL web service and ignore SSL certificate errors, just put this statement before you invoke any web services:

System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");

The usual disclaimers about this being a Very Bad Thing to do in a production environment apply.

I found this at the Axis wiki.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I'm using apache-tomcat-7.0.70 with jdk1.7.0_45 and none of the solutions here and elsewhere on stackoverflow worked for me. Just sharing this solution as it hopefully might help someone as this is very high on Google's search

What worked is doing BOTH of these steps:

  1. Starting my tomcat with "export JAVA_OPTS="$JAVA_OPTS -Dhttps.protocols=TLSv1.2" by adding it to tomcat/bin/setenv.sh (Syntax slightly different on Windows)

  2. Manually building/forcing HttpClients or anything else you need with the TLS1.2 protocol:

    Context ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
    HttpClient httpClient = HttpClientBuilder.create().setSslcontext(ctx).build();
    HttpPost httppost = new HttpPost(scsTokenVerificationUrl);
    
    List<NameValuePair> paramsAccessToken = new ArrayList<NameValuePair>(2);
    paramsAccessToken.add(new BasicNameValuePair("token", token));
    paramsAccessToken.add(new BasicNameValuePair("client_id", scsClientId));
    paramsAccessToken.add(new BasicNameValuePair("secret", scsClientSecret));
    httppost.setEntity(new UrlEncodedFormEntity(paramsAccessToken, "utf-8"));
    
    //Execute and get the response.
    HttpResponse httpResponseAccessToken = httpClientAccessToken.execute(httppost);
    
    String responseJsonAccessToken = EntityUtils.toString(httpResponseAccessToken.getEntity());
    

IOS - How to segue programmatically using swift

You can do this thing using performSegueWithIdentifier function.

Screenshot

Syntax :

func performSegueWithIdentifier(identifier: String, sender: AnyObject?)

Example :

 performSegueWithIdentifier("homeScreenVC", sender: nil)

How to get the unix timestamp in C#

I used this after struggling for a while, it caters to the timezone offset as well:

    public double Convert_DatTime_To_UNIXDATETIME(DateTime dt)
    {
        System.DateTime from_date = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        double unix_time_since = dt.Subtract(from_date).TotalMilliseconds;

        TimeSpan ts_offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

        double offset = ts_offset.TotalMilliseconds;

        return unix_time_since - offset;
    }

Difference between using bean id and name in Spring configuration file

let me answer below question

Is there any difference between using an id attribute and using a name attribute on a <bean> tag,

There is no difference. you will experience same effect when id or name is used on a <bean> tag .

How?

Both id and name attributes are giving us a means to provide identifier value to a bean (For this moment, think id means id but not identifier). In both the cases, you will see same result if you call applicationContext.getBean("bean-identifier"); .

Take @Bean, the java equivalent of <bean> tag, you wont find an id attribute. you can give your identifier value to @Bean only through name attribute.

Let me explain it through an example :
Take this configuration file, let's call it as spring1.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
  <bean id="foo" class="com.intertech.Foo"></bean>
  <bean id="bar" class="com.intertech.Bar"></bean>
</beans>

Spring returns Foo object for, Foo f = (Foo) context.getBean("foo"); . Replace id="foo" with name="foo" in the above spring1.xml, You will still see the same result.

Define your xml configuration like,

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
  <bean id="fooIdentifier" class="com.intertech.Foo"></bean>
  <bean name="fooIdentifier" class="com.intertech.Foo"></bean>
</beans>

You will get BeanDefinitionParsingException. It will say, Bean name 'fooIdentifier' is already used in this element. By the way, This is the same exception you will see if you have below config
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>


If you keep both id and name to the bean tag, the bean is said to have 2 identifiers. you can get the same bean with any identifier. take config as

<?xml version="1.0" encoding="UTF-8"?><br>
<beans ...>
  <bean id="fooById" name="fooByName" class="com.intertech.Foo"></bean>
  <bean id="bar" class="com.intertech.Bar"></bean>
</beans>

the following code prints true

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(...);
Foo fooById = (Foo) context.getBean("fooById")// returns Foo object;
Foo fooByName = (Foo) context.getBean("fooByName")// returns Foo object;
System.out.println(fooById == fooByName) //true

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

Maybe you can refer to : http://msdn.microsoft.com/en-us/library/ms731364.aspx My solution is to change 2 properties authenticationScheme and proxyAuthenticationScheme to "Ntlm", and then it works.

PS: My environment is as follow - Server side: .net 2.0 ASMX - Client side: .net 4

Using reCAPTCHA on localhost

This worked for me:

"With the following test keys, you will always get No CAPTCHA and all verification requests will pass.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI

Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

The reCAPTCHA widget will show a warning message to claim that it's only for testing purpose. Please do not use these keys for your production traffic."

Extracted from here: https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do

BR!

Warning: Found conflicts between different versions of the same dependent assembly

I just had this warning message and cleaned the solution and recompiled (Build -> Clean Solution) and it went away.

Wait for page load in Selenium

private static void checkPageIsReady(WebDriver driver) {
    JavascriptExecutor js = (JavascriptExecutor) driver;

    // Initially bellow given if condition will check ready state of page.
    if (js.executeScript("return document.readyState").toString().equals("complete")) {
        System.out.println("Page Is loaded.");
        return;
    }

    // This loop will rotate for 25 times to check If page Is ready after
    // every 1 second.
    // You can replace your value with 25 If you wants to Increase or
    // decrease wait time.
    for (int i = 0; i < 25; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        // To check page ready state.
        if (js.executeScript("return document.readyState").toString().equals("complete")) {
            break;
        }
    }
}

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Test if number is odd or even

Try this one with #Input field

<?php
    //checking even and odd
    echo '<form action="" method="post">';
    echo "<input type='text' name='num'>\n";
    echo "<button type='submit' name='submit'>Check</button>\n";
    echo "</form>";

    $num = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["num"])) {
        $numErr = "<span style ='color: red;'>Number is required.</span>";
        echo $numErr;
        die();
      } else {
          $num = $_POST["num"];
      }


    $even = ($num % 2 == 0);
    $odd = ($num % 2 != 0);
    if ($num > 0){
        if($even){
            echo "Number is even.";
        } else {
            echo "Number is odd.";
        }
    } else {
        echo "Not a number.";
    }
    }
?>

How do I Merge two Arrays in VBA?

Following the @johannes solution, but merging without loosing data (it was missing first elements):

    Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant

    Dim returnThis() As Variant
    Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
    len1 = UBound(arr1)
    len2 = UBound(arr2)
    lenRe = len1 + len2 + 1
    ReDim returnThis(0 To lenRe)
    counter = 0

    For counter = 0 To len1 'get first array in returnThis
        returnThis(counter) = arr1(counter)
    Next


    For counter = 0 To len2 'get the second array in returnThis
        returnThis(counter + len1 + 1) = arr2(counter)
    Next
mergeArrays = returnThis
End Function

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>

Could not find module FindOpenCV.cmake ( Error in configuration process)

I faced the same error. In my case this "OpenCVConfig.cmake" file is located in /usr/local/share/OpenCV. In CMakeLists.txt add the line

set(OpenCV_DIR /usr/local/share/OpenCV)

as suggested by the error message.

.mp4 file not playing in chrome

Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.

Adding a tooltip to an input box

If you are using bootstrap (I am using version 4.0), feel free to try the following code.

<input data-toggle="tooltip" data-placement="top" title="This is the text of the tooltip" value="44"/>

data-placement can be top, right, bottom or left

print call stack in C or C++

There is no standardized way to do that. For windows the functionality is provided in the DbgHelp library

How do you get current active/default Environment profile programmatically in Spring?

To tweak a bit in order to handle the case where the variable is not set you could use a default value:

@Value("${spring.profiles.active:unknown}")
private String activeProfile;

This way if spring.profiles.active is set, it will take it else it will take the default value unknown.

So no exception will be triggered. And no need to force add something like @ActiveProfiles("test") in your test to make it pass.

Removing Spaces from a String in C?

Here is the simplest thing i could think of. Note that this program uses second command line argument (argv[1]) as a line to delete whitespaces from.

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

/*The function itself with debug printing to help you trace through it.*/

char* trim(const char* str)
{
    char* res = malloc(sizeof(str) + 1);
    char* copy = malloc(sizeof(str) + 1);
    copy = strncpy(copy, str, strlen(str) + 1);
    int index = 0;

    for (int i = 0; i < strlen(copy) + 1; i++) {
        if (copy[i] != ' ')
        {
            res[index] = copy[i];
            index++;
        }
        printf("End of iteration %d\n", i);
        printf("Here is the initial line: %s\n", copy);
        printf("Here is the resulting line: %s\n", res);
        printf("\n");
    }
    return res;
}

int main(int argc, char* argv[])
{
    //trim function test

    const char* line = argv[1];
    printf("Here is the line: %s\n", line);

    char* res = malloc(sizeof(line) + 1);
    res = trim(line);

    printf("\nAnd here is the formatted line: %s\n", res);

    return 0;
}

Quick easy way to migrate SQLite3 to MySQL?

I recently had to migrate from MySQL to JavaDB for a project that our team is working on. I found a Java library written by Apache called DdlUtils that made this pretty easy. It provides an API that lets you do the following:

  1. Discover a database's schema and export it as an XML file.
  2. Modify a DB based upon this schema.
  3. Import records from one DB to another, assuming they have the same schema.

The tools that we ended up with weren't completely automated, but they worked pretty well. Even if your application is not in Java, it shouldn't be too difficult to whip up a few small tools to do a one-time migration. I think I was able to pull of our migration with less than 150 lines of code.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

My solution based on the ideas above.

function pageLoad() {
    var element = document.querySelector('table[id*=_fixedTable] > tbody > tr:last-child > td:last-child > div');
    if (element) {
        element.style.overflow = "visible";
    } 
}

It's not limited to a certain id plus you don't need to include any other library such as jQuery.

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Jquery UI Datepicker not displaying

Try putting the z-index of your datepicker css a lot higher (eg z-index: 1000). The datepicker is probably shown under your original content. I had the same problem and this helped me out.

How to create a string with format?

The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again.

Default value in Doctrine

You can do it using xml as well:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

Python Variable Declaration

For scoping purpose, I use:

custom_object = None

Convert MySql DateTime stamp into JavaScript's Date format

A quick search in google provided this:

 function mysqlTimeStampToDate(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
  }

Source:http://snippets.dzone.com/posts/show/4132

NodeJS - Error installing with NPM

As commented below you may not need to install VS on windows, check this out

https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245

UPDATED 02/2016

Some npm plugins need node-gyp to be installed.

However, node-gyp has it's own dependencies (from the github page):

enter image description here

UPDATED 09/2016

If you're using Windows you can now install all node-gyp dependencies with single command (NOTE: Run As Admin in Windows PowerShell):

 $ npm install --global --production windows-build-tools

and then install the package

 $ npm install --global node-gyp

UPDATED 06/2018

https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383

Delete your $HOME/.node-gyp directory and try again.

See full documentation here: node-gyp

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Disable all dialog boxes in Excel while running VB script?

Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?

As so:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False, _
            ConflictResolution:=xlLocalSessionChanges

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

In addition to the locations listed above, the OS X version of Perl also has two more ways:

  1. The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.

  2. The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

How do I prevent a form from being resized by the user?

There is an option in vb.net that lets you do all this.

Set <code>lock = false</code> to <code>locked = true</code>

The user wont be able to re-size the form or move it around, although there are other ways, this I think is the best.

How to set a session variable when clicking a <a> link

I had the same problem - i wanted to pass a parameter to another page by clicking a hyperlink and get the value to go to the next page (without using GET because the parameter is stored in the URL).

to those who don't understand why you would want to do this the answer is you dont want the user to see sensitive information or you dont want someone editing the GET.

well after scouring the internet it seemed it wasnt possible to make a normal hyperlink using the POST method.

And then i had a eureka moment!!!! why not just use CSS to make the submit button look like a normal hyperlink??? ...and put the value i want to pass in a hidden field

i tried it and it works. you can see an exaple here http://paulyouthed.com/test/css-button-that-looks-like-hyperlink.php

the basic code for the form is:

    <form enctype="multipart/form-data" action="page-to-pass-to.php" method="post">
                        <input type="hidden" name="post-variable-name" value="value-you-want-pass"/>
                        <input type="submit" name="whatever" value="text-to-display" id="hyperlink-style-button"/>
                </form>

the basic css is:

    #hyperlink-style-button{
      background:none;
      border:0;
      color:#666;
      text-decoration:underline;
    }

    #hyperlink-style-button:hover{
      background:none;
      border:0;
      color:#666;
      text-decoration:none;
      cursor:pointer;
      cursor:hand;
    }

Return array from function

At a minimum, change this:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

To this:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

There are a couple fixes to point out. First, images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs. Second, you want to return an Object, not an Array. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object();.

After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

Getting Google+ profile picture url with user_id

You can get the URL for the profile image using the people.get method of the Google+ API. That does require an extra round trip, but is the most reliable way to get the image.

You technically can also use the URL https://s2.googleusercontent.com/s2/photos/profile/{id}?sz={size} which will then redirect to the final URL. {id} is the Google user ID or one of the old Google Profiles usernames (they still exist for users who had them, but I don't think you can create new ones anymore). {size} is the desired size of the photo in pixels. I'm almost certain this is not a documented, supported feature, so I wouldn't rely on it for anything important as it may go away at anytime without notice. But for quick prototypes or small one-off applications, it may be sufficient.

How to do "If Clicked Else .."

You should avoid using global vars, and prefer using .data()

So, you'd do:

jQuery('#id').click(function(){
  $(this).data('clicked', true);
});

Then, to check if it was clicked and perform an action:

if(jQuery('#id').data('clicked')) {
    //clicked element, do-some-stuff
} else {
    //run function2
}

Hope this helps. Cheers

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

Using margin / padding to space <span> from the rest of the <p>

Add this style to your span:

position:relative; 
top: 10px;

Demo: http://jsfiddle.net/BqTUS/3/

How can I stop a running MySQL query?

mysql>show processlist;

mysql> kill "number from first col";

Configure Flask dev server to be visible across the network

For me i followed the above answer and modified it a bit:

  1. Just grab your ipv4 address using ipconfig on command prompt
  2. Go to the file in which flask code is present
  3. In main function write app.run(host= 'your ipv4 address')

Eg:

enter image description here

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

MySQL: How to set the Primary Key on phpMyAdmin?

You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.

TypeError: $(...).on is not a function

This problem is solved, in my case, by encapsulating my jQuery in:

(function($) {
//my jquery 
})(jQuery);

Comparing two dictionaries and checking how many (key, value) pairs are equal

Here is my answer, use a recursize way:

def dict_equals(da, db):
    if not isinstance(da, dict) or not isinstance(db, dict):
        return False
    if len(da) != len(db):
        return False
    for da_key in da:
        if da_key not in db:
            return False
        if not isinstance(db[da_key], type(da[da_key])):
            return False
        if isinstance(da[da_key], dict):
            res = dict_equals(da[da_key], db[da_key])
            if res is False:
                return False
        elif da[da_key] != db[da_key]:
            return False
    return True

a = {1:{2:3, 'name': 'cc', "dd": {3:4, 21:"nm"}}}
b = {1:{2:3, 'name': 'cc', "dd": {3:4, 21:"nm"}}}
print dict_equals(a, b)

Hope that helps!

MySQL dump by query

Dump a table using a where query:

mysqldump mydatabase mytable --where="mycolumn = myvalue" --no-create-info > data.sql

Dump an entire table:

mysqldump mydatabase mytable > data.sql

Notes:

  • Replace mydatabase, mytable, and the where statement with your desired values.
  • By default, mysqldump will include DROP TABLE and CREATE TABLE statements in its output. Therefore, if you wish to not delete all the data in your table when restoring from the saved data file, make sure you use the --no-create-info option.
  • You may need to add the appropriate -h, -u, and -p options to the example commands above in order to specify your desired database host, user, and password, respectively.

What does java:comp/env/ do?

There is also a property resourceRef of JndiObjectFactoryBean that is, when set to true, used to automatically prepend the string java:comp/env/ if it is not already present.

<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="jdbc/loc"/>
  <property name="resourceRef" value="true"/>
</bean>

How to convert List<Integer> to int[] in Java?

I'll throw one more in here. I've noticed several uses of for loops, but you don't even need anything inside the loop. I mention this only because the original question was trying to find less verbose code.

int[] toArray(List<Integer> list) {
    int[] ret = new int[ list.size() ];
    int i = 0;
    for( Iterator<Integer> it = list.iterator(); 
         it.hasNext(); 
         ret[i++] = it.next() );
    return ret;
}

If Java allowed multiple declarations in a for loop the way C++ does, we could go a step further and do for(int i = 0, Iterator it...

In the end though (this part is just my opinion), if you are going to have a helping function or method to do something for you, just set it up and forget about it. It can be a one-liner or ten; if you'll never look at it again you won't know the difference.

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

How do I comment on the Windows command line?

Lines starting with "rem" (from the word remarks) are comments:

rem comment here
echo "hello"

JSON.stringify doesn't work with normal Javascript array

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

Python:Efficient way to check if dictionary is empty or not

As far as I know the for loop uses the iter function and you should not mess with a structure while iterating over it.

Does it have to be a dictionary? If you use a list something like this might work:

while len(my_list) > 0:
    #get last item from list
    key, value = my_list.pop()
    #do something with key and value
    #maybe
    my_list.append((key, value))

Note that my_list is a list of the tuple (key, value). The only disadvantage is that you cannot access by key.

EDIT: Nevermind, the answer above is mostly the same.

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

How to add percent sign to NSString

iOS 9.2.1, Xcode 7.2.1, ARC enabled

You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [stringTest stringByAppendingString:@"%"];
NSLog(@"%@", stringTest);

For iOS7.0+

To expand the answer to other characters that might cause you conflict you may choose to use:

- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters

Written out step by step it looks like this:

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [[stringTest stringByAppendingString:@"%"] 
             stringByAddingPercentEncodingWithAllowedCharacters:
             [NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];

NSLog(@"percent value of test: %@", stringTest);

Or short hand:

NSLog(@"percent value of test: %@", [[[[NSString stringWithFormat:@"%d", test] 
stringByAppendingString:@"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);

Thanks to all the original contributors. Hope this helps. Cheers!

Creating random colour in Java?

package com.adil.util;

/**
* The Class RandomColor.
*
* @author Adil OUIDAD
* @URL : http://kizana.fr
*/
public class RandomColor {      
    /**
    * Gets the random color.
    *
    * @return the random color
    */
    public static String getRandomColor() {
         String[] letters = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
         String color = "#";
         for (int i = 0; i < 6; i++ ) {
            color += letters[(int) Math.round(Math.random() * 15)];
         }
         return color;
    }
}

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Appending to an object

You can do this with Object.assign(). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}

alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "helloagain_again",message: "yet another message"}
} 

EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the Object.keys() function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with Object.values() and key-values pairs with Object.entries().

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

Loading PictureBox Image from resource file with path (Part 3)

It depends on your file path. For me, the current directory was [project]\bin\Debug, so I had to move to the parent folder twice.

Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;

To find your current directory, you can make a dummy label called label2 and write this:

this.label2.Text = System.IO.Directory.GetCurrentDirectory();

What is the maximum number of edges in a directed graph with n nodes?

Directed graph:

Question: What's the maximum number of edges in a directed graph with n vertices?

  • Assume there are no self-loops.
  • Assume there there is at most one edge from a given start vertex to a given end vertex.

Each edge is specified by its start vertex and end vertex. There are n choices for the start vertex. Since there are no self-loops, there are n-1 choices for the end vertex. Multiplying these together counts all possible choices.

Answer: n(n-1)

Undirected graph

Question: What's the maximum number of edges in an undirected graph with n vertices?

  • Assume there are no self-loops.
  • Assume there there is at most one edge from a given start vertex to a given end vertex.

In an undirected graph, each edge is specified by its two endpoints and order doesn't matter. The number of edges is therefore the number of subsets of size 2 chosen from the set of vertices. Since the set of vertices has size n, the number of such subsets is given by the binomial coefficient C(n,2) (also known as "n choose 2"). Using the formula for binomial coefficients, C(n,2) = n(n-1)/2.

Answer: (n*(n-1))/2

process.start() arguments

Very edge case, but I had to use a program that worked correctly only when I specified

StartInfo = {..., RedirectStandardOutput = true}

Not specifying it would result in an error. There was not even the need to read the output afterward.

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Permission is only granted to system app

Preferences --> EditorEditor --> Inspections --> Android Lint --> uncheck item Using System app permissio

getOutputStream() has already been called for this response

The issue here is that your JSP is talking directly to the response OutputStream. This technically isn't forbidden, but it's very much not a good idea.

Specifically, you call response.getOutputStream() and write data to that. Later, when the JSP engine tries to flush the response, it fails because your code has already "claimed" the response. An application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream.

You should be writing this code as a Servlet, not a JSP. JSPs are only really suitable for textual output as contained in the JSP. You can see that there's no actual text output in your JSP, it only contains java.

Shift elements in a numpy array

One way to do it without spilt the code into cases

with array:

def shift(arr, dx, default_value):
    result = np.empty_like(arr)
    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s: s if s > 0 else None
    result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
    result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]     
    return result

with matrix it can be done like this:

def shift(image, dx, dy, default_value):
    res = np.full_like(image, default_value)

    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s : s if s > 0 else None

    res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
        image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
    return res

How do I split a string on a delimiter in Bash?

A different take on Darron's answer, this is how I do it:

IN="[email protected];[email protected]"
read ADDR1 ADDR2 <<<$(IFS=";"; echo $IN)

How do I remove carriage returns with Ruby?

What do you get when you do puts lines? That will give you a clue.

By default File.open opens the file in text mode, so your \r\n characters will be automatically converted to \n. Maybe that's the reason lines are always equal to lines2. To prevent Ruby from parsing the line ends use the rb mode:

C:\> copy con lala.txt
a
file
with
many
lines
^Z

C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"
irb(main):003:0>

But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read.

Passing arguments forward to another javascript function

The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments object.

The arguments object contains one element for each actual parameter provided to the function. When you call a you supply three arguments: the numbers 1, 2, and, 3. So, arguments contains [1, 2, 3].

function a(args){
    console.log(arguments) // [1, 2, 3]
    b(arguments);
}

When you call b, however, you pass exactly one argument: a's arguments object. So arguments contains [[1, 2, 3]] (i.e. one element, which is a's arguments object, which has properties containing the original arguments to a).

function b(args){
    // arguments are lost?
    console.log(arguments) // [[1, 2, 3]]
}

a(1,2,3);

As @Nick demonstrated, you can use apply to provide a set arguments object in the call.

The following achieves the same result:

function a(args){
    b(arguments[0], arguments[1], arguments[2]); // three arguments
}

But apply is the correct solution in the general case.

Column count doesn't match value count at row 1

You can resolve the error by providing the column names you are affecting.

> INSERT INTO table_name (column1,column2,column3)
 `VALUES(50,'Jon Snow','Eye');`

please note that the semi colon should be added only after the statement providing values

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

This is how did it works like a charm.

CSS

#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;

background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}  

in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)


<div id="loader">
</div>

JS at the bottom of _layout file


<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
 $("#loader").fadeOut(1000);
</script>  

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

In case of windows if there is any space in path to jdk like ("C:\Program Files\jdk") then it doesn't work, but if we keep jdk in a location which doesn't have space then it works fine like ("C:\jdk")

Replace invalid values with None in Pandas DataFrame

df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df = df.where(df!='-', None)

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Download a file with Android, and showing the progress in a ProgressDialog

I'd recommend you to use my Project Netroid, It's based on Volley. I have added some features to it such as multi-events callback, file download management. This could be of some help.

How to get the last day of the month?

you can use relativedelta https://dateutil.readthedocs.io/en/stable/relativedelta.html month_end = <your datetime value within the month> + relativedelta(day=31) that will give you the last day.

How to know the version of pip itself

For Windows machine go to command prompt and type.

pip -V 

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Try to download binary zip (for ex. Maven 3.0.5 (Binary zip)) instead of complete source in official maven site. Also make sure that command line recognizes java and javac commands. I noticed that Maven Source zip didn't include any libraries at lib folder however Binary zip had them + in boot folder it had plexus-classworlds-2.4.jar. Perhaps the problem was with the absence of these libraries. Anyway it helped me so my M2_HOME is: C:\Program Files\Java\apache-maven-3.0.5 and at PATH I put: C:\Program Files\Java\apache-maven-3.0.5\bin.

Giving multiple conditions in for loop in Java

You can also replace complicated condition with single method call to make it less evil in maintain.

C# Iterating through an enum? (Indexing a System.Array)

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

How to store a large (10 digits) integer?

In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:

long l1 = 9999999999;  // this won't compile
long l2 = 9999999999L; // this will work

how to sort an ArrayList in ascending order using Collections and Comparator

Just throwing this out there...Can't you just do:

Collections.sort(myarrayList);

It's been awhile though...

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

Capturing "Delete" Keypress with jQuery

Javascript Keycodes

  • e.keyCode == 8 for backspace
  • e.keyCode == 46 for forward backspace or delete button in PC's

Except this detail Colin & Tod's answer is working.

How to use KeyListener

The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);
    

MySQL duplicate entry error even though there is no duplicate entry

Your code and schema are OK. You probably trying on previous version of table.

http://sqlfiddle.com/#!2/9dc64/1/0

Your table even has no UNIQUE, so that error is impossible on that table.

Backup data from that table, drop it and re-create.

Maybe you tried to run that CREATE TABLE IF NOT EXIST. It was not created, you have old version, but there was no error because of IF NOT EXIST.

You may run SQL like this to see current table structure:

DESCRIBE my_table;

Edit - added later:

Try to run this:

DROP TABLE `my_table`; --make backup - it deletes table

CREATE TABLE `my_table` (
  `number` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `money` int(11) NOT NULL,
  PRIMARY KEY (`number`,`name`),
  UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

If for any reason you cannot change the original filter mapping ("/*" in my case) and you are dispatching to an unchangeable third-party filter, you can find useful the following:

  • Intercept the path to be bypassed
  • Skip to and execute the last ring of the filter chain (the servlet itself)
  • The skipping is done via reflection, inspecting the container instances in debug mode

The following works in Weblogic 12.1.3:

      import org.apache.commons.lang3.reflect.FieldUtils;
      import javax.servlet.Filter;

      [...]

      @Override   
      public void doFilter(ServletRequest request, ServletRespons response, FilterChain chain) throws IOException, ServletException { 
          String path = ((HttpServletRequest) request).getRequestURI();

          if(!bypassSWA(path)){
              swpFilterHandler.doFilter(request, response, chain);

          } else {
              try {
                  ((Filter) (FieldUtils.readField(
                                (FieldUtils.readField(
                                        (FieldUtils.readField(chain, "filters", true)), "last", true)), "item", true)))
                  .doFilter(request, response, chain);
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              }           
          }   
      }

How can I do string interpolation in JavaScript?

Try sprintf library (a complete open source JavaScript sprintf implementation). For example:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

vsprintf takes an array of arguments and returns a formatted string.

How to disable input conditionally in vue.js

Can use this add condition.

  <el-form-item :label="Amount ($)" style="width:100%"  >
            <template slot-scope="scoped">
            <el-input-number v-model="listQuery.refAmount" :disabled="(rowData.status !== 1 ) === true" ></el-input-number>
            </template>
          </el-form-item>

run main class of Maven project

Try the maven-exec-plugin. From there:

mvn exec:java -Dexec.mainClass="com.example.Main"

This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

If you're on Windows, apply quotes for exec.mainClass and exec.args:

mvn exec:java -D"exec.mainClass"="com.example.Main"

If you're doing this regularly, you can add the parameters into the pom.xml as well:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>com.example.Main</mainClass>
    <arguments>
      <argument>foo</argument>
      <argument>bar</argument>
    </arguments>
  </configuration>
</plugin>

How to build a JSON array from mysql database

Just an update for Mysqli users :

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);

if (mysqli_connect_errno()) 
  die('Could not connect: ' . mysql_error());

$return_arr = array();

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
   }
 }

mysqli_close($base);

echo json_encode($return_arr);

How to convert a byte array to a hex string in Java?

Converts bytes data to hex characters

@param bytes byte array to be converted to hex string
@return byte String in hex format

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    }
    return new String(hexChars);
}

Regex to check with starts with http://, https:// or ftp://

If you wanna do it in case-insensitive way, this is better:

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I also tried deleting the database again, called update-database and then add-migration. I ended up with an additional migration that seems not to change anything (see below)

Based on above details, I think you have done last thing first. If you run Update database before Add-migration, it won't update the database with your migration schemas. First you need to add the migration and then run update command.

Try them in this order using package manager console.

PM> Enable-migrations //You don't need this as you have already done it
PM> Add-migration Give_it_a_name
PM> Update-database

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

How do I clone a subdirectory only of a Git repository?

While I hate actually having to use svn when dealing with git repos :/ I use this all the time;

function git-scp() (
  URL="$1" && shift 1
  svn export ${URL/blob\/master/trunk}
)

This allows you to copy out from the github url without modification. Usage;

--- /tmp » git-scp https://github.com/dgraph-io/dgraph/blob/master/contrib/config/kubernetes/helm                                                                                                                  1 ?
A    helm
A    helm/Chart.yaml
A    helm/README.md
A    helm/values.yaml
Exported revision 6367.

--- /tmp » ls | grep helm
Permissions Size User    Date Modified    Name
drwxr-xr-x     - anthony 2020-01-07 15:53 helm/

Searching for file in directories recursively

I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.

    private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
    {
        try
        {
            filePathCollector = filePathCollector ?? new LinkedList<string>();

            var matchingFilePaths = Directory.GetFiles(path, pattern);

            foreach(var matchingFile in matchingFilePaths)
            {
                filePathCollector.Add(matchingFile);
            }

            var subDirectories = Directory.EnumerateDirectories(path);

            foreach (var subDirectory in subDirectories)
            {
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);
            }

            return filePathCollector;
        }
        catch (Exception error)
        {
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;

            if (isIgnorableError)
            {
                return Enumerable.Empty<string>();
            }

            throw error;
        }
    }

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

How to convert a SVG to a PNG with ImageMagick?

Try svgexport:

svgexport input.svg output.png 64x
svgexport input.svg output.png 1024:1024

svgexport is a simple cross-platform command line tool that I have made for exporting svg files to jpg and png, see here for more options. To install svgexport install npm, then run:

npm install svgexport -g

Edit: If you find an issue with the library, please submit it on GitHub, thanks!

How to remove leading and trailing spaces from a string

You can use:

  • String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
  • String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
  • String.Trim - combination of the two functions above

Usage:

string txt = "                   i am a string                                    ";
char[] charsToTrim = { ' ' };    
txt = txt.Trim(charsToTrim)); // txt = "i am a string"

EDIT:

txt = txt.Replace(" ", ""); // txt = "iamastring"   

How to make a node.js application run permanently?

Forever is a very good NodeJs module to do exactly that.

Install forever by typing in the command line

$ npm install forever -g

Then use the following command to run a node.js script

$ forever start /path/to/script.js

You are good to go. Additionally you can run

$ forever list

to see all the running scripts. You can terminate any specific script by typing

$ forever stop [pid]

where [pid] is the process ID of the script you will obtain from the list command. To stop all scripts, you may type

$ forever stopall

How to delete the last row of data of a pandas dataframe

drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:

newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)

and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.

How do I convert a IPython Notebook into a Python file via commandline?

I understand this is an old thread. I have faced the same issue and wanted to convert the .pynb file to .py file via command line.

My search took me to ipynb-py-convert

By following below steps I was able to get .py file

  1. Install "pip install ipynb-py-convert"
  2. Go to the directory where the ipynb file is saved via command prompt
  3. Enter the command

> ipynb-py-convert YourFileName.ipynb YourFilename.py

Eg:. ipynb-py-convert getting-started-with-kaggle-titanic-problem.ipynb getting-started-with-kaggle-titanic-problem.py

Above command will create a python script with the name "YourFileName.py" and as per our example it will create getting-started-with-kaggle-titanic-problem.py file

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

Python: "TypeError: __str__ returned non-string" but still prints to output?

The problem that you are facing is : TypeError : str returned non-string (type NoneType)

Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error

You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it

 class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

    def __str__(self):
        return self.summary

but if the value you are returning in not of string type then you can do like this to return string value from your str function

*typeconverting the value to string that your str function returns

class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

   def __str__(self):
       return str(self.summary)
            `

use jQuery's find() on JSON object

The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/or map methods. Probably not much better than using $.each

jQuery.grep(TestObj, function(obj) {
    return obj.id === "A";
});

or

jQuery.map(TestObj, function(obj) {
    if(obj.id === "A")
         return obj; // or return obj.name, whatever.
});

Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.

But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.

function getObjects(obj, key, val) {
    var retv = [];

    if(jQuery.isPlainObject(obj))
    {
        if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
            retv.push(obj);

        var objects = jQuery.grep(obj, function(elem) {
            return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
        });

        retv.concat(jQuery.map(objects, function(elem){
            return getObjects(elem, key, val);
        }));
    }

    return retv;
}

Essentially the same as Box9's answer, but using the jQuery utility functions where useful.

········

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

You can change this by using the VM arguments as well in the launch configuration.

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You don't need to prevent this error message!
Error messages are your friends!
Without error message you'd never know what is happened.
It's all right! Any working code supposed to throw out error messages.

Though error messages needs proper handling. Usually you don't have to to take any special actions to avoid such an error messages. Just leave your code intact. But if you don't want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.

ini_set('display_errors',0);
ini_set('log_errors',1);

or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.

To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if's.
But there can be solution too - exceptions!

But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.

Using return is another method to avoid nested error messages. Here is a snippet from my database handling function:

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }
  if (!mysql_num_rows($res)) return NULL;

  //fetching goes here
  //if there was no errors only

How to pass variable number of arguments to printf/sprintf

Simple example below. Note you should pass in a larger buffer, and test to see if the buffer was large enough or not

void Log(LPCWSTR pFormat, ...) 
{
    va_list pArg;
    va_start(pArg, pFormat);
    char buf[1000];
    int len = _vsntprintf(buf, 1000, pFormat, pArg);
    va_end(pArg);
    //do something with buf
}

Git - Undo pushed commits

You can revert individual commits with:

git revert <commit_hash>

This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit and not commits after that. If you want to revert a range of commits, you can do it like this:

git revert <oldest_commit_hash>..<latest_commit_hash>

It reverts the commits between and including the specified commits.

To know the hash of the commit(s) you can use git log

Look at the git-revert man page for more information about the git revert command. Also, look at this answer for more information about reverting commits.

What is the equivalent to getLastInsertId() in Cakephp?

In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html

Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

Can you explain the flow of your application and how it relates to your problem?

ffprobe or avprobe not found. Please install one

I know the user asked this for Linux, but I had this issue in Windows (10 64bits) and found little information, so this is how I solved it:

  • Download LIBAV, I used libav-11.3-win64.7z. Just copy "avprobe.exe" and all DLLs from "/win64/usr/bin" to where "youtube-dl.exe" is.

In case LIBAV does not help, try with FFMPEG, copying the contents of the "bin" folder to where "youtube-dl.exe" is. That did not help me, but others said it did, so it may worth a try.

Hope this helps someone having the issue in Windows.

Detect if user is scrolling

this works:

window.onscroll = function (e) {  
// called when the window is scrolled.  
} 

edit:

you said this is a function in a TimeInterval..
Try doing it like so:

userHasScrolled = false;
window.onscroll = function (e)
{
    userHasScrolled = true;
}

then inside your Interval insert this:

if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Creating a copy of a database in PostgreSQL

Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:

CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;

Still, you may get:

ERROR:  source database "originaldb" is being accessed by other users

To disconnect all other users from the database, you can use this query:

SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity 
WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();

Doctrine findBy 'does not equal'

I used the QueryBuilder to get the data,

$query=$this->dm->createQueryBuilder('AppBundle:DocumentName')
             ->field('fieldName')->notEqual(null);

$data=$query->getQuery()->execute();

Matplotlib - global legend and title aside subplots

suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')

How do I include a JavaScript file in another JavaScript file?

I just wrote this JavaScript code (using Prototype for DOM manipulation):

var require = (function() {
    var _required = {};
    return (function(url, callback) {
        if (typeof url == 'object') {
            // We've (hopefully) got an array: time to chain!
            if (url.length > 1) {
                // Load the nth file as soon as everything up to the
                // n-1th one is done.
                require(url.slice(0, url.length - 1), function() {
                    require(url[url.length - 1], callback);
                });
            } else if (url.length == 1) {
                require(url[0], callback);
            }
            return;
        }
        if (typeof _required[url] == 'undefined') {
            // Haven't loaded this URL yet; gogogo!
            _required[url] = [];

            var script = new Element('script', {
                src: url,
                type: 'text/javascript'
            });
            script.observe('load', function() {
                console.log("script " + url + " loaded.");
                _required[url].each(function(cb) {
                    cb.call(); // TODO: does this execute in the right context?
                });
                _required[url] = true;
            });

            $$('head')[0].insert(script);
        } else if (typeof _required[url] == 'boolean') {
            // We already loaded the thing, so go ahead.
            if (callback) {
                callback.call();
            }
            return;
        }

        if (callback) {
            _required[url].push(callback);
        }
    });
})();

Usage:

<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
    require(['foo.js','bar.js'], function () {
        /* Use foo.js and bar.js here */
    });
</script>

Gist: http://gist.github.com/284442.

JavaScript Nested function

Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

Find out how much memory is being used by an object in Python

There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).

There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.

You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

This one also works

  1. Remove the "php.executablePath" line from the VS code settings.

  2. Then add the xampp php path to the System variables

enter image description here

enter image description here

After that restart the Visual Studio Code

Splitting String with delimiter

def (value1, value2) = '1128-2'.split('-') should work.

Can anyone please try this in Groovy Console?

def (v, z) =  '1128-2'.split('-')

assert v == '1128'
assert z == '2'

How do I create and store md5 passwords in mysql

just get the hash by following line and store it into the database:

$encryptedValue = md5("YOUR STRING");

Flutter.io Android License Status Unknown

If you updated the android SDK, the licenses may have changed. Depending on how you did the update you may or may not have been prompted to accept the changes, or maybe it just doesn't save the fact that you did accept them in a way flutter can understand.

To resolve, try running

flutter doctor --android-licenses

This should prompt you to accept licenses (it may ask you first, in case just type y and press enter - although it should tell you that).

If you still have problems after doing that, it might be worth either opening a new bug in the Flutter Github repository, or adding a comment on an existing issue like this one as it may be what you're seeing.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused

When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.

The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

How do I display todays date on SSRS report?

You can also drag and drop "Execution Time" item from Built-in Fields list.

Php - testing if a radio button is selected and get the value

my form:

<form method="post" action="radio.php">
   select your gender: 
    <input type="radio" name="radioGender" value="female">
    <input type="radio" name="radioGender" value="male">
    <input type="submit" name="btnSubmit" value="submit">
</form>

my php:

   <?php
      if (isset($_POST["btnSubmit"])) {
        if (isset($_POST["radioGender"])) {
        $answer = $_POST['radioGender'];
           if ($answer == "female") {
               echo "female";
           } else {
               echo "male";
           }    
        }else{
            echo "please select your gender";
             }
      }
  ?>

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

In our network I have found that restarting the Workstation service on the client computer is able to resolve this problem. This has worked in cases where a reboot of the client would also fix the problem. But restarting the service is much quicker & easier [and may work when a reboot does not].

My impression is that the local Windows PC is caching some old information and this seems to clear it out.

For information on restarting a service, see this question. It boils down to running the following commands on a command line:

C:\> net stop workstation /y
C:\> net start workstation

Note - the /y flag will force the service to stop even if this will interrupt existing connections. But otherwise it will prompt the user and wait. So this may be necessary for scripting.


Be aware that on Windows Server 2016 (+ possibly others) these commands may also stop the netlogon service. If so you will have to add: net start netlogon

mongo - couldn't connect to server 127.0.0.1:27017

The cause by me was the space - run this in the console:

df -h

or more specifically:

du -hs /var/lib/mongodb/ 

to check he disk usage. If it's ~ 99% - just clean up some space and try again!

Which MySQL data type to use for storing boolean values

BOOL and BOOLEAN are synonyms of TINYINT(1). Zero is false, anything else is true. More information here.

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

This works:

Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next() == 5) {
        iter.remove();
    }
}

I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove() functionality.

How-to turn off all SSL checks for postman for a specific site

enter image description here

This steps are used in spring boot with self signed ssl certificate implementation

if SSL turns off then HTTPS call will be worked as expected.

https://localhost:8443/test/hello

These are the steps we have to follow,

  1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

after key generation has done then copy that file in to the resource foder in your project

  1. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
  1. change your postman ssl verification settings to turn OFF

now verify the url: https://localhost:8443/test/hello

not finding android sdk (Unity)

In my case, I was trying to build and get APK for an old Unity 3D project (so that I can play the game in my Android phone). I was using the most recent Android Studio version, and all the SDK packages I could download via SDK Manager in Android Studio. SDK Packages was located in

C:/Users/Onat/AppData/Local/Android/Sdk And the error message I got was the same except the JDK (Java Development Kit) version "jdk-12.0.2" . JDK was located in

C:\Program Files\Java\jdk-12.0.2 And Environment Variable in Windows was JAVA_HOME : C:\Program Files\Java\jdk-12.0.2

After 3 hours of research, I found out that Unity does not support JDK 10. As told in https://forum.unity.com/threads/gradle-build-failed-error-could-not-determine-java-version-from-10-0-1.532169/ . My suggestion is:

1.Uninstall unwanted JDK if you have one installed already. https://www.java.com/tr/download/help/uninstall_java.xml

2.Head to http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

3.Login to/Open a Oracle account if not already logged in.

4.Download the older but functional JDK 8 for your computer set-up(32 bit/64 bit, Windows/Linux etc.)

5.Install the JDK. Remember the installation path. (https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/)

6.If you are using Windows, Open Environment Variables and change Java Path via Right click My Computer/This PC>Properties>Advanced System Settings>Environment Variables>New>Variable Name: JAVA_HOME>Variable Value: [YOUR JDK Path, Mine was "C:\Program Files\Java\jdk1.8.0_221"]

7.In Unity 3D, press Edit > Preferences > External Tools and fill in the JDK path (Mine was "C:\Program Files\Java\jdk1.8.0_221").

8.Also, in the same pop-up, edit SDK Path. (Get it from Android Studio > SDK Manager > Android SDK > Android SDK Location.)

9.If needed, restart your computer for changes to take effect.

How do I clone a job in Jenkins?

New Item>Project Name = abc > Instead of Freestyle job, select Copy from job name of already existing jobs

If you are inside the folder that you want to copy out of the directory then use ../.

Java logical operator short-circuiting

Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.

Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.

It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:

 if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

How to grep recursively, but only in files with certain extensions?

I am aware this question is a bit dated, but I would like to share the method I normally use to find .c and .h files:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"

or if you need the line number as well:

tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"

Creating runnable JAR with Gradle

You can use the SpringBoot plugin:

plugins {
  id "org.springframework.boot" version "2.2.2.RELEASE"
}

Create the jar

gradle assemble

And then run it

java -jar build/libs/*.jar

Note: your project does NOT need to be a SpringBoot project to use this plugin.

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

Write HTML file using Java

If you are willing to use Groovy, the MarkupBuilder is very convenient for this sort of thing, but I don't know that Java has anything like it.

http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder

How to get current local date and time in Kotlin

checkout these easy to use Kotlin extensions for date format

fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
    return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}

fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

How do I tell matplotlib that I am done with a plot?

Just enter plt.hold(False) before the first plt.plot, and you can stick to your original code.

Is there a native jQuery function to switch elements?

I wanted a solution witch does not use clone() as it has side effect with attached events, here is what I ended up to do

jQuery.fn.swapWith = function(target) {
    if (target.prev().is(this)) {
        target.insertBefore(this);
        return;
    }
    if (target.next().is(this)) {
        target.insertAfter(this);
        return
    }

    var this_to, this_to_obj,
        target_to, target_to_obj;

    if (target.prev().length == 0) {
        this_to = 'before';
        this_to_obj = target.next();
    }
    else {
        this_to = 'after';
        this_to_obj = target.prev();
    }
    if (jQuery(this).prev().length == 0) {
        target_to = 'before';
        target_to_obj = jQuery(this).next();
    }
    else {
        target_to = 'after';
        target_to_obj = jQuery(this).prev();
    }

    if (target_to == 'after') {
        target.insertAfter(target_to_obj);
    }
    else {
        target.insertBefore(target_to_obj);
    }
    if (this_to == 'after') {
        jQuery(this).insertAfter(this_to_obj);
    }
    else {
        jQuery(this).insertBefore(this_to_obj);
    }

    return this;
};

it must not be used with jQuery objects containing more than one DOM element

How to delete an SMS from the inbox in Android programmatically?

Use this function to delete specific message thread or modify according your needs:

public void delete_thread(String thread) 
{ 
  Cursor c = getApplicationContext().getContentResolver().query(
  Uri.parse("content://sms/"),new String[] { 
  "_id", "thread_id", "address", "person", "date","body" }, null, null, null);

 try {
  while (c.moveToNext()) 
      {
    int id = c.getInt(0);
    String address = c.getString(2);
    if (address.equals(thread)) 
        {
     getApplicationContext().getContentResolver().delete(
     Uri.parse("content://sms/" + id), null, null);
    }

       }
} catch (Exception e) {

  }
}

Call this function simply below:

delete_thread("54263726");//you can pass any number or thread id here

Don't forget to add android mainfest permission below:

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

substring index range

public String substring(int beginIndex, int endIndex)

beginIndex—the begin index, inclusive.

endIndex—the end index, exclusive.

Example:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3, 8));
    }
 }

Output: "lo Wo"

From 3 to 7 index.

Also there is another kind of substring() method:

public String substring(int beginIndex)

beginIndex—the begin index, inclusive. Returns a sub string starting from beginIndex to the end of the main String.

Example:

public class Test {

    public static void main(String args[]) {
        String Str = new String("Hello World");

        System.out.println(Str.substring(3));
    }
}

Output: "lo World"

From 3 to the last index.

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

How to set environment variable for everyone under my linux system?

Amazingly, Unix and Linux do not actually have a place to set global environment variables. The best you can do is arrange for any specific shell to have a site-specific initialization.

If you put it in /etc/profile, that will take care of things for most posix-compatible shell users. This is probably "good enough" for non-critical purposes.

But anyone with a csh or tcsh shell won't see it, and I don't believe csh has a global initialization file.

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

Notepad++ Multi editing

Notepad++ only has column editing. This is not completely the same as multiple cursors.

Sublime Text has a marvelous implementation of this, might be worth checking out...
It's a relatively new editor (2011) that is gaining popularity quite fast: http://www.google.com/trends/explore#q=Notepad%2B%2B%2C%20Sublime%20Text&cmpt=q

Edit: Apparently somewhere around Notepad++ version 6.x multi-cursor editing got added, but there are still a few more advanced features for it in Sublime, like "select next occurrence".

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Does SVG support embedding of bitmap images?

You can use a data: URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?

C#: what is the easiest way to subtract time?

This works too:

System.DateTime dTime = DateTime.Now();

// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0); 

System.DateTime result = dTime + tSpan;

To subtract a year:

DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

How can I get nth element from a list?

Haskell's standard list data type forall t. [t] in implementation closely resembles a canonical C linked list, and shares its essentially properties. Linked lists are very different from arrays. Most notably, access by index is a O(n) linear-, instead of a O(1) constant-time operation.

If you require frequent random access, consider the Data.Array standard.

!! is an unsafe partially defined function, provoking a crash for out-of-range indices. Be aware that the standard library contains some such partial functions (head, last, etc.). For safety, use an option type Maybe, or the Safe module.

Example of a reasonably efficient, robust total (for indices = 0) indexing function:

data Maybe a = Nothing | Just a

lookup :: Int -> [a] -> Maybe a
lookup _ []       = Nothing
lookup 0 (x : _)  = Just x
lookup i (_ : xs) = lookup (i - 1) xs

Working with linked lists, often ordinals are convenient:

nth :: Int -> [a] -> Maybe a
nth _ []       = Nothing
nth 1 (x : _)  = Just x
nth n (_ : xs) = nth (n - 1) xs

How to change the background color of a UIButton while it's highlighted?

My best solution for Swift 3+ without subclassing.

extension UIButton {
  func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContext(rect.size)
    color.setFill()
    UIRectFill(rect)
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(colorImage, for: state)
  }
}

With this extension it's easy to manage colors for different states and it will fade your normal color automatically in case highlighted color is not provided.

button.setBackgroundColor(.red, for: .normal)

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

Statement interface Doc

SUMMARY: void setFetchSize(int rows) Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.

Read this ebook J2EE and beyond By Art Taylor

Adding values to Arraylist

Two last variants are the same, int is wrapped to Integer automatically where you need an Object. If you not write any class in <> it will be Object by default. So there is no difference, but it will be better to understanding if you write Object.

How ViewBag in ASP.NET MVC works

ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData. ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.

e.g: 1. Creating ViewBag: ViewBag.FirstName="John";

  1. Accessing View: @ViewBag.FirstName.

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

How to set a transparent background of JPanel?

In my particular case it was easier to do this:

 panel.setOpaque(true);
 panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

If it's bigin when you try to acces to joomla administrator panel, Just a username and password problem !! You have just to update a jos_user in your joomla database.

Go to your joomla web site directory and open a configuration.php with bloc note or note pad to show what database name your joomla administrator site use. You have to find a line who have:

public $user = 'joomlauser251';           //MySQL username

In my case joomlauser251 is my DB name.

Login to your mysql:

 mysql -uyourusername -pyourpassword

Select database for your joomla:

use joomlauser251;

Change password for admin:

UPDATE jos_users SET password=MD5(‘NewPassword’) WHERE username=’admin’;

And retry to acces again.

That’s all !!!

Manually adding a Userscript to Google Chrome

Share and install userscript with one-click

To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js filename to get on-click installation when you click on Raw and get this page:

Installation page

How to do this ?

  1. Name your gist <filename>.user.js, write your code and click on "Create".
    Make file on gist

  2. In the gist page, click on Raw to get installation page (first screen).
    Raw button

  3. Check the code and install it.

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

How can I echo HTML in PHP?

Don't echo out HTML.

If you want to use

<?php echo "<h1>  $title; </h1>"; ?>

you should be doing this:

<h1><?= $title;?></h1>

Clearing an HTML file upload field via JavaScript

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.

Given a form like:

<form> 
    <input id="fileInput" name="fileInput" type="file" /> 
</form>

The straight DOM way:

function clearFileInput(id) 
{ 
    var oldInput = document.getElementById(id); 

    var newInput = document.createElement("input"); 

    newInput.type = "file"; 
    newInput.id = oldInput.id; 
    newInput.name = oldInput.name; 
    newInput.className = oldInput.className; 
    newInput.style.cssText = oldInput.style.cssText; 
    // TODO: copy any other relevant attributes 

    oldInput.parentNode.replaceChild(newInput, oldInput); 
}

clearFileInput("fileInput");

Simple DOM way. This may not work in older browsers that don't like file inputs:

oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);

The jQuery way:

$("#fileInput").replaceWith($("#fileInput").val('').clone(true));

// .val('') required for FF compatibility as per @nmit026

Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947

Determining 32 vs 64 bit in C++

You should be able to use the macros defined in stdint.h. In particular INTPTR_MAX is exactly the value you need.

#include <cstdint>
#if INTPTR_MAX == INT32_MAX
    #define THIS_IS_32_BIT_ENVIRONMENT
#elif INTPTR_MAX == INT64_MAX
    #define THIS_IS_64_BIT_ENVIRONMENT
#else
    #error "Environment not 32 or 64-bit."
#endif

Some (all?) versions of Microsoft's compiler don't come with stdint.h. Not sure why, since it's a standard file. Here's a version you can use: http://msinttypes.googlecode.com/svn/trunk/stdint.h

Angular, Http GET with parameter?

For Angular 9+ You can add headers and params directly without the key-value notion:

const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params}); 

In C#, how to check if a TCP port is available?

TcpClient c;

//I want to check here if port is free.
c = new TcpClient(ip, port);

...how can I first check if a certain port is free on my machine?

I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free. – Ali

You have misunderstood what's happening here.

TcpClient(...) parameters are of server ip and server port you wish to connect to.

The TcpClient selects a transient local port from the available pool to communicate to the server. There's no need to check for the availability of the local port as it is automatically handled by the winsock layer.

In case you can't connect to the server using the above code fragment, the problem could be one or more of several. (i.e. server ip and/or port is wrong, remote server not available, etc..)

Force uninstall of Visual Studio

I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:

D:\vs_ultimate.exe /uninstall /force

Where D: is the location of your installation media (mounted iso, etc).

You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.

EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.

http://blogs.msdn.com/b/heaths/archive/2015/07/17/removing-visual-studio-components-left-behind-after-an-uninstall.aspx

Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.

Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.

Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.

Good luck!

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

How do I print the elements of a C++ vector in GDB?

To view vector std::vector myVector contents, just type in GDB:

(gdb) print myVector

This will produce an output similar to:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30}

To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki.

What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).

Convert a Python int into a big-endian string of bytes

This is fast and works for small and (arbitrary) large ints:

def Dump(n): 
  s = '%x' % n
  if len(s) & 1:
    s = '0' + s
  return s.decode('hex')
print repr(Dump(1245427))  #: '\x13\x00\xf3'

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

How to tell if node.js is installed or not

Ctrl + R - to open the command line and then writes:

node -v

Remove all unused resources from an android project

On Windows: Press Ctlr+Alt+Shift+i one dialog box will appear, then type unused, you will find number of options select and remove unused resources

What causes a TCP/IP reset (RST) flag to be sent?

If there is a router doing NAT, especially a low end router with few resources, it will age the oldest TCP sessions first. To do this it sets the RST flag in the packet that effectively tells the receiving station to (very ungracefully) close the connection. this is done to save resources.

Why does the order in which libraries are linked sometimes cause errors in GCC?

If you add -Wl,--start-group to the linker flags it does not care which order they're in or if there are circular dependencies.

On Qt this means adding:

QMAKE_LFLAGS += -Wl,--start-group

Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).

How to sort Counter by value? - python

Yes:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})

Using the sorted keyword key and a lambda function:

>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

This works for all dictionaries. However Counter has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

Change Circle color of radio button

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/radio"
    android:buttonTint="@color/my_color"/>

All button will change color, the circle box and the central check.

linux shell script: split string, put them in an array then loop through them

You can probably skip the step of explicitly creating an array...

One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.

Below is an example using semicolons (as you had mentioned in your question):

export IFS=";"
sentence="one;two;three"
for word in $sentence; do
  echo "$word"
done

Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).

"The Controls collection cannot be modified because the control contains code blocks"

Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind

I removed my JavaScript from the head section of page and added it to the body of the page and got it working

.Net: How do I find the .NET version?

This answer is applicable to .NET Core only!

Typing dotnet --version in your terminal of choice will print out the version of the .NET Core SDK in use.

Learn more about the dotnet command here.

Unable to open debugger port in IntelliJ

Add the following parameter debug-enabled="true" to this line in the glassfish configuration. Example:

<java-config  debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009" debug-enabled="true"
  system-classpath="" native-library-path-prefix="D:\Project\lib\windows\64bit" classpath-suffix="">

Start and stop the glassfish domain or service which was using this configuration.

Extracting specific columns in numpy array

One more thing you should pay attention to when selecting columns from N-D array using a list like this:

data[:,:,[1,9]]

If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:

print data.shape            # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape       # gives [2,20] instead of [20,2]!!

How can I run NUnit tests in Visual Studio 2017?

You need to install NUnitTestAdapter. The latest version of NUnit is 3.x.y (3.6.1) and you should install NUnit3TestAdapter along with NUnit 3.x.y

To install NUnit3TestAdapter in Visual Studio 2017, follow the steps below:

  1. Right click on menu Project ? click "Manage NuGet Packages..." from the context menu
  2. Go to the Browse tab and search for NUnit
  3. Select NUnit3TestAdapter ? click Install at the right side ? click OK from the Preview pop up

Enter image description here

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

Check whether user has a Chrome extension installed

If you have control over the Chrome extension, you can try what I did:

// Inside Chrome extension
var div = document.createElement('div');
div.setAttribute('id', 'myapp-extension-installed-div');
document.getElementsByTagName('body')[0].appendChild(div);

And then:

// On web page that needs to detect extension
if ($('#myapp-extension-installed-div').length) {

}

It feels a little hacky, but I couldn't get the other methods to work, and I worry about Chrome changing its API here. It's doubtful this method will stop working any time soon.

Display all dataframe columns in a Jupyter Python Notebook

Python 3.x for large (but not too large) DataFrames

Maybe because I have an older version of pandas but on Jupyter notebook this work for me

import pandas as pd
from IPython.core.display import HTML

df=pd.read_pickle('Data1')
display(HTML(df.to_html()))

Deserializing a JSON into a JavaScript object

Do like jQuery does! (the essence)

function parseJSON(data) {
    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); 
}
// testing
obj = parseJSON('{"name":"John"}');
alert(obj.name);

This way you don't need any external library and it still works on old browsers.

How to iterate through LinkedHashMap with lists as values

// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}

Unable to import path from django.urls

You need Django version 2

pip install --upgrade django
pip3 install --upgrade django

python -m django --version # 2.0.2
python3 -m django --version # 2.0.2

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

How to resolve Unneccessary Stubbing exception

Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch() elsewhere. More like repeatedly creating the stubs of the same method.

Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.

Consider the below Test Class for example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
    @Mock
    Service1 svc1Mock1;

    @Mock
    Service2 svc2Mock2;

    @InjectMock
    TestClass class;

    //Assume you have many dependencies and you want to set up all the stubs 
    //in one place assuming that all your tests need these stubs.

    //I know that any initialization code for the test can/should be in a 
    //@Before method. Lets assume there is another method just to create 
    //your stubs.

    public void setUpRequiredStubs() {
        when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
        when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
    }

    @Test
    public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
        // You forget that you defined the stub for svcMock1.someMethod or 
        //thought you could redefine it. Well you cannot. That's going to be 
        //a problem and would throw your UnnecessaryStubbingException.
       when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
       setUpRequiredStubs();
    }
}

I would rather considering refactoring your tests to stub where necessary.

Twitter Bootstrap modal: How to remove Slide down effect

just remove 'fade' class from modal class

class="modal fade bs-example-modal-lg"

as

class="modal bs-example-modal-lg"