Programs & Examples On #Nxt

The NXT tag should be used when asking question about programming in the NXT 1.0 or 2.0 environment, or about programming the NXT 1.0/2.0 controller using other methods than the language/environment provided by LEGO.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.

So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.

UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.

javac: file not found: first.java Usage: javac <options> <source files>

Seems like you have your path right. But what is your working directory? on command prompt run:

javac -version

this should show your java version. if it doesnt, you have not set java in path correctly.

navigate to C:

cd \

Then:

javac -sourcepath users\AccName\Desktop -d users\AccName\Desktop first.java

-sourcepath is the complete path to your .java file, -d is the path/directory you want your .class files to be, then finally the file you want compiled (first.java).

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

Getting RSA private key from PEM BASE64 Encoded private key file

You will find below some code for reading unencrypted RSA keys encoded in the following formats:

  • PKCS#1 PEM (-----BEGIN RSA PRIVATE KEY-----)
  • PKCS#8 PEM (-----BEGIN PRIVATE KEY-----)
  • PKCS#8 DER (binary)

It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream or DerValue).

private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";

public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
    byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
    String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);

    if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
        // OpenSSL / PKCS#1 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
        return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
    }

    if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
        // PKCS#8 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
        return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
    }

    // We assume it's a PKCS#8 DER encoded binary file
    return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}

private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
    try {
        return keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Unexpected key format!", e);
    }
}

private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
    // We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
    int pkcs1Length = pkcs1Bytes.length;
    int totalLength = pkcs1Length + 22;
    byte[] pkcs8Header = new byte[] {
            0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
            0x2, 0x1, 0x0, // Integer (0)
            0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
            0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
    };
    byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
    return readPkcs8PrivateKey(pkcs8bytes);
}

private static byte[] join(byte[] byteArray1, byte[] byteArray2){
    byte[] bytes = new byte[byteArray1.length + byteArray2.length];
    System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
    System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
    return bytes;
}

Source: https://github.com/Mastercard/client-encryption-java/blob/master/src/main/java/com/mastercard/developer/utils/EncryptionUtils.java

Sorted array list in Java

Since the currently proposed implementations which do implement a sorted list by breaking the Collection API, have an own implementation of a tree or something similar, I was curios how an implementation based on the TreeMap would perform. (Especialy since the TreeSet does base on TreeMap, too)

If someone is interested in that, too, he or she can feel free to look into it:

TreeList

Its part of the core library, you can add it via Maven dependency of course. (Apache License)

Currently the implementation seems to compare quite well on the same level than the guava SortedMultiSet and to the TreeList of the Apache Commons library.

But I would be happy if more than only me would test the implementation to be sure I did not miss something important.

Best regards!

How to browse localhost on Android device?

Combining a few of the answers above plus one other additional item solved the problem for me.

  1. As mentioned above, turn your firewall off [add a specific rule allowing the incoming connections to the port once you've successfully connected]
  2. Find you IP address via ipconfig as mentioned above
  3. Verify that your webserver is binding to the ip address found above and not just 127.0.0.1. Test this locally by browsing to the ip address and port. E.g. 192.168.1.113:8888. If it's not, find a solution. E.g. https://groups.google.com/forum/?fromgroups=#!topic/google-appengine-java/z4rtqkKO2hg
  4. Now test it out on your Android device. Note that I also turned off my data connection and exclusively used a wifi connection on my Android.

$lookup on ObjectId's in an array

You can also use the pipeline stage to perform checks on a sub-docunment array

Here's the example using python (sorry I'm snake people).

db.products.aggregate([
  { '$lookup': {
      'from': 'products',
      'let': { 'pid': '$products' },
      'pipeline': [
        { '$match': { '$expr': { '$in': ['$_id', '$$pid'] } } }
        // Add additional stages here 
      ],
      'as':'productObjects'
  }
])

The catch here is to match all objects in the ObjectId array (foreign _id that is in local field/prop products).

You can also clean up or project the foreign records with additional stages, as indicated by the comment above.

How can I find the first and last date in a month using PHP?

For specific month and year use date() as natural language as following

$first_date = date('d-m-Y',strtotime('first day of april 2010'));
$last_date = date('d-m-Y',strtotime('last day of april 2010'));
// Isn't it simple way?

but for Current month

$first_date = date('d-m-Y',strtotime('first day of this month'));
$last_date = date('d-m-Y',strtotime('last day of this month'));

Two arrays in foreach loop

All fully tested

3 ways to create a dynamic dropdown from an array.

This will create a dropdown menu from an array and automatically assign its respective value.

Method #1 (Normal Array)

<?php

$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');

echo '<select name="countries">';

foreach($names AS $let=>$word){
    echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
 
?>


Method #2 (Normal Array)

<select name="countries">

<?php

$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>

</select>


Method #3 (Associative Array)

<?php

$my_array = array(
     'tn' => 'Tunisia',
     'us' => 'United States',
     'fr' => 'France'
);

echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
    echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>

READ_EXTERNAL_STORAGE permission for Android

Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">

and

function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element
}

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You could unregister the control with

regsvr32 /u badboy.ocx

at the command line. Though i would suggest testing these things in a vmware.

Using the Web.Config to set up my SQL database connection string?

Add this to your web config and change the catalog name which is your database name:

  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>

Reference System.Configuration assembly in your project.

Here is how you retrieve connection string from the config file:

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

How to link to apps on the app store

Simply change 'itunes' to 'phobos' in the app link.

http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=300136119&mt=8

Now it will open the App Store directly

How to put a UserControl into Visual Studio toolBox

I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.

Solution:

  1. From Solution Explorer I Right-Clicked the offending user control file and selected Exclude From Project
  2. Rebuild the solution
  3. Right-Click the user control and select Include in Project (assuming you have the Show All Files enabled in the Solution Explorer)

Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.

Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

Passing a variable to a powershell script via command line

Using param to name the parameters allows you to ignore the order of the parameters:

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Check if object is a jQuery object

var elArray = [];
var elObjeto = {};

elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE

elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE

Transform DateTime into simple Date in Ruby on Rails

Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.

self.date || self.exif_date_time_original.to_s

How do I redirect in expressjs while passing some context?

use app.set & app.get

Setting data

router.get(
  "/facebook/callback",
  passport.authenticate("facebook"),
  (req, res) => {
    req.app.set('user', res.req.user)
    return res.redirect("/sign");
  }
);

Getting data

router.get("/sign", (req, res) => {
  console.log('sign', req.app.get('user'))
});

Access-Control-Allow-Origin Multiple Origin Domains?

Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you would like to allow, and if it matches, echo the value of the Origin header back to the client as the Access-Control-Allow-Origin header in the response.

With .htaccess you can do it like this:

# ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
    <IfModule mod_headers.c>
        SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        Header merge Vary Origin
    </IfModule>
</FilesMatch>

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

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

print arraylist element?

Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog class need to override the toString() method (as mentioned in other answers) from the Object class to return a valid result.

public class Print {
    public static void main(final String[] args) {
        List<Dog> list = new ArrayList<Dog>();
        Dog e = new Dog("Tommy");
        list.add(e);
        list.add(new Dog("tiger"));
        System.out.println(list);
        for(Dog d:list) {
            System.out.println(d);
            // prints [Tommy, tiger]
        }
    }

    private static class Dog {
        private final String name;
        public Dog(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}

The output of this code is:

[Tommy, tiger]  
Tommy  
tiger

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

Edit: After updating to appcompat-v7:22.1.1 and using AppCompatActivity instead of ActionBarActivity my styles.xml looks like:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>

Note: This means I am using a Toolbar provided by the framework (NOT included in an XML file).

This worked for me:
styles.xml file:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>

Update: A quote from Gabriele Mariotti's blog.

With the new Toolbar you can apply a style and a theme. They are different! The style is local to the Toolbar view, for example the background color. The app:theme is instead global to all ui elements inflated in the Toolbar, for example the color of the title and icons.

Binding select element to object in Angular

Tested on Angular 11. I need an extra object 'typeSelected'. Pay attention I'm not using [(ngValue)] as other answers do :

HTML

<mat-select formControlName="type" [(value)]="typeSelected" [compareWith]="typeComparation">
     <mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
          {{myType.title}}
     </mat-option>
</mat-select>

CODE

// declaration
typeSelected: SurveyType;
...

// assigning variable 'type' of object 'survey' to 'typeSelected'
this.typeSelected = survey?.type;
...


// function to compare SurveyType objects
typeComparation = ( option, value ) =>  {
    if (option && value) {
        return option.id === value.id;
    }
}

Creating a LINQ select from multiple tables

If the anonymous type causes trouble for you, you can create a simple data class:

public class PermissionsAndPages
{
     public ObjectPermissions Permissions {get;set}
     public Pages Pages {get;set}
}

and then in your query:

select new PermissionsAndPages { Permissions = op, Page = pg };

Then you can pass this around:

return queryResult.SingleOrDefault(); // as PermissionsAndPages

Get push notification while App in foreground iOS

As @Danial Martine said iOS won't show a notification banner/alert. That's by design. But if really have to do it then there is one way . I have also achieve this by same.

1.Download the parse frame work from Parse FrameWork

2.Import #import <Parse/Parse.h>

3.Add following code to your didReceiveRemoteNotification Method

 - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [PFPush handlePush:userInfo];
}

PFPush will take care how to handle the remote notification . If App is in foreground this shows the alert otherwise it shows the notification at the top.

How to exit from Python without traceback?

something like import sys; sys.exit(0) ?

DateTime format to SQL format using C#

I think the problem was the two single quotes missing.

This is the sql I run to the MSSMS:

WHERE checktime >= '2019-01-24 15:01:36.000' AND checktime <= '2019-01-25 16:01:36.000'

As you can see there are two single quotes, so your codes must be:

string sqlFormattedDate = "'" + myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss") + "'";

Use single quotes for every string in MSSQL or even in MySQL. I hope this helps.

How do you clear the SQL Server transaction log?

DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:

if anyone has any comments to add for situations when this is NOT an adequate or optimal solution then please comment below


  • Right click on the database name.

  • Select Tasks ? Shrink ? Database

  • Then click OK!

I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.

I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds

In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]

--

PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!

Byte Array in Python

An alternative that also has the added benefit of easily logging its output:

hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)

allows you to do easy substitutions like so:

hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)

RecyclerView expand/collapse items

Use two view types in the your RVAdapter. One for expanded layout and other for collapsed. And the magic happens with setting android:animateLayoutChanges="true" for RecyclerView Checkout the effect achieved using this at 0:42 in this video

ASP.NET Setting width of DataBound column in GridView

Width can be set to specific column as below: By percentages:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="100%"></asp:BoundField>

OR

By pixel:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="500px"></asp:BoundField>

jQuery table sort

This is a nice way of sorting a table:

_x000D_
_x000D_
$(document).ready(function () {_x000D_
                $('th').each(function (col) {_x000D_
                    $(this).hover(_x000D_
                            function () {_x000D_
                                $(this).addClass('focus');_x000D_
                            },_x000D_
                            function () {_x000D_
                                $(this).removeClass('focus');_x000D_
                            }_x000D_
                    );_x000D_
                    $(this).click(function () {_x000D_
                        if ($(this).is('.asc')) {_x000D_
                            $(this).removeClass('asc');_x000D_
                            $(this).addClass('desc selected');_x000D_
                            sortOrder = -1;_x000D_
                        } else {_x000D_
                            $(this).addClass('asc selected');_x000D_
                            $(this).removeClass('desc');_x000D_
                            sortOrder = 1;_x000D_
                        }_x000D_
                        $(this).siblings().removeClass('asc selected');_x000D_
                        $(this).siblings().removeClass('desc selected');_x000D_
                        var arrData = $('table').find('tbody >tr:has(td)').get();_x000D_
                        arrData.sort(function (a, b) {_x000D_
                            var val1 = $(a).children('td').eq(col).text().toUpperCase();_x000D_
                            var val2 = $(b).children('td').eq(col).text().toUpperCase();_x000D_
                            if ($.isNumeric(val1) && $.isNumeric(val2))_x000D_
                                return sortOrder == 1 ? val1 - val2 : val2 - val1;_x000D_
                            else_x000D_
                                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;_x000D_
                        });_x000D_
                        $.each(arrData, function (index, row) {_x000D_
                            $('tbody').append(row);_x000D_
                        });_x000D_
                    });_x000D_
                });_x000D_
            });
_x000D_
            table, th, td {_x000D_
            border: 1px solid black;_x000D_
        }_x000D_
        th {_x000D_
            cursor: pointer;_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
        <tr><th>id</th><th>name</th><th>age</th></tr>_x000D_
        <tr><td>1</td><td>Julian</td><td>31</td></tr>_x000D_
        <tr><td>2</td><td>Bert</td><td>12</td></tr>_x000D_
        <tr><td>3</td><td>Xavier</td><td>25</td></tr>_x000D_
        <tr><td>4</td><td>Mindy</td><td>32</td></tr>_x000D_
        <tr><td>5</td><td>David</td><td>40</td></tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/

The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

javascript scroll event for iPhone/iPad?

I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.

HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:

<div id="wrapper">
  <div id="scroller">
    ... my scrollable content
  </div>
</div>

CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).

.touch #wrapper {
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.touch #scroller {
  position: absolute;
  z-index: 1;
  width: 100%;
}

JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.

# coffeescript
if Modernizr.touch
  myScroller = new IScroll('#wrapper', probeType: 3)
  myScroller.on 'scroll', updatePosition
  myScroller.on 'scrollEnd', updatePosition

You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)

function getScroll(elem, iscroll) {   
  var x, y;

  if (Modernizr.touch && iscroll) {
    x = iscroll.x * -1;
    y = iscroll.y * -1;   
  } else {
    x = elem.scrollTop;
    y = elem.scrollLeft;   
  }

  return {x: x, y: y}; 
}

The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.

EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

If you are using ASP.NET MVC Core 3 or newer, IHostingEnvironment has been deprecated and replaced with IWebHostEnvironment

public Startup(IWebHostEnvironment webHostEnvironment)
{
    var webRootPath = webHostEnvironment.WebRootPath;
}

How does a PreparedStatement avoid or prevent SQL injection?

I guess it will be a string. But the input parameters will be sent to the database & appropriate cast/conversions will be applied prior to creating an actual SQL statement.

To give you an example, it might try and see if the CAST/Conversion works.
If it works, it could create a final statement out of it.

   SELECT * From MyTable WHERE param = CAST('10; DROP TABLE Other' AS varchar(30))

Try an example with a SQL statement accepting a numeric parameter.
Now, try passing a string variable (with numeric content that is acceptable as numeric parameter). Does it raise any error?

Now, try passing a string variable (with content that is not acceptable as numeric parameter). See what happens?

Which Eclipse version should I use for an Android app?

Eclipse 3.5 for Java Developer is the best option for you and 3.6 version is good but not at all because of compatibility issues.

Should I use past or present tense in git commit messages?

The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:

Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.

So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.

How do I group Windows Form radio buttons?

Radio button without panel

public class RadioButton2 : RadioButton
{
   public string GroupName { get; set; }
}

private void RadioButton2_Clicked(object sender, EventArgs e)
{
    RadioButton2 rb = (sender as RadioButton2);

    if (!rb.Checked)
    {
       foreach (var c in Controls)
       {
           if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
           {
              (c as RadioButton2).Checked = false;
           }
       }

       rb.Checked = true;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    //a group
    RadioButton2 rb1 = new RadioButton2();
    rb1.Text = "radio1";
    rb1.AutoSize = true;
    rb1.AutoCheck = false;
    rb1.Top = 50;
    rb1.Left = 50;
    rb1.GroupName = "a";
    rb1.Click += RadioButton2_Clicked;
    Controls.Add(rb1);

    RadioButton2 rb2 = new RadioButton2();
    rb2.Text = "radio2";
    rb2.AutoSize = true;
    rb2.AutoCheck = false;
    rb2.Top = 50;
    rb2.Left = 100;
    rb2.GroupName = "a";
    rb2.Click += RadioButton2_Clicked;
    Controls.Add(rb2);

    //b group
    RadioButton2 rb3 = new RadioButton2();
    rb3.Text = "radio3";
    rb3.AutoSize = true;
    rb3.AutoCheck = false;
    rb3.Top = 80;
    rb3.Left = 50;
    rb3.GroupName = "b";
    rb3.Click += RadioButton2_Clicked;
    Controls.Add(rb3);

    RadioButton2 rb4 = new RadioButton2();
    rb4.Text = "radio4";
    rb4.AutoSize = true;
    rb4.AutoCheck = false;
    rb4.Top = 80;
    rb4.Left = 100;
    rb4.GroupName = "b";
    rb4.Click += RadioButton2_Clicked;
    Controls.Add(rb4);
}

Javascript search inside a JSON object

You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.

For example :-

let data = {
 "list": [
   {"name":"my Name","id":12,"type":"car owner"},
   {"name":"my Name2","id":13,"type":"car owner2"},
   {"name":"my Name4","id":14,"type":"car owner3"},
   {"name":"my Name4","id":15,"type":"car owner5"}
]}

and now use below command onkeyup or enter

to get single object

data.list.find( record => record.name === "my Name")

to get single array object

data.list.filter( record => record.name === "my Name")

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.

First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.

Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.

Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:

$sql_script = 'select * from USERS where password="'.$digested_password.'"'

Fourth, profit.

So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...

Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.

Convert a list to a string in C#

If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList). Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().

Java Interfaces/Implementation naming convention

Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:

IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations

The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.

I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.

Switch to another branch without changing the workspace files

Why not just git reset --soft <branch_name>?

Demonstration:

mkdir myrepo; cd myrepo; git init
touch poem; git add poem; git commit -m 'add poem'  # first commit
git branch original
echo bananas > poem; git commit -am 'change poem'  # second commit
echo are tasty >> poem  # unstaged change
git reset --soft original

Result:

$ git diff --cached
diff --git a/poem b/poem
index e69de29..9baf85e 100644
--- a/poem
+++ b/poem
@@ -0,0 +1 @@
+bananas
$ git diff
diff --git a/poem b/poem
index 9baf85e..ac01489 100644
--- a/poem
+++ b/poem
@@ -1 +1,2 @@
 bananas
+are tasty

One thing to note though, is that the current branch changes to original. You’re still left in the previous branch after the process, but can easily git checkout original, because it’s the same state. If you do not want to lose the previous HEAD, you should note the commit reference and do git branch -f <previous_branch> <commit> after that.

Timeout a command in bash without unnecessary delay

OS X doesn't use bash 4 yet, nor does it have /usr/bin/timeout, so here's a function that works on OS X without home-brew or macports that is similar to /usr/bin/timeout (based on Tino's answer). Parameter validation, help, usage, and support for other signals are an exercise for reader.

# implement /usr/bin/timeout only if it doesn't exist
[ -n "$(type -p timeout 2>&1)" ] || function timeout { (
    set -m +b
    sleep "$1" &
    SPID=${!}
    ("${@:2}"; RETVAL=$?; kill ${SPID}; exit $RETVAL) &
    CPID=${!}
    wait %1
    SLEEPRETVAL=$?
    if [ $SLEEPRETVAL -eq 0 ] && kill ${CPID} >/dev/null 2>&1 ; then
      RETVAL=124
      # When you need to make sure it dies
      #(sleep 1; kill -9 ${CPID} >/dev/null 2>&1)&
      wait %2
    else
      wait %2
      RETVAL=$?
    fi
    return $RETVAL
) }

git: fatal: I don't handle protocol '??http'

In Android Studio:

I removed git clone and just retain the url only and it worked!!

Copying an array of objects into another array in javascript

If you want to keep reference:

Array.prototype.push.apply(destinationArray, sourceArray);

Razor View Without Layout

Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

 @{
 var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
 string cLayout = "";
 if (controller == "Webmaster") {
 cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
 }
 else {
 cLayout = "~/Views/Shared/_Layout.cshtml";
 }
 Layout = cLayout;
 }

Procedure 2 : Set Layout by Returning from ActionResult

One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.

public ActionResult Index()
{
 SampleModel model = new SampleModel();
 //Any Logic
 return View("Index", "_WebmasterLayout", model);
}

Procedure 3 : View - wise Layout (By defining Layout within each view on the top)

ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.

@{
   Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}

Procedure 4 : Placing _ViewStart file in each of the directories

This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:

@{
  Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}

How to copy to clipboard in Vim?

@Jacob Dalton has mentioned this in a comment, but nobody seems to have mentioned in an answer that vim has to be compiled with clipboard support for any of the suggestions mentioned here to work. Mine wasn't configured that way on Mac OS X by default and I had to rebuild vim. Use this the command to find out whether you have it or not vim --version | grep 'clipboard'. +clipboard means you're good and the suggestions here will work for you, while -clipboard means you have to recompile and rebuild vim.

Why SpringMVC Request method 'GET' not supported?

Apparently some POST requests looks like a "GET" to the server (like Heroku...)

So I use this strategy and it works for me:

@RequestMapping(value = "/salvar", method = { RequestMethod.GET, RequestMethod.POST })

String replacement in batch file

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

Single vs Double quotes (' vs ")

If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of RSI.

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

Difference between Inheritance and Composition

Composition is just as it sounds - you create an object by plugging in parts.

EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,

Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel

So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.

Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.

For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.

With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).

Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,

iFuelable Interface:
   void AddSomeFuel()
   void UseSomeFuel()
   int  percentageFull()

then you can have a method somewhere else

private void FillHerUp(iFuelable : objectToFill) {

   Do while (objectToFill.percentageFull() <= 100)  {

        objectToFill.AddSomeFuel();
   }

Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.

If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Java Set retain order?

The Set interface does not provide any ordering guarantees.

Its sub-interface SortedSet represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet. They are TreeSet and ConcurrentSkipListSet.

In addition to the SortedSet interface, there is also the LinkedHashSet class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

Excel formula to search if all cells in a range read "True", if not, then show "False"

You can just AND the results together if they are stored as TRUE / FALSE values:

=AND(A1:D2)

Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.

=AND(EXACT(A1:D2,"TRUE"))

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

The reason is that php cannot find the correct path of mysql.sock.

Please make sure that your mysql is running first.

Then, please confirm that which path is the mysql.sock located, for example /tmp/mysql.sock

then add this path string to php.ini:

  • mysql.default_socket = /tmp/mysql.sock
  • mysqli.default_socket = /tmp/mysql.sock
  • pdo_mysql.default_socket = /tmp/mysql.sock

Finally, restart Apache.

Batch script: how to check for admin rights

Here is another one to add to the list ;-)

(attempt a file creation in system location)

CD.>"%SystemRoot%\System32\Drivers\etc\_"
MODE CON COLS=80 LINES=25

IF EXIST "%SystemRoot%\System32\Drivers\etc\_" (

  DEL "%SystemRoot%\System32\Drivers\etc\_"

  ECHO Has Admin privileges

) ELSE (

  ECHO No Admin privileges

)

The MODE CON reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

LINQ to read XML

Or, if you want a more general approach - i.e. for nesting up to "levelN":

void Main()
{
    XElement rootElement = XElement.Load(@"c:\events\test.xml");

    Console.WriteLine(GetOutline(0, rootElement));  
}

private string GetOutline(int indentLevel, XElement element)
{
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
    {
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
    }

    foreach (XElement childElement in element.Elements())
    {
        result.Append(GetOutline(indentLevel + 1, childElement));
    }

    return result.ToString();
}

How do you follow an HTTP Redirect in Node.js?

Possibly a little bit of a necromancing post here, but...

here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON

Note - uses a callback helper (shown at the end of this post)

( TLDR; full working demo in context here or remixed-version here)

function getJSON(url,cb){

    var callback=errBack(cb);
    //var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 301/302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("301/302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      console.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {

                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

Note - uses a callback helper (shown below)

you can paste this into the node console and it should run as is.

( or for full working demo in context see here )

var 

fs      = require('fs'),
https   = require('https');

function errBack (cb,THIS,logger) {

   var 
   self,
   EB=function(fn,r,e){
       if (logger===false) {
           fn.log=fn.info=fn.warn=fn.errlog=function(){};       
       } else {
           fn.log        = logger?logger.log   : console.log.bind(console);
           fn.info       = logger?logger.info  : console.info.bind(console);
           fn.warn       = logger?logger.warn  : console.warn.bind(console);
           fn.errlog     = logger?logger.error : console.error.bind(console);
       }
       fn.result=r;
       fn.error=e;
       return (self=fn);
   };


   if (typeof cb==='function') {
       return EB(

            logger===false // optimization when not logging - don't log errors
            ?   function(err){
                   if (err) {
                      cb (err);
                     return true;
                   }
                   return false;
               }

            :  function(err){
                   if (err) {
                      self.errlog(err);
                      cb (err);
                     return true;
                   }
                   return false;
               },

           function () {
               return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
           },
           function (err) {
               return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
           }
       );
   } else {

       return EB(

           function(err){
               if (err) {
                   if (typeof err ==='object' && err instanceof Error) {
                       throw err;
                   } else {
                       throw new Error(err);
                   }
                   return true;//redundant due to throw, but anyway.
               }
               return false;
           },

           logger===false
              ? self.log //optimization :resolves to noop when logger==false
              : function () {
                   self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
           },

           function (err) {
               throw typeof err==='string'?new Error(err):err;
           }
       );
   }
}

function getJSON(url,cb){

    var callback=errBack(cb);

    if (typeof url!=='string') {
        return callback.error("getJSON:expecting url as string");
    }

    if (typeof cb!=='function') {
        return callback.error("getJSON:expecting cb as function");
    }

    var redirs = [url],
    fetch = function(u){
        callback.info("hitting:"+u);
        https.get(u, function(res){
            var body = [];
            callback.info({statusCode:res.statusCode});
            if ([301,302].indexOf(res.statusCode)>=0) {
                if (redirs.length>10) {
                    return callback.error("excessive 302 redirects detected");
                } else {
                    if (redirs.indexOf(res.headers.location)<0) {
                        redirs.push(res.headers.location);
                        return fetch(res.headers.location);
                    } else {
                        return callback.error("302 redirect loop detected");
                    }
                }
            } else {
              res.on('data', function(chunk){
                  body.push(chunk);
                  console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
              });
              res.on('end', function(){
                  try {
                      // convert to a single buffer
                      var json = Buffer.concat(body);
                      callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});

                      // parse the buffer as json
                      return callback.result(JSON.parse(json),json);
                  } catch (err) {
                      // read with "bypass refetch" option
                      console.error("exception in getJSON.fetch:",err.message||err);

                      if (json.length>32) {
                        console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
                      } else {
                          console.error("json==>|"+json.toString('utf-8')+"|<=== json");
                      }

                      return callback.error(err,undefined,json);
                  }
              });
            }
        });
    };
    fetch(url);   
}

var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};


function getTLDs(cb,filter_func){

    if (typeof cb!=='function') return TLDs;

    var 
    read,fetch,
    CB_WRAP=function(tlds){
        return cb(
            filter_func===false
            ? cb(tlds)
            : tlds.filter(
                typeof filter_func==='function'
                 ? filter_func
                 : TLD_default_filter)
            );
    },
    check_mtime = function(mtime) {
       if (Date.now()-mtime > TLD_refresh_msec) {
           return fetch();
       } 
       if (TLDs) return CB_WRAP (TLDs);
       return read();
    };

    fetch = function(){

        getJSON(TLD_url,function(err,data){
            if (err) {
                console.log("exception in getTLDs.fetch:",err.message||err);
                return read(true);      
            } else {
                TLDs=Object.keys(data);

                fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
                    if (err) {
                        // ignore save error, we have the data
                        CB_WRAP(TLDs);
                    } else {
                        // get mmtime for the file we just made
                        fs.stat(TLD_cache,function(err,stats){
                            if (!err && stats) {
                               TLD_last_msec = stats.mtimeMs; 
                            }
                            CB_WRAP(TLDs);    
                        });
                    }
                });
            }
        });
    };

    read=function(bypassFetch) {
        fs.readFile(TLD_cache,'utf-8',function(err,json){

            try {
                if (err) {

                    if (bypassFetch) {
                        // after a http errror, we fallback to hardcoded basic list of tlds
                        // if the disk file is not readable
                        console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);    

                        throw err;
                    }
                    // if the disk read failed, get the data from the CDN server instead
                    return fetch();
                }

                TLDs=JSON.parse(json);
                if (bypassFetch) {
                    // we need to update stats here as fetch called us directly
                    // instead of being called by check_mtime
                    return fs.stat(TLD_cache,function(err,stats){
                        if (err) return fetch();
                        TLD_last_msec =stats.mtimeMs;
                        return CB_WRAP(TLDs);
                    });
                }

            } catch (e){
                // after JSON error, if we aren't in an http fail situation, refetch from cdn server
                if (!bypassFetch) {
                    return fetch();
                }

                // after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds

                console.log("exception in getTLDs.read:",err.messsage||err);    
                TLDs=TLDs_fallback;
            }

            return CB_WRAP(TLDs);
        });
    };

    if (TLD_last_msec) {
        return check_mtime(TLD_last_msec);
    } else {
        fs.stat(TLD_cache,function(err,stats){
            if (err) return fetch();
            TLD_last_msec =stats.mtimeMs;
            return check_mtime(TLD_last_msec);
        });
    }
}

getTLDs(console.log.bind(console));

Extract value of attribute node via XPath

for all xml with namespace use local-name()

//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name 

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.

How can I convert a .py to .exe for Python?

Now you can convert it by using PyInstaller. It works with even Python 3.

Steps:

  1. Fire up your PC
  2. Open command prompt
  3. Enter command pip install pyinstaller
  4. When it is installed, use the command 'cd' to go to the working directory.
  5. Run command pyinstaller <filename>

How to reverse apply a stash?

According to the git-stash manpage, "A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created," and git stash show -p gives us "the changes recorded in the stash as a diff between the stashed state and its original parent.

To keep your other changes intact, use git stash show -p | patch --reverse as in the following:

$ git init
Initialized empty Git repository in /tmp/repo/.git/

$ echo Hello, world >messages

$ git add messages

$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 messages

$ echo Hello again >>messages

$ git stash

$ git status
# On branch master
nothing to commit (working directory clean)

$ git stash apply
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   messages
#
no changes added to commit (use "git add" and/or "git commit -a")

$ echo Howdy all >>messages

$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
 Hello, world
+Hello again
+Howdy all

$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.

$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
 Hello, world
+Howdy all

Edit:

A light improvement to this is to use git apply in place of patch:

git stash show -p | git apply --reverse

Alternatively, you can also use git apply -R as a shorthand to git apply --reverse.

I've been finding this really handy lately...

What is the memory consumption of an object in Java?

no, 100 small objects needs more information (memory) than one big.

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

How can I determine if an image has loaded, using Javascript/jQuery?

You want to do what Allain said, however be aware that sometimes the image loads before dom ready, which means your load handler won't fire. The best way is to do as Allain says, but set the src of the image with javascript after attaching the load hander. This way you can guarantee that it fires.

In terms of accessibility, will your site still work for people without javascript? You may want to give the img tag the correct src, attach you dom ready handler to run your js: clear the image src (give it a fixed with and height with css to prevent the page flickering), then set your img load handler, then reset the src to the correct file. This way you cover all bases :)

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

How to set cellpadding and cellspacing in table with CSS?

Here is the solution.

The HTML:

<table cellspacing="0" cellpadding="0">
    <tr>
        <td>
            123
        </td>
    </tr>
</table>

The CSS:

table { 
      border-spacing:0; 
      border-collapse:collapse;   
    }

Hope this helps.

EDIT

td, th {padding:0}

How to find third or n?? maximum salary from salary table?

Just change the inner query value: E.g Select Top (2)* from Student_Info order by ClassID desc

Use for both problem:

Select Top (1)* from 
(
 Select Top (1)* from Student_Info order by ClassID desc 
) as wsdwe
order by ClassID 

EC2 instance has no public DNS

I tried to fix the 'no public DNS' once the EC2 was up and running, I couldnt add a public DNS

this is even after following the above steps making mods to the VPC or the Subnet

so, I had to make modifications to the subnet and the vpc, before starting another instance, and THEN start up a new instance.

the new instance had a public DNS. That is how it worked for me.

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

Laravel - display a PDF file in storage without forcing download?

I am using Laravel 5.4 and response()->file('path/to/file.ext') to open e.g. a pdf in inline-mode in browsers. This works quite well, but when a user wants to save the file, the save-dialog suggests the last part of the url as filename.

I already tried adding a headers-array like mentioned in the Laravel-docs, but this doesn't seem to override the header set by the file()-method:

return response()->file('path/to/file.ext', [
  'Content-Disposition' => 'inline; filename="'. $fileNameFromDb .'"'
]);

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

Available text color classes in Bootstrap

The bootstrap 3 documentation lists this under helper classes: Muted, Primary, Success, Info, Warning, Danger.

The bootstrap 4 documentation lists this under utilities -> color, and has more options: primary, secondary, success, danger, warning, info, light, dark, muted, white.

To access them one uses the class text-[class-name]

So, if I want the primary text color for example I would do something like this:

<p class="text-primary">This text is the primary color.</p>

This is not a huge number of choices, but it's some.

How to write some data to excel file(.xlsx)

Hope here is the exact what we are looking for.

private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

Apple Mach-O Linker Error when compiling for device

I fixed it by changing Mach-O Type under linking section on the Build settings from Nothing to Executable.

How to call javascript function from code-behind

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

Replace last occurrence of a string in a string

Another 1-liner but without preg:

$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';

echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer

How to implement a property in an interface

You mean like this?

class MyResourcePolicy : IResourcePolicy {
    private string version;

    public string Version {
        get {
            return this.version;
        }
        set {
            this.version = value;
        }
    }
}

Is there a Newline constant defined in Java like Environment.Newline in C#?

As of Java 7 (and Android API level 19):

System.lineSeparator()

Documentation: Java Platform SE 7


For older versions of Java, use:

System.getProperty("line.separator");

See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.

How to format font style and color in echo

 echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";

What's the best way to use R scripts on the command line (terminal)?

Try smallR for writing quick R scripts in the command line:

http://code.google.com/p/simple-r/

(r command in the directory)

Plotting from the command line using smallR would look like this:

r -p file.txt

Determine whether a key is present in a dictionary

In the same vein as martineau's response, the best solution is often not to check. For example, the code

if x in d:
    foo = d[x]
else:
    foo = bar

is normally written

foo = d.get(x, bar)

which is shorter and more directly speaks to what you mean.

Another common case is something like

if x not in d:
    d[x] = []

d[x].append(foo)

which can be rewritten

d.setdefault(x, []).append(foo)

or rewritten even better by using a collections.defaultdict(list) for d and writing

d[x].append(foo)

How do I test a private function or a class that has private methods, fields or inner classes?

I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.

You mentioned different types of problems. Let's start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:

public class ClassToTest {

    private final String first = "first";
    private final List<String> second = new ArrayList<>();
    ...
}

I'd have used this:

public class ClassToTest {

    private final String first;
    private final List<String> second;

    public ClassToTest() {
        this("first", new ArrayList<>());
    }

    public ClassToTest(final String first, final List<String> second) {
        this.first = first;
        this.second = second;
    }
    ...
}

This won't be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you'll be able to inject necessary values in test without reflection.

Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to wrap it within an interface, like Callable and then you pass in that interface also in the constructor (with that multiple constructor trick):

public ClassToTest() {
    this(...);
}

public ClassToTest(final Callable<T> privateMethodLogic) {
    this.privateMethodLogic = privateMethodLogic;
}

Mostly all that I wrote looks like it's a dependency injection pattern. In my personal experience it's really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I'd say the same about nested classes. If a nested class contains heavy logic it would be better if you'd moved it as a package private class and have injected it into a class needing it.

There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it's just annoying and I don't like that kind of stuff).

There is also setter injection, but I wouldn't recommended using it. I'd better stick with a constructor and initialize everything when it's really necessary, leaving the possibility for injecting necessary dependencies.

Java parsing XML document gives "Content not allowed in prolog." error

You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

Yes, that is supported.

Check the documentation provided here for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

DropDownList's SelectedIndexChanged event not firing

Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.

protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
 //code goes here
}

Java division by zero doesnt throw an ArithmeticException - why?

This is behaviour of floating point arithmetic is by specification. Excerpt from the specification, § 15.17.2. Division Operator /:

Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

Replace first occurrence of pattern in a string

public string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

here is an Extension Method that could also work as well per VoidKing request

public static class StringExtensionMethods
{
    public static string ReplaceFirst(this string text, string search, string replace)
    {
      int pos = text.IndexOf(search);
      if (pos < 0)
      {
        return text;
      }
      return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

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

Solved the problem by re-installing CUDA:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.1.0/local_installers/cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
echo "md5sum: $(md5sum cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb)"
echo "correct: 056de5e03444cce506202f50967b0016"
dpkg -i cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
apt-key add /var/cuda-repo-ubuntu1804-11-1-local/7fa2af80.pub
apt-get -qq update
apt-get -qq -y install cuda
rm cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb

Empty set literal?

No, there's no literal syntax for the empty set. You have to write set().

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

event.preventDefault() function not working in IE

Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.

Did you test your code on ie6 and/or ie7?

The doc says

Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.

but in case it doesn't, you might want to try

new Event(event).preventDefault();

java.text.ParseException: Unparseable date

        String date="Sat Jun 01 12:53:10 IST 2013";
        SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
        Date currentdate=sdf.parse(date);
        SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
        System.out.println(sdf2.format(currentdate));

Convert Rtf to HTML

You can try to upload it to google docs, and download it as HTML.

Retrieve list of tasks in a queue in Celery

EDIT: See other answers for getting a list of tasks in the queue.

You should look here: Celery Guide - Inspecting Workers

Basically this:

from celery.app.control import Inspect

# Inspect all nodes.
i = Inspect()

# Show the items that have an ETA or are scheduled for later processing
i.scheduled()

# Show tasks that are currently active.
i.active()

# Show tasks that have been claimed by workers
i.reserved()

Depending on what you want

Launch an app from within another (iPhone)

The lee answer is absolutely correct for iOS prior to 8.

In iOS 9+ you must whitelist any URL schemes your App wants to query in Info.plist under the LSApplicationQueriesSchemes key (an array of strings):

enter image description here

MySQL Query to select data from last week?

i Use this for the week start from SUNDAY:

SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY  
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY

What does this format means T00:00:00.000Z?

It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:

2015-03-04T00:00:00.000Z //Complete ISO-8601 date

If you try to parse this date as it is you will receive an Invalid Date error:

new Date('T00:00:00.000Z'); // Invalid Date

So, I guess the way to parse a timestamp in this format is to concat with any date

new Date('2015-03-04T00:00:00.000Z'); // Valid Date

Then you can extract only the part you want (timestamp part)

var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

$dbc is returning false. Your query has an error in it:

SELECT users.*, profile.* --You do not join with profile anywhere.
                                 FROM users 
                                 INNER JOIN contact_info 
                                 ON contact_info.user_id = users.user_id 
                                 WHERE users.user_id=3");

The fix for this in general has been described by Raveren.

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

How to import keras from tf.keras in Tensorflow?

Update for everybody coming to check why tensorflow.keras is not visible in PyCharm.

Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflow and keras inside tensorflow (tensorflow.keras) properly.

Also, it is recommended(by Francois Chollet) that everybody switches to tensorflow.keras in place of plain keras.

How to keep console window open

For visual c# console Application use:

Console.ReadLine();
Console.Read();
Console.ReadKey(true);

for visual c++ win32 console application use:

system("pause");

press ctrl+f5 to run the application.

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

What is the "-->" operator in C/C++?

The usage of --> has historical relevance. Decrementing was (and still is in some cases), faster than incrementing on the x86 architecture. Using --> suggests that x is going to 0, and appeals to those with mathematical backgrounds.

What does void do in java?

When the return type is void, your method doesn't return anything.

Look again at your code: There's no return in that method. You print to the console and exit.

Show/hide widgets in Flutter programmatically

bool _visible = false;

 void _toggle() {
    setState(() {
      _visible = !_visible;
    });
  }

onPressed: _toggle,

Visibility(
            visible:_visible,
            child: new Container(
            child: new  Container(
              padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 10.0),
              child: new Material(
                elevation: 10.0,
                borderRadius: BorderRadius.circular(25.0),
                child: new ListTile(
                  leading: new Icon(Icons.search),
                  title: new TextField(
                    controller: controller,
                    decoration: new InputDecoration(
                        hintText: 'Search for brands and products', border: InputBorder.none,),
                    onChanged: onSearchTextChanged,
                  ),
                  trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
                    controller.clear();
                    onSearchTextChanged('');
                  },),
                ),
              ),
            ),
          ),
          ),

Python find elements in one list that are not in the other

Not sure why the above explanations are so complicated when you have native methods available:

main_list = list(set(list_2)-set(list_1))

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

Object creation on the stack/heap?

A)

Object* o;
o = new Object();

`` B)

Object* o = new Object();

I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.

One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).

Convert utf8-characters to iso-88591 and back in PHP

It is much better to use

$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');

Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

When to use Spring Security`s antMatcher()?

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

Cannot load properties file from resources directory

I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this

ProjectRoot
         src
         bin
         myconf.properties

Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path

What's the difference between size_t and int in C++?

The definition of SIZE_T is found at: https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx

Pasting here the required information:

SIZE_T is a ULONG_PTR representing the maximum number of bytes to which a pointer can point.

This type is declared as follows:

typedef ULONG_PTR SIZE_T;

A ULONG_PTR is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.

This type is declared as follows:

typedef unsigned __int3264 ULONG_PTR;

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?

If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:

Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish

....otherwise you can convert with a formula by using

=TEXT(A1,"0000-00-00")+0

and format in required date format

Return in Scala

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

get selected value in datePicker and format it

Use jquery-dateFormat. It will solve your problem.

You need to include the jquery.dateFormat in your html file.

<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));

var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

In my case the issue was due to incorrect build order. One project had an xcopy command on post-build events to copy files from bin folder to another folder. But because of incorrect dependencies new files were getting created in bin folder while xcopy is in progress.

In VS right click on the project where you have post-build events. Go to Build Dependencies > Project Dependencies and make sure its correct. Verify the project build order(next tab to dependencies) as well.

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

Is there a "standard" format for command line/shell help text?

We are running Linux, a mostly POSIX-compliant OS. POSIX standards it should be: Utility Argument Syntax.

  • An option is a hyphen followed by a single alphanumeric character, like this: -o.
  • An option may require an argument (which must appear immediately after the option); for example, -o argument or -oargument.
  • Options that do not require arguments can be grouped after a hyphen, so, for example, -lst is equivalent to -t -l -s.
  • Options can appear in any order; thus -lst is equivalent to -tls.
  • Options can appear multiple times.
  • Options precede other nonoption arguments: -lst nonoption.
  • The -- argument terminates options.
  • The - option is typically used to represent one of the standard input streams.

How to embed a PDF viewer in a page?

This might work a little better this way

<embed src= "MyHome.pdf" width= "500" height= "375">

Line continue character in C#

You can use verbatim literals:

const string test = @"Test
123
456
";

But the indentation of the 1st line is tricky/ugly.

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

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

Escape double quotes for JSON in Python

You should be using the json module. json.dumps(string). It can also serialize other python data types.

import json

>>> s = 'my string with "double quotes" blablabla'

>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'

Connection failed: SQLState: '01000' SQL Server Error: 10061

Received SQLSTATE 01000 in the following error message below:

SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."

In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.

All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.

Simply added the permissions again to the backup destination drive and the issue was resolved.

Hope that helps someone.

Windows 2008 Enterprise

SQL Server 2008 Active/Passive cluster.

How does one check if a table exists in an Android SQLite database?

This is what I did:

/* open database, if doesn't exist, create it */
SQLiteDatabase mDatabase = openOrCreateDatabase("exampleDb.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);

Cursor c = null;
boolean tableExists = false;
/* get cursor on it */
try
{
    c = mDatabase.query("tbl_example", null,
        null, null, null, null, null);
        tableExists = true;
}
catch (Exception e) {
    /* fail */
    Log.d(TAG, tblNameIn+" doesn't exist :(((");
}

return tableExists;

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

How to insert strings containing slashes with sed?

sed is the stream editor, in that you can use | (pipe) to send standard streams (STDIN and STDOUT specifically) through sed and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i parameter mentioned below.
Consider the following:

sed -i -e 's/few/asd/g' hello.txt

s/ is used to substitute the found expression few with asd:

The few, the brave.


The asd, the brave.

/g stands for "global", meaning to do this for the whole line. If you leave off the /g (with s/few/asd/, there always needs to be three slashes no matter what) and few appears twice on the same line, only the first few is changed to asd:

The few men, the few women, the brave.


The asd men, the few women, the brave.

This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few occurs it should be replaced, make sure you have that /g.

The following two options (flags) are combined into one, -ie:

-i option is used to edit in place on the file hello.txt.

-e option indicates the expression/command to run, in this case s/.

Note: It's important that you use -i -e to search/replace. If you do -ie, you create a backup of every file with the letter 'e' appended.

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

How to set a background image in Xcode using swift?

You can try this as well, which is really a combination of previous answers from other posters here :

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "RubberMat")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

ld cannot find an existing library

In Ubuntu, you can install libtool which resolves the libraries automatically.

$ sudo apt-get install libtool

This resolved a problem with ltdl for me, which had been installed as libltdl.so.7 and wasn't found as simply -lltdl in the make.

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?

Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").

The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.

A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.

Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.

Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.

Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.

(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)

However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.

Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.

Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)

How to sum a variable by group

Using aggregate:

aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
  Category  x
1    First 30
2   Second  5
3    Third 34

In the example above, multiple dimensions can be specified in the list. Multiple aggregated metrics of the same data type can be incorporated via cbind:

aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...

(embedding @thelatemail comment), aggregate has a formula interface too

aggregate(Frequency ~ Category, x, sum)

Or if you want to aggregate multiple columns, you could use the . notation (works for one column too)

aggregate(. ~ Category, x, sum)

or tapply:

tapply(x$Frequency, x$Category, FUN=sum)
 First Second  Third 
    30      5     34 

Using this data:

x <- data.frame(Category=factor(c("First", "First", "First", "Second",
                                      "Third", "Third", "Second")), 
                    Frequency=c(10,15,5,2,14,20,3))

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Check date with todays date

to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below

    Calendar c = Calendar.getInstance();

    // set the calendar to start of today
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date today = c.getTime();

    // or as a timestamp in milliseconds
    long todayInMillis = c.getTimeInMillis();


    int dayOfMonth = 24;
    int month = 4;
    int year =2013;

    // reuse the calendar to set user specified date
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month - 1);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    // and get that as a Date
    Date dateSpecified = c.getTime();

    // test your condition
    if (dateSpecified.before(today)) {

        Log.v(" date is previou")
    } else if (dateSpecified.equal(today)) {

        Log.v(" date is today ")
    } 
             else if (dateSpecified.after(today)) {

        Log.v(" date is future date ")
    } 

Hope it will help....

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Scroll to bottom of div with Vue.js

  1. Use ref attribute on DOM element for reference
<div class="content scrollable" ref="msgContainer">
    <!-- content -->
</div>
  1. You need to setup a WATCH
  data() {
    return {
      count: 5
    };
  },
  watch: {
    count: function() {
      this.$nextTick(function() {
        var container = this.$refs.msgContainer;
        container.scrollTop = container.scrollHeight + 120;
      });
    }
  }
  1. Ensure you're using proper CSS
.scrollable {
  overflow: hidden;
  overflow-y: scroll;
  height: calc(100vh - 20px);
}

Simple Vim commands you wish you'd known earlier

Until [character] (t). It is useful for any command which accepts a range. My favorite is ct; or ct) which deletes everything up to the trailing semicolon / closing parentheses and then places you in insert mode.

Also, G and gg are useful (Go to bottom and top respectively).

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back

How to automatically generate N "distinct" colors?

Here's a solution to managed your "distinct" issue, which is entirely overblown:

Create a unit sphere and drop points on it with repelling charges. Run a particle system until they no longer move (or the delta is "small enough"). At this point, each of the points are as far away from each other as possible. Convert (x, y, z) to rgb.

I mention it because for certain classes of problems, this type of solution can work better than brute force.

I originally saw this approach here for tesselating a sphere.

Again, the most obvious solutions of traversing HSL space or RGB space will probably work just fine.

Simple WPF RadioButton Binding?

Sometimes it is possible to solve it in the model like this: Suppose you have 3 boolean properties OptionA, OptionB, OptionC.

XAML:

<RadioButton IsChecked="{Binding OptionA}"/>
<RadioButton IsChecked="{Binding OptionB}"/>
<RadioButton IsChecked="{Binding OptionC}"/>

CODE:

private bool _optionA;
public bool OptionA
{
    get { return _optionA; }
    set
    {
        _optionA = value;
        if( _optionA )
        {
             this.OptionB= false;
             this.OptionC = false;
        }
    }
}

private bool _optionB;
public bool OptionB
{
    get { return _optionB; }
    set
    {
        _optionB = value;
        if( _optionB )
        {
            this.OptionA= false;
            this.OptionC = false;
        }
    }
}

private bool _optionC;
public bool OptionC
{
    get { return _optionC; }
    set
    {
        _optionC = value;
        if( _optionC )
        {
            this.OptionA= false;
            this.OptionB = false;
        }
    }
}

You get the idea. Not the cleanest thing, but easy.

Using Page_Load and Page_PreRender in ASP.Net

The major difference between Page_Load and Page_PreRender is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load() methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender is your last chance to tweak the page before it turns into HTML stream.

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

How to check if div element is empty

var empty = $("#cartContent").html().trim().length == 0;

How do I use ROW_NUMBER()?

SQL Row_Number() function is to sort and assign an order number to data rows in related record set. So it is used to number rows, for example to identify the top 10 rows which have the highest order amount or identify the order of each customer which is the highest amount, etc.

If you want to sort the dataset and number each row by seperating them into categories we use Row_Number() with Partition By clause. For example, sorting orders of each customer within itself where the dataset contains all orders, etc.

SELECT
    SalesOrderNumber,
    CustomerId,
    SubTotal,
    ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY SubTotal DESC) rn
FROM Sales.SalesOrderHeader

But as I understand you want to calculate the number of rows of grouped by a column. To visualize the requirement, if you want to see the count of all orders of the related customer as a seperate column besides order info, you can use COUNT() aggregation function with Partition By clause

For example,

SELECT
    SalesOrderNumber,
    CustomerId,
    COUNT(*) OVER (PARTITION BY CustomerId) CustomerOrderCount
FROM Sales.SalesOrderHeader

How to format a phone number with jQuery

 $(".phoneString").text(function(i, text) {
            text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
            return text;
        });

Output :-(123) 657-8963

TSQL - Cast string to integer or return default value

Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.

Casting to a money or float first handles both the currency and scientific issues:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
    DECLARE @IntValue bigint;

    IF (ISNUMERIC(@Value) = 1)
        IF (@Value like '%e%')
            SET @IntValue = CAST(Cast(@Value as float) as bigint);
        ELSE
            SET @IntValue = CAST(CAST(@Value as money) as bigint);
    ELSE
        SET @IntValue = NULL;

    RETURN @IntValue;
END

The function will fail if the number is bigger than a bigint.

If you want to return a different default value, leave this function so it is generic and replace the null afterwards:

SELECT IsNull(dbo.TryConvertInt('nan') , 1000);

Intellij JAVA_HOME variable

Right Click On Project -> Open Module Settings -> Click SDK's

enter image description here

Choose Java Home Directory

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

If you use shared modules, just add RouterModule to a Module where your component is declared and don't forget to add <router-outlet></router-outlet>

Referenced from here RouterLink does not work

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How to create a DateTime equal to 15 minutes ago?

only the below code in Python 3.7 worked for me

from datetime import datetime,timedelta    
print(datetime.now()-timedelta(seconds=900))

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Pass Method as Parameter using C#

Here is an example Which can help you better to understand how to pass a function as a parameter.

Suppose you have Parent page and you want to open a child popup window. In the parent page there is a textbox that should be filled basing on child popup textbox.

Here you need to create a delegate.

Parent.cs // declaration of delegates public delegate void FillName(String FirstName);

Now create a function which will fill your textbox and function should map delegates

//parameters
public void Getname(String ThisName)
{
     txtname.Text=ThisName;
}

Now on button click you need to open a Child popup window.

  private void button1_Click(object sender, RoutedEventArgs e)
  {
        ChildPopUp p = new ChildPopUp (Getname) //pass function name in its constructor

         p.Show();

    }

IN ChildPopUp constructor you need to create parameter of 'delegate type' of parent //page

ChildPopUp.cs

    public  Parent.FillName obj;
    public PopUp(Parent.FillName objTMP)//parameter as deligate type
    {
        obj = objTMP;
        InitializeComponent();
    }



   private void OKButton_Click(object sender, RoutedEventArgs e)
    {


        obj(txtFirstName.Text); 
        // Getname() function will call automatically here
        this.DialogResult = true;
    }

How to convert characters to HTML entities using plain JavaScript

Having a lookup table with a bazillion replace() calls is slow and not maintainable.

Fortunately, the build-in escape() function also encodes most of the same characters, and puts them in a consistent format (%XX, where XX is the hex value of the character).

So, you can let escape() method do most of the work for you and just change its answer to be HTML entities instead of URL-escaped characters:

htmlescaped = escape(mystring).replace(/%(..)/g,"&#x$1;");

This uses the hex format for escaping values rather than the named entities, but for storing and displaying the values, it works just as well as named entities.

Of course, escape also escapes characters you don't need to escape in HTML (spaces, for instance), but you can unescape them with a few replace calls.

Edit: I like bucabay's answer better than my own... handles a larger range of characters, and requires no hacking afterward to get spaces, slashes, etc. unescaped.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

If using win7 64 bit OS:

After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40} directly to your eclipse folder as even pathing it apparently does nothing on win7.

Mad

edit:

Actual jdk version number on folder name will vary as newer versions are released

Relative frequencies / proportions with dplyr

For the sake of completeness of this popular question, since version 1.0.0 of dplyr, parameter .groups controls the grouping structure of the summarise function after group_by summarise help.

With .groups = "drop_last", summarise drops the last level of grouping. This was the only result obtained before version 1.0.0.

library(dplyr)
library(scales)

original <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)

original
#> # A tibble: 4 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     1     4     8 61.5%   
#> 4     1     5     5 38.5%

new_drop_last <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop_last") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(original, new_drop_last)
#> [1] TRUE

With .groups = "drop", all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by

# .groups = "drop"
new_drop <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_drop
#> # A tibble: 4 x 4
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 46.9%   
#> 2     0     4     4 12.5%   
#> 3     1     4     8 25.0%   
#> 4     1     5     5 15.6%

If .groups = "keep", same grouping structure as .data (mtcars, in this case). summarise does not peel off any variable used in the group_by.

Finally, with .groups = "rowwise", each row is it's own group. It is equivalent to "keep" in this situation

# .groups = "keep"
new_keep <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "keep") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_keep
#> # A tibble: 4 x 4
#> # Groups:   am, gear [4]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 100.0%  
#> 2     0     4     4 100.0%  
#> 3     1     4     8 100.0%  
#> 4     1     5     5 100.0%

# .groups = "rowwise"
new_rowwise <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "rowwise") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE

Another point that can be of interest is that sometimes, after applying group_by and summarise, a summary line can help.

# create a subtotal line to help readability
subtotal_am <- mtcars %>%
  group_by (am) %>% 
  summarise (n=n()) %>%
  mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars %>% group_by (am, gear) %>%
  summarise (n=n()) %>% 
  mutate(rel.freq = n/sum(n)) %>%
  bind_rows(subtotal_am) %>%
  arrange(am, gear) %>%
  mutate(rel.freq =  scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     0    NA    19 100.0%  
#> 4     1     4     8 61.5%   
#> 5     1     5     5 38.5%   
#> 6     1    NA    13 100.0%

Created on 2020-11-09 by the reprex package (v0.3.0)

Hope you find this answer useful.

Reverse a string in Java

    public static void reverseString(String s){
        System.out.println("---------");
        for(int i=s.length()-1; i>=0;i--){
            System.out.print(s.charAt(i));    
        }
        System.out.println(); 

    }

How to use greater than operator with date?

In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example

SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';

How to move table from one tablespace to another in oracle 11g

Moving tables:

First run:

SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';

-- Or suggested in the comments (did not test it myself)

SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; ' 
FROM dba_tables 
WHERE OWNER = '<SCHEMA>' 
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>

Where <schema_name> is the name of the user. And <tablespace_name> is the destination tablespace.

As a result you get lines like:

ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Moving indexes:

First run:

SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;' 
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';

The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.

As a result you should get something like:

ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Last but not least, moving LOBs:

First run:

SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';

This moves the LOB objects to the other tablespace.

As a result you should get something like:

ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);

Paste the results in a script or in a oracle sql developer like application and run it.

O and there is one more thing:

For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.

Flash CS4 refuses to let go

Use a grep analog to find the strings oldnamespace and Jenine inside the files in your whole project folder. Then you'd know what step to do next.

SSH configuration: override the default username

You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:

alias sshb="ssh buck@host"

To make the alias available in your terminal, you can either close and open your terminal, or run

source ~/.bashrc

Then you can connect by just typing in:

sshb

Are there constants in JavaScript?

The const keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:

const CONSTANT_NAME = 0;

How to pass multiple values through command argument in Asp.net?

You can try this:

CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'

Writing sqlplus output to a file

You may use the SPOOL command to write the information to a file.

Before executing any command type the following:

SPOOL <output file path>

All commands output following will be written to the output file.

To stop command output writing type

SPOOL OFF

Reset the Value of a Select Box

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

function resetSelectElement(selectElement) {
    var options = selectElement.options;

    // Look for a default selected option
    for (var i=0, iLen=options.length; i<iLen; i++) {

        if (options[i].defaultSelected) {
            selectElement.selectedIndex = i;
            return;
        }
    }

    // If no option is the default, select first or none as appropriate
    selectElement.selectedIndex = 0; // or -1 for no option selected
}

And beware of setting attributes rather than properties, they have different effects in different browsers.

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

How do I check if a string contains another string in Swift?

If you want to check that one String contains another Sub-String within it or not you can check it like this too,

var name = String()  
name = "John has two apples." 

Now, in this particular string if you want to know if it contains fruit name 'apple' or not you can do,

if name.contains("apple")      
{  
print("Yes , it contains fruit name")    
}    
else      
{    
 print(it does not contain any fruit name)    
}    

Hope this works for you.

split string only on first instance of specified character

Replace the first instance with a unique placeholder then split from there.

"good_luck_buddy".replace(/\_/,'&').split('&')

["good","luck_buddy"]

This is more useful when both sides of the split are needed.

Disabling the button after once click

think simple

<button id="button1" onclick="Click();">ok</button>
<script>
    var buttonClick = false;
    function Click() {
        if (buttonClick) {
            return;
        }
        else {
            buttonClick = true;
            //todo
            alert("ok");
            //buttonClick = false;
        }
    }
</script>

if you want run once :)

What is @ModelAttribute in Spring MVC?

I know I am late to the party, but I'll quote like they say, "better be late than never". So let us get going, Everybody has their own ways to explain things, let me try to sum it up and simple it up for you in a few steps with an example; Suppose you have a simple form, form.jsp

<form:form action="processForm" modelAttribute="student">
First Name : <form:input path="firstName" /> 
<br><br>
Last Name : <form:input path="lastName" />
<br><br>
<input type="submit" value="submit"/>
</form:form>

path="firstName" path="lastName" These are the fields/properties in the StudentClass when the form is called their getters are called but once submitted their setters are called and their values are set in the bean that was indicated in the modelAttribute="student" in the form tag.

We have StudentController that includes the following methods;

@RequestMapping("/showForm")
public String showForm(Model theModel){ //Model is used to pass data between 
//controllers and views
    theModel.addAttribute("student", new Student()); //attribute name, value
return "form";
}

@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent){
    System.out.println("theStudent :"+ theStudent.getLastName());
return "form-details";
}

//@ModelAttribute("student") Student theStudent
//Spring automatically populates the object data with form data all behind the 
//scenes 

now finally we have a form-details.jsp

<b>Student Information</b>
${student.firstName}
${student.lastName}

So back to the question What is @ModelAttribute in Spring MVC? A sample definition from the source for you, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation The @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view.

What actually happens is it gets all the values of your form those were submitted by it and then holds them for you to bind or assign them to the object. It works same like the @RequestParameter where we only get a parameter and assign the value to some field. Only difference is @ModelAttribute holds all form data rather than a single parameter. It creates a bean for you that holds form submitted data to be used by the developer later on.

To recap the whole thing. Step 1 : A request is sent and our method showForm runs and a model, a temporary bean is set with the name student is forwarded to the form. theModel.addAttribute("student", new Student());

Step 2 : modelAttribute="student" on form submission model changes the student and now it holds all parameters of the form

Step 3 : @ModelAttribute("student") Student theStudent We fetch the values being hold by @ModelAttribute and assign the whole bean/object to Student.

Step 4 : And then we use it as we bid, just like showing it on the page etc like I did

I hope it helps you to understand the concept. Thanks

How do I disable a href link in JavaScript?

Instead of void you can also use:

<a href="javascript:;">this link is disabled</a> 

Filter dataframe rows if value in column is in a set list of values

You can use query, i.e.:

b = df.query('a > 1 & a < 5')

How to remove item from array by value?

In a global function we can't pass a custom value directly but there are many way as below

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

My favorite no-conflict-friendly construct:

jQuery(function($) {
  // ...
});

Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

Or as we say in coffeescript:

jQuery ($) ->
  # code here

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

C++ cout hex values?

Use:

#include <iostream>

...

std::cout << std::hex << a;

There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.

Binding value to input in Angular JS

If you don't wan't to use ng-model there is ng-value you can try.

Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/