Programs & Examples On #Password policy

Vector of structs initialization

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

But I found new to do this using default_structure_element like following...

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

It should be CascadeType.Merge, in that case it will update if the record already exists.

jQuery multiple events to trigger the same function

You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

Another option is to use chaining support of jquery api.

Android turn On/Off WiFi HotSpot programmatically

Here's the complete solution if you want to implement the wifi hotspot feature programmatically in your android app.

SOLUTION FOR API < 26:

For devices < API 26. There is no public API by Android for this purpose. So, in order to work with those APIs you've to access private APIs through reflection. It is not recommended but if you've no other options left, then here's a trick.

First of all, you need to have this permission in your manifest,

  <uses-permission  
  android:name="android.permission.WRITE_SETTINGS"  
  tools:ignore="ProtectedPermissions"/>

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

Here's how you can ask it on run-time:

 private boolean showWritePermissionSettings() {    
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M  
    && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { 
  if (!Settings.System.canWrite(this)) {    
    Log.v("DANG", " " + !Settings.System.canWrite(this));   
    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS); 
    intent.setData(Uri.parse("package:" + this.getPackageName()));  
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    this.startActivity(intent); 
    return false;   
  } 
}   
return true; //Permission already given 
}

You can then access the setWifiEnabled method through reflection. This returns true if the action you asked for is being process correctly i.e. enabling/disabling hotspot.

     public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) { 
 WifiManager wifiManager;
try {   
  if (enabled) { //disables wifi hotspot if it's already enabled    
    wifiManager.setWifiEnabled(false);  
  } 

   Method method = wifiManager.getClass()   
      .getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);   
  return (Boolean) method.invoke(wifiManager, wifiConfig, enabled); 
} catch (Exception e) { 
  Log.e(this.getClass().toString(), "", e); 
  return false; 
}   
}

You can also get the wificonfiguration of your hotspot through reflection. I've answered that method for this question on StackOverflow.

P.S: If you don't want to turn on hotspot programmatically, you can start this intent and open the wifi settings screen for user to turn it on manually.

SOLUTION FOR API >= 26:

Finally, android released an official API for versions >= Oreo. You can just use the public exposed API by android i.e. startLocalOnlyHotspot

It turns on a local hotspot without internet access. Which thus can be used to host a server or transfer files.

It requires Manifest.permission.CHANGE_WIFI_STATE and ACCESS_FINE_LOCATION permissions.

Here's a simple example of how you can turn on hotspot using this API.

private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;

The method to turn on hotspot:

@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {

      wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

        @Override
        public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
          super.onStarted(reservation);
          hotspotReservation = reservation;
          currentConfig = hotspotReservation.getWifiConfiguration();

          Log.v("DANG", "THE PASSWORD IS: "
              + currentConfig.preSharedKey
              + " \n SSID is : "
              + currentConfig.SSID);

          hotspotDetailsDialog();

        }

        @Override
        public void onStopped() {
          super.onStopped();
          Log.v("DANG", "Local Hotspot Stopped");
        }

        @Override
        public void onFailed(int reason) {
          super.onFailed(reason);
          Log.v("DANG", "Local Hotspot failed to start");
        }
      }, new Handler());
    }
`

Here's how you can get details of the locally created hotspot

private void hotspotDetaisDialog()
{

    Log.v(TAG, context.getString(R.string.hotspot_details_message) + "\n" + context.getString(
              R.string.hotspot_ssid_label) + " " + currentConfig.SSID + "\n" + context.getString(
              R.string.hotspot_pass_label) + " " + currentConfig.preSharedKey);

}

If it throws, a security exception even after giving the required permissions then you should try enabling your location using GPS. Here's the solution.

Recently, I've developed a demo app called Spotserve. That turns on wifi hotspot for all devices with API>=15 and hosts a demo server on that hotspot. You can check that for more details. Hope this helps!

Convert dictionary values into array

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

Virtual member call in a constructor

Because until the constructor has completed executing, the object is not fully instantiated. Any members referenced by the virtual function may not be initialised. In C++, when you are in a constructor, this only refers to the static type of the constructor you are in, and not the actual dynamic type of the object that is being created. This means that the virtual function call might not even go where you expect it to.

Mongodb service won't start

Delete the .lock file from the C:\mongodb\data\ path and then restart the mongodb service.

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Sub CopyValueWithFormatting()
    Sheet1.Range("A1").Copy
    With Sheet2.Range("B1")
        .PasteSpecial xlPasteFormats
        .PasteSpecial xlPasteValues
    End With
End Sub

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I have added a Maven/Java project with 1 Domain class with the following features:

  • Unit or Integration testing with the plugins Surefire and Failsafe.
  • Findbugs.
  • Test coverage via Jacoco.

Where are the Jacoco results? After testing and running 'mvn clean', you can find the results in 'target/site/jacoco/index.html'. Open this file in the browser.

Enjoy!

I tried to keep the project as simple as possible. The project puts many suggestions from these posts together in an example project. Thank you, contributors!

How can I change default dialog button text color in android 5

Using styles.xml (value)

Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.

<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">


        <!-- Used for the buttons -->
        <item name="colorAccent">@android:color/white</item>
        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/black</item>

        <!-- Used for the background -->
        <item name="android:background">#ffffff</item>
        <item name="android:colorPrimary">@color/white</item>
        <item name="android:colorAccent">@color/white</item>
        <item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
    </style>

Alternative (Using Java)

 @SuppressLint("ResourceAsColor")
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)

                        .setTitle("Royal Frolics")
                        .setIcon(R.mipmap.ic_launcher)
                        .setMessage(message)
                        .setPositiveButton("OK", (dialog1, which) -> {
                            //do nothing
                            result.confirm();
                        }).create();

                Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
                dialog.show();
                
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
                return true;

            }

Android ImageView Animation

Don't hard code image bounds. Just use:

RotateAnimation anim = new RotateAnimation( fromAngle, toAngle, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

How do I check if a C++ string is an int?

Ok, the way I see it you have 3 options.

1: If you simply wish to check whether the number is an integer, and don't care about converting it, but simply wish to keep it as a string and don't care about potential overflows, checking whether it matches a regex for an integer would be ideal here.

2: You can use boost::lexical_cast and then catch a potential boost::bad_lexical_cast exception to see if the conversion failed. This would work well if you can use boost and if failing the conversion is an exceptional condition.

3: Roll your own function similar to lexical_cast that checks the conversion and returns true/false depending on whether it's successful or not. This would work in case 1 & 2 doesn't fit your requirements.

How do I see if Wi-Fi is connected on Android?

Using WifiManager you can do:

WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}

The method getNeworkId returns -1 only when it's not connected to a network;

Skipping Iterations in Python

Example for Continue:

number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      continue    # continue here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 6 # Note: 5 is skipped!!
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

How to convert an NSTimeInterval (seconds) into minutes

Here's a Swift version:

func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
    return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}

Can be used like this:

let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")

Applying .gitignore to committed files

Old question, but some of us are in git-posh (powershell). This is the solution for that:

git ls-files -ci --exclude-standard | foreach { git rm --cached $_ }

How to link 2 cell of excel sheet?

I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain

How to link two (multiple) workbooks and cells in Excel...

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

UITableView load more when scrolling to bottom like Facebook application

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
    NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
    if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
        // This is the last cell
        [self loadMore];
    }
}

If you are using Core Data and NSFetchedResultsController, then loadMore could look like the following:

// Load more
- (void)loadMore {
    [self.fetchedResultsController.fetchRequest setFetchLimit:newFetchLimit];
    [NSFetchedResultsController deleteCacheWithName:@"cache name"];
    NSError *error;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }

    [self.tableView reloadData];
}

Handling JSON Post Request in Go

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    log.Println(t.Test)
}

How to access ssis package variables inside script component

  • On the front properties page of the variable script, amend the ReadOnlyVariables (or ReadWriteVariables) property and select the variables you are interested in. This will enable the selected variables within the script task
  • Within code you will now have access to read the variable as

    string myString = Variables.MyVariableName.ToString();

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Set default format of datetimepicker as dd-MM-yyyy

Ammending as "optional Answer". If you don't need to programmatically solve the problem, here goes the "visual way" in VS2012.

In Visual Studio, you can set custom format directly from the properties Panel: enter image description here

First Set the "Format" property to: "Custom"; Secondly, set your custom format to: "dd-MM-yyyy";

UILabel is not auto-shrinking text to fit label size

Well in the end i didn't find my answer. And i think the autoshrink doesn't work for multiple lines. I ended up using suggestion in this link: autoshrink on a UILabel with multiple lines

The solutions is to calulate text height at given width and if text is bigger, to shrink font size and then do he same again until the height is equal or less than your needed size.

I don't understand why this should be so hard to implement. If i'm missing something, everyone is welcome to correct me :)

List file using ls command in Linux with full path

I have had this issue, and I use the following :

ls -dl $PWD/* | grep $PWD

It has always got me the listingI have wanted, but your mileage may vary.

Create a Bitmap/Drawable from file path

here is a solution:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I used (the suggested answer from above)

sudo apt-get install eclipse eclipse-cdt g++

but ONLY after then also doing

sudo eclipse -clean

Hope that also helps.

Calling Scalar-valued Functions in SQL

You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.

https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx

presenting ViewController with NavigationViewController swift

SWIFT 3

let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)

How to remove the hash from window.location (URL) with JavaScript without page refresh?

function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

window.addEventListener("load", function(){
    removeLocationHash();
});

How to disable XDebug

Comment extension in php.ini and restart Apache. Here is a simple script (you can assign shortcut to it)

xdebug-toggle.php

define('PATH_TO_PHP_INI', 'c:/xampp/php/php.ini');
define('PATH_TO_HTTPD', 'c:/xampp/apache/bin/httpd.exe');
define('REXP_EXTENSION', '(zend_extension\s*=.*?php_xdebug)');

$s = file_get_contents(PATH_TO_PHP_INI);
$replaced = preg_replace('/;' . REXP_EXTENSION . '/', '$1', $s);
$isOn = $replaced != $s;
if (!$isOn) {
    $replaced = preg_replace('/' . REXP_EXTENSION . '/', ';$1', $s);
}
echo 'xdebug is ' . ($isOn ? 'ON' : 'OFF') . " now. Restarting apache...\n\n";
file_put_contents(PATH_TO_PHP_INI, $replaced);

passthru(PATH_TO_HTTPD . ' -k restart');

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

How to remove first and last character of a string?

This way you can remove 1 leading "[" and 1 trailing "]" character. If your string happen to not start with "[" or end with "]" it won't remove anything:

str.replaceAll("^\\[|\\]$", "")

Shortest way to check for null and assign another value if not

You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.

The type is defined in an assembly that is not referenced, how to find the cause?

In my case this was because doing a NuGet package update had only updated references to a dll dependency in some but not all projects in my solution - resulting in conflicting versions. Using a grep-style tool to search text within *.csproj files in my solution it was then easy to see the projects that still needed to be updated.

Selecting only first-level elements in jquery

You can also use $("ul li:first-child") to only get the direct children of the UL.

I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

bootstrap popover not showing on top of all elements

It could have to do with the z-index master list on variables.less. In general, be sure that your variables.less file is correct and up-to-date.

".addEventListener is not a function" why does this error occur?

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Post an object as data using Jquery Ajax

You may pass an object to the data option in $.ajax. jQuery will send this as regular post data, just like a normal HTML form.

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: dataO, // same as using {numberId: 1, companyId: 531}
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert('In Ajax');
    }
});

How to compare two List<String> to each other?

You could also use Except(produces the set difference of two sequences) to check whether there's a difference or not:

IEnumerable<string> inFirstOnly = a1.Except(a2);
IEnumerable<string> inSecondOnly = a2.Except(a1);
bool allInBoth = !inFirstOnly.Any() && !inSecondOnly.Any();

So this is an efficient way if the order and if the number of duplicates does not matter(as opposed to the accepted answer's SequenceEqual). Demo: Ideone

If you want to compare in a case insentive way, just add StringComparer.OrdinalIgnoreCase:

a1.Except(a2, StringComparer.OrdinalIgnoreCase)

Possible cases for Javascript error: "Expected identifier, string or number"

Actually I got something like that on IE recently and it was related to JavaScript syntax "errors". I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as

{ one:1, two:2, three:3, }

IE6 really doesn't like that comma after 3. You might look for something like that, touchy little syntax formality issues.

Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.

Good luck.

Not equal <> != operator on NULL

NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries

You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx

Which rows are returned when using LIMIT with OFFSET in MySQL?

It will return 18 results starting on record #9 and finishing on record #26.

Start by reading the query from offset. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.

Check this out.

And also the official documentation.

How to set data attributes in HTML elements

Another way to set the data- attribute is using the dataset property.

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>

const el = document.querySelector('#user');

// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''

// set the data attribute
el.dataset.dateOfBirth = '1960-10-03'; 
// Result: el.dataset.dateOfBirth === 1960-10-03

delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined

// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true

Spring @PropertySource using YAML

it's because you have not configure snakeyml. spring boot come with @EnableAutoConfiguration feature. there is snakeyml config too when u call this annotation..

this is my way:

@Configuration
@EnableAutoConfiguration
public class AppContextTest {
}

here is my test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(
        classes = {
                AppContextTest.class,
                JaxbConfiguration.class,
        }
)

public class JaxbTest {
//tests are ommited
}

Remove redundant paths from $PATH variable

For an easy copy-paste template I use this Perl snippet:

PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`

This way you don't need to escape the slashes for the substitute operator.

Getting indices of True values in a boolean list

Use enumerate, list.index returns the index of first match found.

>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]

For huge lists, it'd be better to use itertools.compress:

>>> from itertools import compress
>>> list(compress(xrange(len(t)), t))
[4, 5, 7]
>>> t = t*1000
>>> %timeit [i for i, x in enumerate(t) if x]
100 loops, best of 3: 2.55 ms per loop
>>> %timeit list(compress(xrange(len(t)), t))
1000 loops, best of 3: 696 µs per loop

How to generate a Dockerfile from an image?

This is derived from @fallino's answer, with some adjustments and simplifications by using the output format option for docker history. Since macOS and Gnu/Linux have different command-line utilities, a different version is necessary for Mac. If you only need one or the other, you can just use those lines.

#!/bin/bash
case "$OSTYPE" in
    linux*)
        docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
        tac                                                    | # reverse the file
        sed 's,^\(|3.*\)\?/bin/\(ba\)\?sh -c,RUN,'             | # change /bin/(ba)?sh calls to RUN
        sed 's,^RUN #(nop) *,,'                                | # remove RUN #(nop) calls for ENV,LABEL...
        sed 's,  *&&  *, \\\n \&\& ,g'                           # pretty print multi command lines following Docker best practices
    ;;
    darwin*)
        docker history --no-trunc --format "{{.CreatedBy}}" $1 | # extract information from layers
        tail -r                                                | # reverse the file
        sed -E 's,^(\|3.*)?/bin/(ba)?sh -c,RUN,'               | # change /bin/(ba)?sh calls to RUN
        sed 's,^RUN #(nop) *,,'                                | # remove RUN #(nop) calls for ENV,LABEL...
        sed $'s,  *&&  *, \\\ \\\n \&\& ,g'                      # pretty print multi command lines following Docker best practices
    ;;
    *)
        echo "unknown OSTYPE: $OSTYPE"
    ;;
esac

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

In my case, I forgot to add git to the respository name at the end.

New og:image size for Facebook share?

EDIT: The current best practices regarding Open Graph image sizes are officially outlined here: https://developers.facebook.com/docs/sharing/best-practices#images


There was a post in the Facebook developers group today, where one of the FB guys uploaded a PDF containing their new rules about image sizes – since that seems to be available only if you’re a member of the group, I uploaded it here: http://www.sendspace.com/file/ghqwhr

And they also said they will post about it in the developer blog in the coming days, so keep checking there as well

To summarize the linked document:

  • Minimum size in pixels is 600x315
  • Recommended size is 1200x630 - Images this size will get a larger display treatment.
  • Aspect ratio should be 1.91:1

I keep getting "Uncaught SyntaxError: Unexpected token o"

I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.

I was accessing the iframe data like this:

$('#load-file-iframe').contents().text()

which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to

$('#load-file-iframe').contents().find('body').text()

once I noticed some garbage in the HTML response.

Long story short check your raw HTML response data and you might turn something up.

Simplest way to throw an error/exception with a custom message in Swift 2?

Based on @Nick keets answer, here is a more complete example:

extension String: Error {} // Enables you to throw a string

extension String: LocalizedError { // Adds error.localizedDescription to Error instances
    public var errorDescription: String? { return self }
}

func test(color: NSColor) throws{
    if color == .red {
        throw "I don't like red"
    }else if color == .green {
        throw "I'm not into green"
    }else {
        throw "I like all other colors"
    }
}

do {
    try test(color: .green)
} catch let error where error.localizedDescription == "I don't like red"{
    Swift.print ("Error: \(error)") // "I don't like red"
}catch let error {
    Swift.print ("Other cases: Error: \(error.localizedDescription)") // I like all other colors
}

Originally published on my swift blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Adding this in project gradle worked for me

allprojects {
 repositories {
     jcenter()
     maven {
         url "https://maven.google.com" // specifically this worked 
     }
 }}

Server did not recognize the value of HTTP Header SOAPAction

Just to help someone on this problem, after an afternoon of debug, the problem was that the web service was developed with framework 4.5 and the call from android must be done with SoapEnvelope.VER12 and not with SoapEnvelope.VER11

Difference between an API and SDK

You use an SDK to access functionality of a library, and an API to control it.

How can I pass a class member function as a callback?

Necromancing.
I think the answers to date are a little unclear.

Let's make an example:

Supposed you have an array of pixels (array of ARGB int8_t values)

// A RGB image
int8_t* pixels = new int8_t[1024*768*4];

Now you want to generate a PNG. To do so, you call the function toJpeg

bool ok = toJpeg(writeByte, pixels, width, height);

where writeByte is a callback-function

void writeByte(unsigned char oneByte)
{
    fputc(oneByte, output);
}

The problem here: FILE* output has to be a global variable.
Very bad if you're in a multithreaded environment (e.g. a http-server).

So you need some way to make output a non-global variable, while retaining the callback signature.

The immediate solution that springs into mind is a closure, which we can emulate using a class with a member function.

class BadIdea {
private:
    FILE* m_stream;
public:
    BadIdea(FILE* stream)  {
        this->m_stream = stream;
    }

    void writeByte(unsigned char oneByte){
            fputc(oneByte, this->m_stream);
    }

};

And then do

FILE *fp = fopen(filename, "wb");
BadIdea* foobar = new BadIdea(fp);

bool ok = TooJpeg::writeJpeg(foobar->writeByte, image, width, height);
delete foobar;
fflush(fp);
fclose(fp);

However, contrary to expectations, this does not work.

The reason is, C++ member functions are kinda implemented like C# extension functions.

So you have

class/struct BadIdea
{
    FILE* m_stream;
}

and

static class BadIdeaExtensions
{
    public static writeByte(this BadIdea instance, unsigned char oneByte)
    {
         fputc(oneByte, instance->m_stream);
    }

}

So when you want to call writeByte, you need pass not only the address of writeByte, but also the address of the BadIdea-instance.

So when you have a typedef for the writeByte procedure, and it looks like this

typedef void (*WRITE_ONE_BYTE)(unsigned char);

And you have a writeJpeg signature that looks like this

bool writeJpeg(WRITE_ONE_BYTE output, uint8_t* pixels, uint32_t 
 width, uint32_t height))
    { ... }

it's fundamentally impossible to pass a two-address member function to a one-address function pointer (without modifying writeJpeg), and there's no way around it.

The next best thing that you can do in C++, is using a lambda-function:

FILE *fp = fopen(filename, "wb");
auto lambda = [fp](unsigned char oneByte) { fputc(oneByte, fp);  };
bool ok = TooJpeg::writeJpeg(lambda, image, width, height);

However, because lambda is doing nothing different, than passing an instance to a hidden class (such as the "BadIdea"-class), you need to modify the signature of writeJpeg.

The advantage of lambda over a manual class, is that you just need to change one typedef

typedef void (*WRITE_ONE_BYTE)(unsigned char);

to

using WRITE_ONE_BYTE = std::function<void(unsigned char)>; 

And then you can leave everything else untouched.

You could also use std::bind

auto f = std::bind(&BadIdea::writeByte, &foobar);

But this, behind the scene, just creates a lambda function, which then also needs the change in typedef.

So no, there is no way to pass a member function to a method that requires a static function-pointer.

But lambdas are the easy way around, provided that you have control over the source.
Otherwise, you're out of luck.
There's nothing you can do with C++.

Note:
std::function requires #include <functional>

However, since C++ allows you to use C as well, you can do this with libffcall in plain C, if you don't mind linking a dependency.

Download libffcall from GNU (at least on ubuntu, don't use the distro-provided package - it is broken), unzip.

./configure
make
make install

gcc main.c -l:libffcall.a -o ma

main.c:

#include <callback.h>

// this is the closure function to be allocated 
void function (void* data, va_alist alist)
{
     int abc = va_arg_int(alist);

     printf("data: %08p\n", data); // hex 0x14 = 20
     printf("abc: %d\n", abc);

     // va_start_type(alist[, return_type]);
     // arg = va_arg_type(alist[, arg_type]);
     // va_return_type(alist[[, return_type], return_value]);

    // va_start_int(alist);
    // int r = 666;
    // va_return_int(alist, r);
}



int main(int argc, char* argv[])
{
    int in1 = 10;

    void * data = (void*) 20;
    void(*incrementer1)(int abc) = (void(*)()) alloc_callback(&function, data);
    // void(*incrementer1)() can have unlimited arguments, e.g. incrementer1(123,456);
    // void(*incrementer1)(int abc) starts to throw errors...
    incrementer1(123);
    // free_callback(callback);
    return EXIT_SUCCESS;
}

And if you use CMake, add the linker library after add_executable

add_library(libffcall STATIC IMPORTED)
set_target_properties(libffcall PROPERTIES
        IMPORTED_LOCATION /usr/local/lib/libffcall.a)
target_link_libraries(BitmapLion libffcall)

or you could just dynamically link libffcall

target_link_libraries(BitmapLion ffcall)

Note:
You might want to include the libffcall headers and libraries, or create a cmake project with the contents of libffcall.

TypeError: $ is not a function when calling jQuery function

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...

JavaScript + Unicode regexes

As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

Indenting code in Sublime text 2?

Select all code that you intend to indent, then hit Ctrl + ] in Sublime text to indent.

For macOS users, use command + ] to indent, and command + [ to un-indent.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

postgresql.conf is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat, for example

@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL

@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale

Alternatively you can query your database with SHOW config_file; if you are a superuser.

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

What does it mean if a Python object is "subscriptable" or not?

As a corollary to the earlier answers here, very often this is a sign that you think you have a list (or dict, or other subscriptable object) when you do not.

For example, let's say you have a function which should return a list;

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']

Now when you call that function, and something_happens() for some reason does not return a True value, what happens? The if fails, and so you fall through; gimme_things doesn't explicitly return anything -- so then in fact, it will implicitly return None. Then this code:

things = gimme_things()
print("My first thing is {0}".format(things[0]))

will fail with "NoneType object is not subscriptable" because, well, things is None and so you are trying to do None[0] which doesn't make sense because ... what the error message says.

There are two ways to fix this bug in your code -- the first is to avoid the error by checking that things is in fact valid before attempting to use it;

things = gimme_things()
if things:
    print("My first thing is {0}".format(things[0]))
else:
    print("No things")  # or raise an error, or do nothing, or ...

or equivalently trap the TypeError exception;

things = gimme_things()
try:
    print("My first thing is {0}".format(things[0]))
except TypeError:
    print("No things")  # or raise an error, or do nothing, or ...

Another is to redesign gimme_things so that you make sure it always returns a list. In this case, that's probably the simpler design because it means if there are many places where you have a similar bug, they can be kept simple and idiomatic.

def gimme_things():
    if something_happens():
        return ['all', 'the', 'things']
    else:  # make sure we always return a list, no matter what!
        logging.info("Something didn't happen; return empty list")
        return []

Of course, what you put in the else: branch depends on your use case. Perhaps you should raise an exception when something_happens() fails, to make it more obvious and explicit where something actually went wrong? Adding exceptions to your own code is an important way to let yourself know exactly what's up when something fails!

(Notice also how this latter fix still doesn't completely fix the bug -- it prevents you from attempting to subscript None but things[0] is still an IndexError when things is an empty list. If you have a try you can do except (TypeError, IndexError) to trap it, too.)

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

What is "String args[]"? parameter in main method Java

In Java args contains the supplied command-line arguments as an array of String objects.

In other words, if you run your program as java MyProgram one two then args will contain ["one", "two"].

If you wanted to output the contents of args, you can just loop through them like this...

public class ArgumentExample {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

Jquery to change form action

Use jQuery.attr() in your click handler:

$("#myform").attr('action', 'page1.php');

Display text on MouseOver for image in html

You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?

CSS:

div {
    display: none;
    border:1px solid #000;
    height:30px;
    width:290px;
    margin-left:10px;
}

a:hover + div {
    display: block;
}?

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

What does the following Oracle error mean: invalid column index

I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this

SELECT * FROM EMPLOYE E WHERE E.ID = ?

and for the preparedStatement object (JDBC) if you set the parameters like

preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)

then it results in SQLException: Invalid column index

So, I removed that second parameter setting to prepared statement then problem solved

Sourcetree - undo unpushed commits

  1. Right click on the commit you like to reset to (not the one you like to delete!)
  2. Select "Reset master to this commit"
  3. Select "Soft" reset.

A soft reset will keep your local changes.

Source: https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree

Edit

About git revert: This command creates a new commit which will undo other commits. E.g. if you have a commit which adds a new file, git revert could be used to make a commit which will delete the new file.

About applying a soft reset: Assume you have the commits A to E (A---B---C---D---E) and you like to delete the last commit (E). Then you can do a soft reset to commit D. With a soft reset commit E will be deleted from git but the local changes will be kept. There are more examples in the git reset documentation.

Format number to always show 2 decimal places

For modern browsers, use toLocaleString:

var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });

Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:

num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

which gives:

1.35

Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:

num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

it will give:

1,35

MVC pattern on Android

Although this post seems to be old, I'd like to add the following two to inform about the recent development in this area for Android:

android-binding - Providing a framework that enabes the binding of android view widgets to data model. It helps to implement MVC or MVVM patterns in android applications.

roboguice - RoboGuice takes the guesswork out of development. Inject your View, Resource, System Service, or any other object, and let RoboGuice take care of the details.

What's the HTML to have a horizontal space between two objects?

CSS

div.horizontalgap {
  float: left;
  overflow: hidden;
  height: 1px;
  width: 0px;
}

Usage in HTML (for a 10px horizontal gap)

<div class="horizontalgap" style="width:10px"></div>

Hide axis and gridlines Highcharts

i managed to turn off mine with just

       lineColor: 'transparent',
       tickLength: 0

Handle spring security authentication exceptions with @ExceptionHandler

This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter in a handy way.

I tried to find an elegant way to inject MessageConverter into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.

I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.

Step 1 - Create a standalone class, storing MessageConverters

This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.

public class MessageProcessor { // Any name you like
    // List of HttpMessageConverter
    private List<HttpMessageConverter<?>> messageConverters;
    // under org.springframework.web.servlet.mvc.method.annotation
    private RequestResponseBodyMethodProcessor processor;

    /**
     * Below class name are copied from the framework.
     * (And yes, they are hard-coded, too)
     */
    private static final boolean jaxb2Present =
        ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());

    private static final boolean jackson2Present =
        ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
        ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());

    private static final boolean gsonPresent =
        ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());

    public MessageProcessor() {
        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();

        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (gsonPresent) {
            this.messageConverters.add(new GsonHttpMessageConverter());
        }

        processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
    }

    /**
     * This method will convert the response body to the desire format.
     */
    public void handle(Object returnValue, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
        processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
    }

    /**
     * @return list of message converters
     */
    public List<HttpMessageConverter<?>> getMessageConverters() {
        return messageConverters;
    }
}

Step 2 - Create AuthenticationEntryPoint

As in many tutorials, this class is essential to implement custom error handling.

public class CustomEntryPoint implements AuthenticationEntryPoint {
    // The class from Step 1
    private MessageProcessor processor;

    public CustomEntryPoint() {
        // It is up to you to decide when to instantiate
        processor = new MessageProcessor();
    }

    @Override
    public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

        // This object is just like the model class, 
        // the processor will convert it to appropriate format in response body
        CustomExceptionObject returnValue = new CustomExceptionObject();
        try {
            processor.handle(returnValue, request, response);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

Step 3 - Register the entry point

As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
    }
}

Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How can I generate Javadoc comments in Eclipse?

At a place where you want javadoc, type in /**<NEWLINE> and it will create the template.

remove kernel on jupyter notebook

You can delete it in the terminal via:

jupyter kernelspec uninstall yourKernel

where yourKernel is the name of the kernel you want to delete.

How to style the parent element when hovering a child element?

Another, simpler approach (to an old question)..
would be to place elements as siblings and use:

Adjacent Sibling Selector (+) or General Sibling Selector (~)

<div id="parent">
  <!-- control should come before the target... think "cascading" ! -->
  <button id="control">Hover Me!</button>
  <div id="target">I'm hovered too!</div>
</div>
#parent {
  position: relative;
  height: 100px;
}

/* Move button control to bottom. */
#control {
  position: absolute;
  bottom: 0;
}

#control:hover ~ #target {
  background: red;
}

enter image description here

Demo Fiddle here.

django - get() returned more than one topic

I had same problem and solution was obj = ClassName.objects.filter()

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

How to find a value in an array and remove it by using PHP array functions?

Okay, this is a bit longer, but does a couple of cool things.

I was trying to filter a list of emails but exclude certain domains and emails.

Script below will...

  1. Remove any records with a certain domain
  2. Remove any email with an exact value.

First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.

Then it will output a list of clean records at the end.

//list of domains to exclude
$excluded_domains = array(
    "domain1.com",
);

//list of emails to exclude
$excluded_emails = array(
    "[email protected]",
    "[email protected]",    
);

function get_domain($email) {

    $domain = explode("@", $email);
    $domain = $domain[1];
    return $domain;

}

//loop through list of emails
foreach($emails as $email) {

    //set false flag
    $exclude = false;

    //extract the domain from the email     
    $domain = get_domain($email);

    //check if the domain is in the exclude domains list
    if(in_array($domain, $excluded_domains)){
        $exclude = true;
    }

    //check if the domain is in the exclude emails list
    if(in_array($email, $excluded_emails)){
        $exclude = true;
    } 

    //if its not excluded add it to the final array
    if($exclude == false) {
        $clean_email_list[] = $email;
    }

    $count = $count + 1;
}

print_r($clean_email_list);

How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

OR

Using CSV writer :

import csv
with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

Javascript callback when IFRAME is finished loading?

First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.

On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:

// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
  if (typeof callback == 'function') {
    callback($('body', this.contentWindow.document).html());
  }
  setTimeout(function () {$('#frameId').remove();}, 50);
});

Flutter - Wrap text on overflow, like insert ellipsis or fade

Wrapping whose child elements are in a row or column, please wrap your column or row is new Flexible();

https://github.com/flutter/flutter/issues/4128

How to fix git error: RPC failed; curl 56 GnuTLS

I have a workaround if you need to clone or pull and the problem lies in the size of the repository history. It may also help when you want to push later, with no guarantee.

Simply retrieve the last commits with --depth=[number of last commits].

You can do this at clone time, or, if working from a local repository to which you added a remote, at pull time. For instance, to only retrieve the last commit (of each branch):

git clone repo --depth=1
# or
git pull --depth=1

UPDATE: if the remote is getting too much ahead of you, the issue may come back later as you try to pull the last changes, but there are too many and the connection closes with curl 56. You may have to git pull --depth=[number of commits ahead on remote], which is tedious if you're working on a very active repository.

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

How to concatenate two strings in C++?

It is better to use C++ string class instead of old style C string, life would be much easier.

if you have existing old style string, you can covert to string class

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
    string trueString = string (greeting);
    cout << trueString + "and there \n"; // compiles fine
    cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too

Attach event to dynamic elements in javascript

I've made a simple function for this.

The _case function allows you to not only get the target, but also get the parent element where you bind the event on.

The callback function returns the event which holds the target (evt.target) and the parent element matching the selector (this). Here you can do the stuff you need after the element is clicked.

I've not yet decided which is better, the if-else or the switch

_x000D_
_x000D_
var _case = function(evt, selector, cb) {_x000D_
  var _this = evt.target.closest(selector);_x000D_
  if (_this && _this.nodeType) {_x000D_
    cb.call(_this, evt);_x000D_
    return true;_x000D_
  } else { return false; }_x000D_
}_x000D_
_x000D_
document.getElementById('ifelse').addEventListener('click', function(evt) {_x000D_
  if (_case(evt, '.parent1', function(evt) {_x000D_
      console.log('1: ', this, evt.target);_x000D_
    })) return false;_x000D_
_x000D_
  if (_case(evt, '.parent2', function(evt) {_x000D_
      console.log('2: ', this, evt.target);_x000D_
    })) return false;_x000D_
_x000D_
  console.log('ifelse: ', this);_x000D_
})_x000D_
_x000D_
_x000D_
document.getElementById('switch').addEventListener('click', function(evt) {_x000D_
  switch (true) {_x000D_
    case _case(evt, '.parent3', function(evt) {_x000D_
      console.log('3: ', this, evt.target);_x000D_
    }): break;_x000D_
    case _case(evt, '.parent4', function(evt) {_x000D_
      console.log('4: ', this, evt.target);_x000D_
    }): break;_x000D_
    default:_x000D_
      console.log('switch: ', this);_x000D_
      break;_x000D_
  }_x000D_
})
_x000D_
#ifelse {_x000D_
  background: red;_x000D_
  height: 100px;_x000D_
}_x000D_
#switch {_x000D_
  background: yellow;_x000D_
  height: 100px;_x000D_
}
_x000D_
<div id="ifelse">_x000D_
  <div class="parent1">_x000D_
    <div class="child1">Click me 1!</div>_x000D_
  </div>_x000D_
  <div class="parent2">_x000D_
    <div class="child2">Click me 2!</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div id="switch">_x000D_
  <div class="parent3">_x000D_
    <div class="child3">Click me 3!</div>_x000D_
  </div>_x000D_
  <div class="parent4">_x000D_
    <div class="child4">Click me 4!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

RSA encryption and decryption in Python

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

What does the "yield" keyword do?

It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as C#'s iterator blocks if you're familiar with those.

The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - as if the generator method was paused. Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.

Linux command to print directory structure in the form of a tree

Is this what you're looking for tree? It should be in most distributions (maybe as an optional install).

~> tree -d /proc/self/
/proc/self/
|-- attr
|-- cwd -> /proc
|-- fd
|   `-- 3 -> /proc/15589/fd
|-- fdinfo
|-- net
|   |-- dev_snmp6
|   |-- netfilter
|   |-- rpc
|   |   |-- auth.rpcsec.context
|   |   |-- auth.rpcsec.init
|   |   |-- auth.unix.gid
|   |   |-- auth.unix.ip
|   |   |-- nfs4.idtoname
|   |   |-- nfs4.nametoid
|   |   |-- nfsd.export
|   |   `-- nfsd.fh
|   `-- stat
|-- root -> /
`-- task
    `-- 15589
        |-- attr
        |-- cwd -> /proc
        |-- fd
        | `-- 3 -> /proc/15589/task/15589/fd
        |-- fdinfo
        `-- root -> /

27 directories

sample taken from maintainer's web page.

You can add the option -L # where # is replaced by a number, to specify the max recursion depth.

Remove -d to display also files.

jquery .html() vs .append()

if by .add you mean .append, then the result is the same if #myDiv is empty.

is the performance the same? dont know.

.html(x) ends up doing the same thing as .empty().append(x)

How can I get enum possible values in a MySQL database?

here is for mysqli

function get_enum_values($mysqli, $table, $field )
{
    $type = $mysqli->query("SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'")->fetch_array(MYSQLI_ASSOC)['Type'];
    preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
    $enum = explode("','", $matches[1]);
    return $enum;
}
$deltypevals = get_enum_values($mysqli, 'orders', 'deltype');
var_dump ($deltypevals);

The property 'value' does not exist on value of type 'HTMLElement'

Also for anyone using properties such as Props or Refs without your "DocgetId's" then you can:

("" as HTMLInputElement).value;

Where the inverted quotes is your props value so an example would be like so:

var val = (this.refs.newText as HTMLInputElement).value;
alert("Saving this:" + val);

Declare global variables in Visual Studio 2010 and VB.NET

All of above can be avoided by simply declaring a friend value for runtime on the starting form.

Public Class Form1 
Friend sharevalue as string = "Boo"

Then access this variable from all forms simply using Form1.sharevalue

Python list iterator behavior and next(iterator)

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

Rails Object to hash

In most recent version of Rails (can't tell which one exactly though), you could use the as_json method :

@post = Post.first
hash = @post.as_json
puts hash.pretty_inspect

Will output :

{ 
  :name => "test",
  :post_number => 20,
  :active => true
}

To go a bit further, you could override that method in order to customize the way your attributes appear, by doing something like this :

class Post < ActiveRecord::Base
  def as_json(*args)
    {
      :name => "My name is '#{self.name}'",
      :post_number => "Post ##{self.post_number}",
    }
  end
end

Then, with the same instance as above, will output :

{ 
  :name => "My name is 'test'",
  :post_number => "Post #20"
}

This of course means you have to explicitly specify which attributes must appear.

Hope this helps.

EDIT :

Also you can check the Hashifiable gem.

How to close Android application?

Use "this.FinishAndRemoveTask();" - it closes application properly

Python requests library how to pass Authorization header with single token

i founded here, its ok with me for linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-code so my code with with linkedin login here:

ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()

RESTful Authentication

Tips valid for securing any web application

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

WSDL validator?

If you're using Eclipse, just have your WSDL in a .wsdl file, eclipse will validate it automatically.

From the Doc

The WSDL validator handles validation according to the 4 step process defined above. Steps 1 and 2 are both delegated to Apache Xerces (and XML parser). Step 3 is handled by the WSDL validator and any extension namespace validators (more on extensions below). Step 4 is handled by any declared custom validators (more on this below as well). Each step must pass in order for the next step to run.

Perfect 100% width of parent container for a Bootstrap input?

Use .container-fluid, if you want to full-width as parent, spanning the entire width of your viewport.

Plugin with id 'com.google.gms.google-services' not found

In build.gradle(Module:app) add this code

dependencies {
    ……..
    compile 'com.google.android.gms:play-services:10.0.1’
    ……  
}

If you still have a problem after that, then add this code in build.gradle(Module:app)

defaultConfig {
    ….
    …...
    multiDexEnabled true
}


dependencies {
    …..
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.android.support:multidex:1.0.1'
}

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Automatically accept all SDK licences

After trying many the possible solutions mentioned by members from the community I just found there might have been different problems overtime so most of the solutions are outdated.

Currently, and as I posted in the Travis community, Travis should be accepting all the licenses by default, but it kept complaining about not accepting the licenses 27.0.3 which shouldn't happen.

Adding:

before_install:
  - yes | sdkmanager "build-tools;27.0.3"

should fix the problem, we we would be able to even use an a 3.+ version of Android Gradle Tools without needing to even declare what version of build-tools we are using:

android:
  components:
    # Use the latest revision of Android SDK Tools
    - tools
    - platform-tools
    - tools

    # The SDK version used to compile your project
    - android-${ANDROID_API}
    # - build-tools-28.0.3    # WE DONT NEED THIS ANYMORE FROM AGP 3.+

    # Additional components
    - extra-google-google_play_services
    - extra-google-m2repository
    - addon-google_apis-google-${ANDROID_API}

This works as October 29th, 2018. Travis might make changes in the future so good luck with that!

Magento Product Attribute Get Value

It seems impossible to get value without loading product model. If you take a look at file app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php you'll see the method

public function getValue(Varien_Object $object)
{
    $value = $object->getData($this->getAttribute()->getAttributeCode());
    if (in_array($this->getConfigField('input'), array('select','boolean'))) {
        $valueOption = $this->getOption($value);
        if (!$valueOption) {
            $opt = new Mage_Eav_Model_Entity_Attribute_Source_Boolean();
            if ($options = $opt->getAllOptions()) {
                foreach ($options as $option) {
                    if ($option['value'] == $value) {
                        $valueOption = $option['label'];
                    }
                }
            }
        }
        $value = $valueOption;
    }
    elseif ($this->getConfigField('input')=='multiselect') {
        $value = $this->getOption($value);
        if (is_array($value)) {
            $value = implode(', ', $value);
        }
    }
    return $value;
}

As you can see this method requires loaded object to get data from it (3rd line).

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

How to add icon to mat-icon-button

All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.

You'll need to import MatButtonModule and MatIconModule in your app module file.

From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.

<button mat-icon-button>
  <mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>

In your case, use

<mat-icon>thumb_up</mat-icon>

As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Or import it in your global styles.scss.

@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

As it mentions, any icon font can be used with the mat-icon component.

Location of my.cnf file on macOS

Copy /usr/local/opt/mysql/support-files/my-default.cnf as /etc/my.cnf or /etc/mysql/my.cnf and then restart mysql.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Getting title and meta tags from external website

Unfortunately, the built in php function get_meta_tags() requires the name parameter, and certain sites, such as twitter leave that off in favor of the property attribute. This function, using a mix of regex and dom document, will return a keyed array of metatags from a webpage. It checks for the name parameter, then the property parameter. This has been tested on instragram, pinterest and twitter.

/**
 * Extract metatags from a webpage
 */
function extract_tags_from_url($url) {
  $tags = array();

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

  $contents = curl_exec($ch);
  curl_close($ch);

  if (empty($contents)) {
    return $tags;
  }

  if (preg_match_all('/<meta([^>]+)content="([^>]+)>/', $contents, $matches)) {
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="utf-8" ?>' . implode($matches[0]));
    $tags = array();
    foreach($doc->getElementsByTagName('meta') as $metaTag) {
      if($metaTag->getAttribute('name') != "") {
        $tags[$metaTag->getAttribute('name')] = $metaTag->getAttribute('content');
      }
      elseif ($metaTag->getAttribute('property') != "") {
        $tags[$metaTag->getAttribute('property')] = $metaTag->getAttribute('content');
      }
    }
  }

  return $tags;
}

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

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

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

getString Outside of a Context or Activity

In MyApplication, which extends Application:

public static Resources resources;

In MyApplication's onCreate:

resources = getResources();

Now you can use this field from anywhere in your application.

how to change text in Android TextView

Your onCreate() method has several huge flaws:

1) onCreate prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView's text here more than ONE time as only the last change will be drawn and thus visible to the user!

2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep() or Thread.wait() in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)

What your initialization of your Activity does is:

  • for no reason you create a new TextView object t!
  • you pick your layout's TextView in the variable t later.
  • you set the text of t (but keep in mind: it will be displayed only after onCreate() finishes and the main event loop of your application runs!)
  • you wait for 10 seconds within your onCreate method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)
  • then you set another text - this one will be displayed as soon as your onCreate() method finishes and several other Activity lifecycle methods have been processed!

The solution:

  1. Set text only once in onCreate() - this must be the first text that should be visible.

  2. Create a Runnable and a Handler

    private final Runnable mUpdateUITimerTask = new Runnable() {
        public void run() {
            // do whatever you want to change here, like:
            t.setText("Second text to display!");
        }
    };
    private final Handler mHandler = new Handler();
    
  3. install this runnable as a handler, possible in onCreate() (but read my advice below):

    // run the mUpdateUITimerTask's run() method in 10 seconds from now
    mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
    

Advice: be sure you know an Activity's lifecycle! If you do stuff like that in onCreate()this will only happen when your Activity is created the first time! Android will possibly keep your Activity alive for a longer period of time, even if it's not visible! When a user "starts" it again - and it is still existing - you will not see your first text anymore!


=> Always install handlers in onResume() and disable them in onPause()! Otherwise you will get "updates" when your Activity is not visible at all! In your case, if you want to see your first text again when it is re-activated, you must set it in onResume(), not onCreate()!

Add characters to a string in Javascript

simply used the + operator. Javascript concats strings with +

How do I disable form resizing for users?

Use the FormBorderStyle property. Make it FixedSingle:

this.FormBorderStyle = FormBorderStyle.FixedSingle;

Multiple submit buttons in an HTML form

If you really just want it to work like an install dialog, just give focus to the "Next" button OnLoad.

That way if the user hits Return, the form submits and goes forward. If they want to go back they can hit Tab or click on the button.

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

What primitive data type is time_t?

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

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

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

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

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

A few things to check:

  1. Make sure that you have the .NET Framework 4 installed.
  2. Ensure that version 4 of the .NET Framework is selected for your website & virtual directory (if applicable).
  3. Ensure that you have MVC installed or have the appropriate DLLs in your bin directory.
  4. Might need to allow ASP.NET 4.0 web service extensions
  5. Put the application in it's own app pool.
  6. Make sure the directory has at least "Scripts Only" execute permissions.

Pass props in Link react-router

For v5

 <Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

React Router Official Site

How can I parse a local JSON file from assets folder into a ListView?

With Kotlin have this extension function to read the file return as string.

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Parse the output string using any JSON parser.

How do you get the file size in C#?

It returns the file contents length

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

How do I get a plist as a Dictionary in Swift?

This answer uses Swift native objects rather than NSDictionary.

Swift 3.0

//get the path of the plist file
guard let plistPath = Bundle.main.path(forResource: "level1", ofType: "plist") else { return }
//load the plist as data in memory
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return }
//use the format of a property list (xml)
var format = PropertyListSerialization.PropertyListFormat.xml
//convert the plist data to a Swift Dictionary
guard let  plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String : AnyObject] else { return }
//access the values in the dictionary 
if let value = plistDict["aKey"] as? String {
  //do something with your value
  print(value)
}
//you can also use the coalesce operator to handle possible nil values
var myValue = plistDict["aKey"] ?? ""

What do the return values of Comparable.compareTo mean in Java?

int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative If thisObject < anotherObject
  • zero If thisObject == anotherObject
  • positive If thisObject > anotherObject

Python urllib2: Receive JSON response from url

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

Difference between two lists

var resultList = checklist.Where(p => myList.All(l => p.value != l.value)).ToList();

event.preventDefault() function not working in IE

preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.

Combining multiple commits before pushing in Git

You can do this with git rebase -i, passing in the revision that you want to use as the 'root':

git rebase -i origin/master

will open an editor window showing all of the commits you have made after the last commit in origin/master. You can reject commits, squash commits into a single commit, or edit previous commits.

There are a few resources that can probably explain this in a better way, and show some other examples:

http://book.git-scm.com/4_interactive_rebasing.html

and

http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

are the first two good pages I could find.

Difference between DOMContentLoaded and load events

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

How to run bootRun with spring profile via gradle task

Kotlin edition: Define the following task in you build.gradle.kts file:

tasks.named<BootRun>("bootRun") {
  args("--spring.profiles.active=dev")
}

This will pass the parameter --spring.profiles.active=dev to bootRun, where the profile name is dev in this case.

Every time you run gradle bootRun the profile dev is used.

Fetch API with Cookie

In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'

Sample JSON fetch request:

fetch(url, {
  method: 'GET',
  credentials: 'include'
})
  .then((response) => response.json())
  .then((json) => {
    console.log('Gotcha');
  }).catch((err) => {
    console.log(err);
});

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

How do I format a String in an email so Outlook will print the line breaks?

You need to send HTML emails. With <br />s in the email, you will always have your line breaks.

How do I prevent site scraping?

Quick approach to this would be to set a booby/bot trap.

  1. Make a page that if it's opened a certain amount of times or even opened at all, will collect certain information like the IP and whatnot (you can also consider irregularities or patterns but this page shouldn't have to be opened at all).

  2. Make a link to this in your page that is hidden with CSS display:none; or left:-9999px; positon:absolute; try to place it in places that are less unlikely to be ignored like where your content falls under and not your footer as sometimes bots can choose to forget about certain parts of a page.

  3. In your robots.txt file set a whole bunch of disallow rules to pages you don't want friendly bots (LOL, like they have happy faces!) to gather information on and set this page as one of them.

  4. Now, If a friendly bot comes through it should ignore that page. Right but that still isn't good enough. Make a couple more of these pages or somehow re-route a page to accept differnt names. and then place more disallow rules to these trap pages in your robots.txt file alongside pages you want ignored.

  5. Collect the IP of these bots or anyone that enters into these pages, don't ban them but make a function to display noodled text in your content like random numbers, copyright notices, specific text strings, display scary pictures, basically anything to hinder your good content. You can also set links that point to a page which will take forever to load ie. in php you can use the sleep() function. This will fight the crawler back if it has some sort of detection to bypass pages that take way too long to load as some well written bots are set to process X amount of links at a time.

  6. If you have made specific text strings/sentences why not go to your favorite search engine and search for them, it might show you where your content is ending up.

Anyway, if you think tactically and creatively this could be a good starting point. The best thing to do would be to learn how a bot works.

I'd also think about scambling some ID's or the way attributes on the page element are displayed:

<a class="someclass" href="../xyz/abc" rel="nofollow" title="sometitle"> 

that changes its form every time as some bots might be set to be looking for specific patterns in your pages or targeted elements.

<a title="sometitle" href="../xyz/abc" rel="nofollow" class="someclass"> 

id="p-12802" > id="p-00392"

Stripping non printable characters from a string in python

Based on @Ber's answer, I suggest removing only control characters as defined in the Unicode character database categories:

import unicodedata
def filter_non_printable(s):
    return ''.join(c for c in s if not unicodedata.category(c).startswith('C'))

LAST_INSERT_ID() MySQL

You could store the last insert id in a variable :

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);    

Or get the max id frm table1

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1); 
SELECT MAX(id) FROM table1;   

PHP json_encode encoding numbers as strings

Like oli_arborum said, I think you can use a preg_replace for doing the job. Just change the command like this :

$json = preg_replace('#:"(\d+)"#', ':$1', $json);

Simple logical operators in Bash

if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
    echo STR is empty but should have a value.
fi

How to prevent Browser cache for php site

try this

<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

Strange PostgreSQL "value too long for type character varying(500)"

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

XMLHttpRequest status 0 (responseText is empty)

Consider also the request timeout:

Modern browser return readyState=4 and status=0 if too much time passes before the server response.

How to remove td border with html?

Surround it with a div and give it a border and remove the border from the table

<div style="border: 1px solid black">
    <table border="0">
        <tr>
            <td>one</td>
            <td>two</td>
        </tr>
        <tr>
            <td>one</td>
            <td>two</td>
        </tr>
    </table>
</div>

You can check the working fiddle here


As per your updated question .... where you want to add or remove borders. You should remove borders from the html table first and then do the following

<td style="border-top: 1px solid black">

Assuming like you only want the top border. Similarly you have to do for others. Better way create four css class...

.topBorderOnly {
    border-top: 1px solid black;
}

.bottomBorderOnly {
    border-bottom: 1px solid black;
}

Then add the css to your code depending on the requirements.

<td class="topBorderOnly bottomBorderOnly">  

This will add both top and bottom border, similarly do for the rest.

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

I ran into a similar issue today - a co-worker could not build his software but I could build it. When he ran gcc it could not find cc1.

His executable path looked reasonable but the fact that I could not easily replicate the failure suggested something in his environment as the cause.

Eventually we found GCC_EXEC_PREFIX defined in his environment which was the culprit and was misleading gcc in the search for cc1. This was part of his shell startup scripts and was meant to work around a limitation on a SPARC/Solaris system that is no longer in use. The problem was resolved by not setting this environment variable.

http://gcc.gnu.org/onlinedocs/gcc/Environment-Variables.html

Start thread with member function

@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:

#include <thread>
#include <iostream>

class CFoo {
  public:
    int m_i = 0;
    void bar() {
      ++m_i;
    }
};

int main() {
  CFoo foo;
  std::thread t1(&CFoo::bar, &foo);
  t1.join();
  std::thread t2(&CFoo::bar, &foo);
  t2.join();
  std::cout << foo.m_i << std::endl;
  return 0;
}

outputs

2

Rewritten sample from this answer would be then:

#include <thread>
#include <iostream>

class Wrapper {
  public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread(&Wrapper::member1, this);
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread(&Wrapper::member2, this, arg1, arg2);
      }
};

int main() {
  Wrapper *w = new Wrapper();
  std::thread tw1 = w->member1Thread();
  tw1.join();
  std::thread tw2 = w->member2Thread("hello", 100);
  tw2.join();
  return 0;
}

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.

You can test your code in the below two ways.

  1. Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
  2. Change your server port to another port that is also available in the system. You will find the same error code reported.

Above is my fix. It works on my machine. I hope it helps!

Creating layout constraints programmatically

Swift version

Updated for Swift 3

This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:

Width and Height

enter image description here

Center in Container

enter image description here

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here (choose one of the methods below)
    // ...
}

Method 1: Anchor Style

// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • See also the Programmatically Creating Constraints documentation.
  • See this answer for a similar example of adding a pinning constraint.

Override console.log(); for production

After read a lot of posts, I made my own solution as follow:

SCRIPT:

function extendConsole() {
    "use strict";
    try {
        var disabledConsoles = {};

        console.enable = function (level, enabled) {
            // Prevent errors in browsers without console[level]
            if (window.console === 'undefined' || !window.console || window.console === null) {
                window.console = {};
            }
            if (window.console[level] === 'undefined' || !window.console[level] || window.console[level] == null) {
                window.console[level] = function() {};
            }

            if (enabled) {
                if (disabledConsoles[level]) {
                    window.console[level] = disabledConsoles[level];
                }
                console.info("console." + level + "() was enabled.");
            } else {
                disabledConsoles[level] = window.console[level];
                window.console[level] = function () { };
                console.info("console." + level + "() was disabled.");
            }
        };
    } catch (exception) {
        console.error("extendConsole() threw an exception.");
        console.debug(exception);
    }
}

USAGE:

extendConsole();
console.enable("debug", window.debugMode);

EXAMPLE:

http://jsfiddle.net/rodolphobrock/2rzxb5bo/10/

Max or Default?

Think about what you're asking!

The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.

Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.

Now, what is it that you actually want to do?

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

How do I uninstall a Windows service if the files do not exist anymore?

1st Step : Move to the Directory where your service is present

Command : cd c:\xxx\yyy\service

2nd Step : Enter the below command

Command : C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe service.exe \u

Here service.exe is your service exe and \u will uninstall the service. you'll see "The uninstall has completed" message.

If you wanna install a service, Remove \u in the above command which will install your service

How to get an object's properties in JavaScript / jQuery?

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {
    foo:    'bar',
    base:   'ball'
};

for(var key in obj) {
    alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}

or using jQuery's .each() method:

$.each(obj, function(key, element) {
    alert('key: ' + key + '\n' + 'value: ' + element);
});

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([]));

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

Why can't decimal numbers be represented exactly in binary?

There are an infinite number of rational numbers, and a finite number of bits with which to represent them. See http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems.

How to calculate modulus of large numbers?

/* The algorithm is from the book "Discrete Mathematics and Its
   Applications 5th Edition" by Kenneth H. Rosen.
   (base^exp)%mod
*/

int modular(int base, unsigned int exp, unsigned int mod)
{
    int x = 1;
    int power = base % mod;

    for (int i = 0; i < sizeof(int) * 8; i++) {
        int least_sig_bit = 0x00000001 & (exp >> i);
        if (least_sig_bit)
            x = (x * power) % mod;
        power = (power * power) % mod;
    }

    return x;
}

Read file-contents into a string in C++

Here's an iterator-based method.

ifstream file("file", ios::binary);
string fileStr;

istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);

copy(inputIt, emptyInputIt, stringInsert);

What's the best way to send a signal to all members of a process group?

Kill The Group Using Only Name of Process Which Belongs to Group:

kill -- -$(ps -ae o pid,pgrp,cmd | grep "[e]xample.py" | awk '{print $2}' | tail -1)

This is a modification of olibre's answer but you don't need to know the PID, just the name of a member of the group.

Explanation:

To get the group id you do the ps command using the arguments as shown, grep it for your command, but formatting example.py with quotes and using the bracket for the first letter (this filters out the grep command itself) then filter it through awk to get the second field which is the group id. The tail -1 gets rid of duplicate group ids. You put all of that in a variable using the $() syntax and voila – you get the group id. So you substitute that $(mess) for that -groupid above.

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

The information does exist - but not in the format you need, and only if you export your classes. This works in Windows, I don't know about other platforms. Using the storage-class specifiers as in, for example:

class __declspec(export) MyClass
{
public:
    void Foo(float x);
}

This makes the compiler build the class definition data into the DLL/Exe. But it's not in a format that you can readily use for reflection.

At my company we built a library that interprets this metadata, and allows you to reflect a class without inserting extra macros etc. into the class itself. It allows functions to be called as follows:

MyClass *instance_ptr=new MyClass;
GetClass("MyClass")->GetFunction("Foo")->Invoke(instance_ptr,1.331);

This effectively does:

instance_ptr->Foo(1.331);

The Invoke(this_pointer,...) function has variable arguments. Obviously by calling a function in this way you're circumventing things like const-safety and so on, so these aspects are implemented as runtime checks.

I'm sure the syntax could be improved, and it only works on Win32 and Win64 so far. We've found it really useful for having automatic GUI interfaces to classes, creating properties in C++, streaming to and from XML and so on, and there's no need to derive from a specific base class. If there's enough demand maybe we could knock it into shape for release.

Remove Android App Title Bar

Use this to remove title from android app in your Androidmainfest.xml

android:theme="@android:style/Theme.NoTitleBar"

or you can use this in your activity

requestWindowFeature(Window.FEATURE_NO_TITLE); 
setContentView(R.layout.activity_main);

How do you set a default value for a MySQL Datetime column?

If you set ON UPDATE CURRENT_TIMESTAMP it will take current time when row data update in table.

 CREATE TABLE bar(
        `create_time` TIMESTAMP CURRENT_TIMESTAMP,
        `update_time` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )

How to set java_home on Windows 7?

One Image can fix this issue. enter image description here

For More

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

error MSB6006: "cmd.exe" exited with code 1

I also faced similar issue.

My source path had one directory with 'space' (D:/source 2012). I resolved this by removing the space (D:/source2012).

I do not want to inherit the child opacity from the parent in CSS

Answers above seems to complicated for me, so I wrote this:

_x000D_
_x000D_
#kb-mask-overlay { _x000D_
    background-color: rgba(0,0,0,0.8);_x000D_
    width: 100%;_x000D_
    height: 100%; _x000D_
    z-index: 10000;_x000D_
    top: 0; _x000D_
    left: 0; _x000D_
    position: fixed;_x000D_
    content: "";_x000D_
}_x000D_
_x000D_
#kb-mask-overlay > .pop-up {_x000D_
    width: 800px;_x000D_
    height: 150px;_x000D_
    background-color: dimgray;_x000D_
    margin-top: 30px; _x000D_
    margin-left: 30px;_x000D_
}_x000D_
_x000D_
span {_x000D_
  color: white;_x000D_
}
_x000D_
<div id="kb-mask-overlay">_x000D_
  <div class="pop-up">_x000D_
    <span>Content of no opacity children</span>_x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
 <p>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vitae arcu nec velit pharetra consequat a quis sem. Vestibulum rutrum, ligula nec aliquam suscipit, sem justo accumsan mauris, id iaculis mauris arcu a eros. Donec sem urna, posuere id felis eget, pharetra rhoncus felis. Mauris tellus metus, rhoncus et laoreet sed, dictum nec orci. Mauris sagittis et nisl vitae aliquet. Sed vestibulum at orci ut tempor. Ut tristique vel erat sed efficitur. Vivamus vestibulum velit condimentum tristique lacinia. Sed dignissim iaculis mattis. Sed eu ligula felis. Mauris diam augue, rhoncus sed interdum nec, euismod eget urna._x000D_
_x000D_
Morbi sem arcu, sollicitudin ut euismod ac, iaculis id dolor. Praesent ultricies eu massa eget varius. Nunc sit amet egestas arcu. Quisque at turpis lobortis nibh semper imperdiet vitae a neque. Proin maximus laoreet luctus. Nulla vel nulla ut elit blandit consequat. Nullam tempus purus vitae luctus fringilla. Nullam sodales vel justo vitae eleifend. Suspendisse et tortor nulla. Ut pharetra, sapien non porttitor pharetra, libero augue dictum purus, dignissim vehicula ligula nulla sed purus. Cras nec dapibus dolor. Donec nulla arcu, pretium ac ipsum vel, accumsan egestas urna. Vestibulum at bibendum tortor, a consequat eros. Nunc interdum at erat nec ultrices. Sed a augue sit amet lacus sodales eleifend ut id metus. Quisque vel luctus arcu. _x000D_
 </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

kb-mask-overlay it's your (opacity) parent, pop-up it's your (no opacity) children. Everything below it's rest of your site.

Check if a value is in an array (C#)

Add necessary namespace

using System.Linq;

Then you can use linq Contains() method

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

Angular2 QuickStart npm start is not working correctly

Here's how I solved the problem today after hours of trying all of these different solutions - (for anyone looking for another way still).

Open 2 instances of cmd at your quickstart dir:

window #1:

npm run build:watch

then...

window #2:

npm run serve

It will then open in the browser and work as expected

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

jQuery post() with serialize and extra data

When you want to add a javascript object to the form data, you can use the following code

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        postData.push({name:key, value:data[key]});
    }
}
$.post(url, postData, function(){});

Or if you add the method serializeObject(), you can do the following

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});

TLS 1.2 in .NET Framework 4.0

According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:

  • At the beginning of the application, add this code: ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  • Set the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto to DWORD 1

iFrame Height Auto (CSS)

This is my PURE CSS solution :)

Add, scrolling yes to your iframe.

<iframe src="your iframe link" width="100%" scrolling="yes" frameborder="0"></iframe>

The trick :)

<style>
    html, body, iframe { height: 100%; }
    html { overflow: hidden; }
</style>

You don't need to worry about responsiveness :)

Virtual Serial Port for Linux

You can use a pty ("pseudo-teletype", where a serial port is a "real teletype") for this. From one end, open /dev/ptyp5, and then attach your program to /dev/ttyp5; ttyp5 will act just like a serial port, but will send/receive everything it does via /dev/ptyp5.

If you really need it to talk to a file called /dev/ttys2, then simply move your old /dev/ttys2 out of the way and make a symlink from ptyp5 to ttys2.

Of course you can use some number other than ptyp5. Perhaps pick one with a high number to avoid duplicates, since all your login terminals will also be using ptys.

Wikipedia has more about ptys: http://en.wikipedia.org/wiki/Pseudo_terminal

Oracle: SQL query that returns rows with only numeric values

You can use the REGEXP_LIKE function as:

SELECT X 
FROM myTable 
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

Sample run:

SQL> SELECT X FROM SO;

X
--------------------
12c
123
abc
a12

SQL> SELECT X  FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

X
--------------------
123

SQL> 

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2017, you switch between Solution View and Folder View back and forth. I think this is a better option, because it will keep the solution cleaner. I use this to edit .gitignore, .md files, etc.

Solution View and Folder View

How do I reverse a C++ vector?

#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
int main()
{
    vector<int>v1;
    for(int i=0; i<5; i++)
        v1.push_back(i*2);
    for(int i=0; i<v1.size(); i++)
        cout<<v1[i];    //02468
    reverse(v1.begin(),v1.end());
    
    for(int i=0; i<v1.size(); i++)
        cout<<v1[i];   //86420
}

How do I perform an IF...THEN in an SQL SELECT?

Use a CASE statement:

SELECT CASE
       WHEN (Obsolete = 'N' OR InStock = 'Y')
       THEN 'Y'
       ELSE 'N'
END as Available

etc...

How to make a Python script run like a service or daemon in Linux

A simple and supported version is Daemonize.

Install it from Python Package Index (PyPI):

$ pip install daemonize

and then use like:

...
import os, sys
from daemonize import Daemonize
...
def main()
      # your code here

if __name__ == '__main__':
        myname=os.path.basename(sys.argv[0])
        pidfile='/tmp/%s' % myname       # any name
        daemon = Daemonize(app=myname,pid=pidfile, action=main)
        daemon.start()

How should I call 3 functions in order to execute them one after the other?

asec=1000; 

setTimeout('some_3secs_function("somevalue")',asec*3);
setTimeout('some_5secs_function("somevalue")',asec*5);
setTimeout('some_8secs_function("somevalue")',asec*8);

I won't go into a deep discussion of setTimeout here, but:

  • in this case I've added the code to execute as a string. this is the simplest way to pass a var into your setTimeout-ed function, but purists will complain.
  • you can also pass a function name without quotes, but no variable can be passed.
  • your code does not wait for setTimeout to trigger.
  • This one can be hard to get your head around at first: because of the previous point, if you pass a variable from your calling function, that variable will not exist anymore by the time the timeout triggers - the calling function will have executed and it's vars gone.
  • I have been known to use anonymous functions to get around all this, but there could well be a better way,

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

How to turn on WCF tracing?

Instead of you manual adding the tracing enabling bit into web.config you can also try using the WCF configuration editor which comes with VS SDK to enable tracing

https://stackoverflow.com/a/16715631/2218571

What is the difference between buffer and cache memory in Linux?

Cache: This is a place acquired by kernel on physical RAM to store pages in caches. Now we need some sort of index to get the address of pages from caches. Here we need the buffer for page caches which keeps metadata of page cache.

When to use throws in a Java method declaration?

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

How to get second-highest salary employees in a table

Simple way WITHOUT using any special feature specific to Oracle, MySQL etc.

Suppose EMPLOYEE table has data as below. Salaries can be repeated. enter image description here

By manual analysis we can decide ranks as follows :-
enter image description here

Same result can be achieved by query

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
order by rank

enter image description here

First we find out distinct salaries. Then we find out count of distinct salaries greater than each row. This is nothing but the rank of that id. For highest salary, this count will be zero. So '+1' is done to start rank from 1.

Now we can get IDs at Nth rank by adding where clause to above query.

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
where rank = N;

How to change language of app when user selects language?

Kotlin solution using context extension

fun Context.applyNewLocale(locale: Locale): Context {
    val config = this.resources.configuration
    val sysLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.locales.get(0)
    } else {
        //Legacy
        config.locale
    }
    if (sysLocale.language != locale.language) {
        Locale.setDefault(locale)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale)
        } else {
            //Legacy
            config.locale = locale
        }
        resources.updateConfiguration(config, resources.displayMetrics)
    }
    return this
}

Usage

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(newBase?.applyNewLocale(Locale("es", "MX")))
}

Android Closing Activity Programmatically

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

Simple JavaScript problem: onClick confirm not preventing default action

If you want to use small inline commands in the onclick tag you could go with something like this.

<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button"> Delete </button>

How to run Unix shell script from Java code?

Here is an example how to run an Unix bash or Windows bat/cmd script from Java. Arguments can be passed on the script and output received from the script. The method accepts arbitrary number of arguments.

public static void runScript(String path, String... args) {
    try {
        String[] cmd = new String[args.length + 1];
        cmd[0] = path;
        int count = 0;
        for (String s : args) {
            cmd[++count] = args[count - 1];
        }
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        try {
            process.waitFor();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        while (bufferedReader.ready()) {
            System.out.println("Received from script: " + bufferedReader.readLine());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
}

When running on Unix/Linux, the path must be Unix-like (with '/' as separator), when running on Windows - use '\'. Hier is an example of a bash script (test.sh) that receives arbitrary number of arguments and doubles every argument:

#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
  echo argument $((counter +=1)): $1
  echo doubling argument $((counter)): $(($1+$1))
  shift
done

When calling

runScript("path_to_script/test.sh", "1", "2")

on Unix/Linux, the output is:

Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4

Hier is a simple cmd Windows script test.cmd that counts number of input arguments:

@echo off
set a=0
for %%x in (%*) do Set /A a+=1 
echo %a% arguments received

When calling the script on Windows

  runScript("path_to_script\\test.cmd", "1", "2", "3")

The output is

Received from script: 3 arguments received

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int