Programs & Examples On #Xmlspy

Altova XMLSpy is an advanced XML editor with support for XML Schema, XSLT, XPath, XQuery, WSDL, SOAP, XBRL, JSON, and more.

Jaxb, Class has two properties of the same name

Your JAXB is looking at both the getTimeSeries() method and the member timeSeries. You don't say which JAXB implementation you're using, or its configuration, but the exception is fairly clear.

at public java.util.List testjaxp.ModeleREP.getTimeSeries()

and

at protected java.util.List testjaxp.ModeleREP.timeSeries

You need to configure you JAXB stuff to use annotations (as per your @XmlElement(name="TimeSeries")) and ignore public methods.

Lightweight XML Viewer that can handle large files

http://www.firstobject.com/dn_editor.htm is so far the best and lightest editor available with handful of utilities. I recommend using it - tried with up to 400 MB of files and more than a million records :)

How to improve Netbeans performance?

NetBeans 8.0.2 (PHP) has two problems: the SubVersion client and the Twig templates. In order to drastically improve overall performance, a) disable teh "Twig Templates" plugin (this will also deactivate Symphony2, in case you may require it) and b) override the SVN client with this switch:

run.args.extra=-J-DsvnClientAdapterFactory=commandline

^ project.properties lets one define the CLI arguments individually (which may also make sense with RAM settings and other customization). guess one could re-enable Twig once that linked bug-report has been closed. re-scanning isn't really the issue, while the rescan performs as it should ...in a timely manner.

Just was testing some more and noticed, that on Linux it runs way smoother with the Oracle JDK than the (common) OpenJDK - have seen there is even one version of NetBeans bundled with it.

Left function in c#

var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
    // Do your stuff.
}

Inner join of DataTables in C#

This is my code. Not perfect, but working good. I hope it helps somebody:

    static System.Data.DataTable DtTbl (System.Data.DataTable[] dtToJoin)
    {
        System.Data.DataTable dtJoined = new System.Data.DataTable();

        foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
            dtJoined.Columns.Add(dc.ColumnName);

        foreach (System.Data.DataTable dt in dtToJoin)
            foreach (System.Data.DataRow dr1 in dt.Rows)
            {
                System.Data.DataRow dr = dtJoined.NewRow();
                foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
                    dr[dc.ColumnName] = dr1[dc.ColumnName];

                dtJoined.Rows.Add(dr);
            }

        return dtJoined;
    }

SUM of grouped COUNT in SQL Query

all of the solution here are great but not necessarily can be implemented for old mysql servers (at least at my case). so you can use sub-queries (i think it is less complicated).

 select sum(t1.cnt) from 
        (SELECT column, COUNT(column) as cnt
            FROM
            table 
            GROUP BY 
            column
            HAVING 
            COUNT(column) > 1) as t1 ;

bower proxy configuration

I struggled with this from behind a proxy so I thought I should post what I did. Below one is worked for me.

-> "export HTTPS_PROXY=(yourproxy)"

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

How to split data into trainset and testset randomly?

A quick note for the answer from @subin sahayam

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set

If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.

test_data = data[int(len(data)*.80+1):]

find: missing argument to -exec

Just for your information:
I have just tried using "find -exec" command on a Cygwin system (UNIX emulated on Windows), and there it seems that the backslash before the semicolon must be removed:
find ./ -name "blabla" -exec wc -l {} ;

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Actually my solution to this problem was much simpler, because I already had the latest version of PowerShell and is still didn't recognize Install-Module command. What fixed the "issue" for me was just typing the command manually, since originally I tried copying the snippet from a website and apparently there was some issue with the formatting when copy&pasting, so when I typed the command manually it installed the module without any problem.

How to get height of <div> in px dimension

For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

How to clear the entire array?

i fell into a case where clearing the entire array failed with dim/redim :

having 2 module-wide arrays, Private inside a userform,

One array is dynamic and uses a class module, the other is fixed and has a special type.

Option Explicit

Private Type Perso_Type
   Nom As String
   PV As Single 'Long 'max 1
   Mana As Single 'Long
   Classe1 As String
   XP1 As Single
   Classe2 As String
   XP2 As Single
   Classe3 As String
   XP3 As Single
   Classe4 As String
   XP4 As Single
   Buff(1 To 10) As IPicture 'Disp
   BuffType(1 To 10) As String
   Dances(1 To 10) As IPicture 'Disp
   DancesType(1 To 10) As String
End Type

Private Data_Perso(1 To 9, 1 To 8) As Perso_Type

Dim ImgArray() As New ClsImage 'ClsImage is a Class module

And i have a sub declared as public to clear those arrays (and associated run-time created controls) from inside and outside the userform like this :

Public Sub EraseControlsCreatedAtRunTime()
Dim i As Long
On Error Resume Next
With Me.Controls 'removing all on run-time created controls of the Userform :
    For i = .Count - 1 To 0 Step -1 
        .Remove i
    Next i
End With
Err.Clear: On Error GoTo 0

Erase ImgArray, Data_Perso
'ReDim ImgArray() As ClsImage ' i tried this, no error but wouldn't work correctly
'ReDim Data_Perso(1 To 9, 1 To 8) As Perso_Type 'without the erase not working, with erase this line is not needed.
End Sub

note : this last sub was first called from outside (other form and class module) with Call FormName.SubName but had to replace it with Application.Run FormName.SubName , less errors, don't ask why...

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

How to print the data in byte array as characters?

Try it:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

Example:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

How do I retrieve my MySQL username and password?

If you have root access to the server where mysql is running you should stop the mysql server using this command

sudo service mysql stop

Now start mysql using this command

sudo /usr/sbin/mysqld --skip-grant-tables  --skip-networking &

Now you can login to mysql using

sudo mysql
FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

Full instructions can be found here http://www.techmatterz.com/recover-mysql-root-password/

How to check file input size with jQuery?

Plese try this:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Random float number generation

For C++, it can generate real float numbers within the range specified by dist variable

#include <random>  //If it doesnt work then use   #include <tr1/random>
#include <iostream>

using namespace std;

typedef std::tr1::ranlux64_base_01 Myeng; 
typedef std::tr1::normal_distribution<double> Mydist;

int main() { 
       Myeng eng; 
       eng.seed((unsigned int) time(NULL)); //initializing generator to January 1, 1970);
       Mydist dist(1,10); 

       dist.reset(); // discard any cached values 
       for (int i = 0; i < 10; i++)
       {
           std::cout << "a random value == " << (int)dist(eng) << std::endl; 
       }

       return (0);
}

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

scikit-learn random state in splitting dataset

We used the random_state parameter for reproducibility of the initial shuffling of training datasets after each epoch.

Can lambda functions be templated?

I've been playing with the latest clang version 5.0.1 compiling with the -std=c++17 flag and there is now some nice support for auto type parameters for lambdas:

#include <iostream>
#include <vector>
#include <stdexcept>

int main() {
    auto slice = [](auto input, int beg, int end) {
        using T = decltype(input);
        const auto size = input.size();
        if (beg > size || end > size || beg < 0 || end < 0) {
            throw std::out_of_range("beg/end must be between [0, input.size())");
        }
        if (beg > end) {
            throw std::invalid_argument("beg must be less than end");
        }
        return T(input.begin() + beg, input.begin() + end);
    };
    auto v = std::vector<int> { 1,2,3,4,5 };
    for (auto e : slice(v, 1, 4)) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

just right click on your project, hover maven then click update project.. done!!

How to run JUnit test cases from the command line

In windows it is

java -cp .;/path/junit.jar org.junit.runner.JUnitCore TestClass [test class name without .class extension]

for example: c:\>java -cp .;f:/libraries/junit-4.8.2 org.junit.runner.JUnitCore TestSample1 TestSample2 ... and so on, if one has more than one test classes.

-cp stands for class path and the dot (.) represents the existing classpath while semi colon (;) appends the additional given jar to the classpath , as in above example junit-4.8.2 is now available in classpath to execute JUnitCore class that here we have used to execute our test classes.

Above command line statement helps you to execute junit (version 4+) tests from command prompt(i-e MSDos).

Note: JUnitCore is a facade to execute junit tests, this facade is included in 4+ versions of junit.

How to declare a variable in a template in Angular

Short answer which help to someone

  • Template Reference variable often reference to DOM element within a template.
  • Also reference to angular or web component and directive.
  • That means you can easily access the varible anywhere in a template

enter image description here

enter image description here

  • Declare reference variable using hash symbol(#)
  • Can able to pass a variable as a parameter on an event

enter image description here

  show(lastName: HTMLInputElement){
    this.fullName = this.nameInputRef.nativeElement.value + ' ' + lastName.value;
    this.ctx.fullName = this.fullName;
  }

*However, you can use ViewChild decorator to reference it inside your component.

import {ViewChild, ElementRef} from '@angular/core';

Reference firstNameInput variable inside Component

@ViewChild('firstNameInput') nameInputRef: ElementRef;

After that, you can use this.nameInputRef anywhere inside your Component.

Working with ng-template

In the case of ng-template, it is a little bit different because each template has its own set of input variables.

enter image description here

https://stackblitz.com/edit/angular-2-template-reference-variable

How many socket connections can a web server handle?

I think that the number of concurrent socket connections one web server can handle largely depends on the amount of resources each connection consumes and the amount of total resource available on the server barring any other web server resource limiting configuration.

To illustrate, if every socket connection consumed 1MB of server resource and the server has 16GB of RAM available (theoretically) this would mean it would only be able to handle (16GB / 1MB) concurrent connections. I think it's as simple as that... REALLY!

So regardless of how the web server handles connections, every connection will ultimately consume some resource.

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

PHP has a built in function called bool chmod(string $filename, int $mode )

http://php.net/function.chmod

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);
    chmod($file, 0777);  //changed to add the zero
    return true;
}

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

Python error: "IndexError: string index out of range"

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

so_far = " " * len(word)

?

Edit:

try something like

print "%d / %d" % (new, so_far)

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to retrieve Jenkins build parameters using the Groovy API?

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

How to concatenate characters in java?

this is very simple approach to concatenate or append the character

       StringBuilder desc = new StringBuilder(); 
       String Description="this is my land"; 
       desc=desc.append(Description.charAt(i));

Convert String To date in PHP

Use the strtotime function:

Example:

 $date = "25 december 2009";
 $my_date = date('m/d/y', strtotime($date));
 echo $my_date;

PHP + MySQL transactions examples

I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:

function transaction ($con, $Q){
        mysqli_query($con, "START TRANSACTION");

        for ($i = 0; $i < count ($Q); $i++){
            if (!mysqli_query ($con, $Q[$i])){
                echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
                break;
            }   
        }

        if ($i == count ($Q)){
            mysqli_query($con, "COMMIT");
            return 1;
        }
        else {
            mysqli_query($con, "ROLLBACK");
            return 0;
        }
    }

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Make sure the database tables are using InnoDB storage engine and READ-COMMITTED transaction isolation level.

You can check it by SELECT @@GLOBAL.tx_isolation, @@tx_isolation; on mysql console.

If it is not set to be READ-COMMITTED then you must set it. Make sure before setting it that you have SUPER privileges in mysql.

You can take help from http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html.

By setting this I think your problem will be get solved.


You might also want to check you aren't attempting to update this in two processes at once. Users ( @tala ) have encountered similar error messages in this context, maybe double-check that...

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

import tensorflow as tf
sess = tf.Session()

this code will show an Attribute error on version 2.x

to use version 1.x code in version 2.x

try this

import tensorflow.compat.v1 as tf
sess = tf.Session()

How to set the style -webkit-transform dynamically using JavaScript?

Here are the JavaScript notations for most common vendors:

webkitProperty
MozProperty
msProperty
OProperty
property

I reset inline transform styles like:

element.style.webkitTransform = "";
element.style.MozTransform = "";
element.style.msTransform = "";
element.style.OTransform = "";
element.style.transform = "";

And like this using jQuery:

$(element).css({
    "webkitTransform":"",
    "MozTransform":"",
    "msTransform":"",
    "OTransform":"",
    "transform":""
});

See blog post Coding Vendor Prefixes with JavaScript (2012-03-21).

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to best display in Terminal a MySQL SELECT returning too many fields?

I believe putty has a maximum number of columns you can specify for the window.

For Windows I personally use Windows PowerShell and set the screen buffer width reasonably high. The column width remains fixed and you can use a horizontal scroll bar to see the data. I had the same problem you're having now.

edit: For remote hosts that you have to SSH into you would use something like plink + Windows PowerShell

Using the passwd command from within a shell script

Nowadays, you can use this command:

echo "user:pass" | chpasswd

Sql Server : How to use an aggregate function like MAX in a WHERE clause

But its still giving an error message in Query Builder. I am using SqlServerCe 2008.

SELECT         Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount, 
                     Order_Details.TotalPrice
FROM           Order_Products INNER JOIN
                     Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
                     Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING        (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))

I replaced WHERE with HAVING as said by @powerlord. But still showing an error.

Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]

PHPMailer AddAddress()

foreach ($all_address as $aa) {
    $mail->AddAddress($aa); 
}

Regular expression that matches valid IPv6 addresses

Here's what I came up with, using a bit of lookahead and named groups. This is of course just IPv6, but it shouldn't interfere with additional patterns if you want to add IPv4:

(?=([0-9a-f]+(:[0-9a-f])*)?(?P<wild>::)(?!([0-9a-f]+:)*:))(::)?([0-9a-f]{1,4}:{1,2}){0,6}(?(wild)[0-9a-f]{0,4}|[0-9a-f]{1,4}:[0-9a-f]{1,4})

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...

Eslint: How to disable "unexpected console statement" in Node.js?

The following works with ESLint in VSCode if you want to disable the rule for just one line.

To disable the next line:

// eslint-disable-next-line no-console
console.log('hello world');

To disable the current line:

console.log('hello world'); // eslint-disable-line no-console

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

How to update record using Entity Framework Core?

A more generic approach

To simplify this approach an "id" interface is used

public interface IGuidKey
{
    Guid Id { get; set; }
}

The helper method

public static void Modify<T>(this DbSet<T> set, Guid id, Action<T> func)
    where T : class, IGuidKey, new()
{
    var target = new T
    {
        Id = id
    };
    var entry = set.Attach(target);
    func(target);
    foreach (var property in entry.Properties)
    {
        var original = property.OriginalValue;
        var current = property.CurrentValue;

        if (ReferenceEquals(original, current))
        {
            continue;
        }

        if (original == null)
        {
            property.IsModified = true;
            continue;
        }

        var propertyIsModified = !original.Equals(current);
        property.IsModified = propertyIsModified;
    }
}

Usage

dbContext.Operations.Modify(id, x => { x.Title = "aaa"; });

How to check Django version

You can do it without Python too. Just type this in your Django directory:

cat __init__.py | grep VERSION

And you will get something like:

VERSION = (1, 5, 5, 'final', 0)

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

How to change the server port from 3000?

1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:

{ "port": 1337 }

2->Using Command Line Tool Run this command in Angular-Cli

ng serve --port 1234

To change the port number permanently:

Goto

node_modules/angular-cli/commands/server.js

Search for var defaultPort = process.env.PORT || 4200; (change 4200 to anything else you want).

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

How to create an array containing 1...N

https://stackoverflow.com/a/49577331/8784402

With Delta

For javascript

smallest and one-liner
[...Array(N)].map((v, i) => from + i * step);

Examples and other alternatives

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((v, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

[...Array(10)].map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Range Function
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

From-To with steps/delta

using iterators
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

For Typescript

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

How to check if a symlink exists

Is the file really a symbolic link? If not, the usual test for existence is -r or -e.

See man test.

Change placeholder text

If you wanna use Javascript then you can use getElementsByName() method to select the input fields and to change the placeholder for each one... see the below code...

document.getElementsByName('Email')[0].placeholder='new text for email';
document.getElementsByName('First Name')[0].placeholder='new text for fname';
document.getElementsByName('Last Name')[0].placeholder='new text for lname';

Otherwise use jQuery:

$('input:text').attr('placeholder','Some New Text');

Use async await with Array.map

I had a task on BE side to find all entities from a repo, and to add a new property url and to return to controller layer. This is how I achieved it (thanks to Ajedi32's response):

async findAll(): Promise<ImageResponse[]> {
    const images = await this.imageRepository.find(); // This is an array of type Image (DB entity)
    const host = this.request.get('host');
    const mappedImages = await Promise.all(images.map(image => ({...image, url: `http://${host}/images/${image.id}`}))); // This is an array of type Object
    return plainToClass(ImageResponse, mappedImages); // Result is an array of type ImageResponse
  }

Note: Image (entity) doesn't have property url, but ImageResponse - has

What is the difference between And and AndAlso in VB.NET?

AndAlso is much like And, except it works like && in C#, C++, etc.

The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".

This is sometimes very useful, e.g. in an expression such as:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

EPPlus - Read Excel Table

There is no native but what if you use what I put in this post:

How to parse excel rows back to types using EPPlus

If you want to point it at a table only it will need to be modified. Something like this should do it:

public static IEnumerable<T> ConvertTableToObjects<T>(this ExcelTable table) where T : new()
{
    //DateTime Conversion
    var convertDateTime = new Func<double, DateTime>(excelDate =>
    {
        if (excelDate < 1)
            throw new ArgumentException("Excel dates cannot be smaller than 0.");

        var dateOfReference = new DateTime(1900, 1, 1);

        if (excelDate > 60d)
            excelDate = excelDate - 2;
        else
            excelDate = excelDate - 1;
        return dateOfReference.AddDays(excelDate);
    });

    //Get the properties of T
    var tprops = (new T())
        .GetType()
        .GetProperties()
        .ToList();

    //Get the cells based on the table address
    var start = table.Address.Start;
    var end = table.Address.End;
    var cells = new List<ExcelRangeBase>();

    //Have to use for loops insteadof worksheet.Cells to protect against empties
    for (var r = start.Row; r <= end.Row; r++)
        for (var c = start.Column; c <= end.Column; c++)
            cells.Add(table.WorkSheet.Cells[r, c]);

    var groups = cells
        .GroupBy(cell => cell.Start.Row)
        .ToList();

    //Assume the second row represents column data types (big assumption!)
    var types = groups
        .Skip(1)
        .First()
        .Select(rcell => rcell.Value.GetType())
        .ToList();

    //Assume first row has the column names
    var colnames = groups
        .First()
        .Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx })
        .Where(o => tprops.Select(p => p.Name).Contains(o.Name))
        .ToList();

    //Everything after the header is data
    var rowvalues = groups
        .Skip(1) //Exclude header
        .Select(cg => cg.Select(c => c.Value).ToList());

    //Create the collection container
    var collection = rowvalues
        .Select(row =>
        {
            var tnew = new T();
            colnames.ForEach(colname =>
            {
                //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                var val = row[colname.index];
                var type = types[colname.index];
                var prop = tprops.First(p => p.Name == colname.Name);

                //If it is numeric it is a double since that is how excel stores all numbers
                if (type == typeof(double))
                {
                    if (!string.IsNullOrWhiteSpace(val?.ToString()))
                    {
                        //Unbox it
                        var unboxedVal = (double)val;

                        //FAR FROM A COMPLETE LIST!!!
                        if (prop.PropertyType == typeof(Int32))
                            prop.SetValue(tnew, (int)unboxedVal);
                        else if (prop.PropertyType == typeof(double))
                            prop.SetValue(tnew, unboxedVal);
                        else if (prop.PropertyType == typeof(DateTime))
                            prop.SetValue(tnew, convertDateTime(unboxedVal));
                        else
                            throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                    }
                }
                else
                {
                    //Its a string
                    prop.SetValue(tnew, val);
                }
            });

            return tnew;
        });


    //Send it back
    return collection;
}

Here is a test method:

[TestMethod]
public void Table_To_Object_Test()
{
    //Create a test file
    var fi = new FileInfo(@"c:\temp\Table_To_Object.xlsx");

    using (var package = new ExcelPackage(fi))
    {
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.First();
        var ThatList = worksheet.Tables.First().ConvertTableToObjects<ExcelData>();
        foreach (var data in ThatList)
        {
            Console.WriteLine(data.Id + data.Name + data.Gender);
        }

        package.Save();
    }
}

Gave this in the console:

1JohnMale
2MariaFemale
3DanielUnknown

Just be careful if you Id field is an number or string in excel since the class is expecting a string.

How to cast List<Object> to List<MyClass>

Depending on what you want to do with the list, you may not even need to cast it to a List<Customer>. If you only want to add Customer objects to the list, you could declare it as follows:

...
List<Object> list = getList();
return (List<? super Customer>) list;

This is legal (well, not just legal, but correct - the list is of "some supertype to Customer"), and if you're going to be passing it into a method that will merely be adding objects to the list then the above generic bounds are sufficient for this.

On the other hand, if you want to retrieve objects from the list and have them strongly typed as Customers - then you're out of luck, and rightly so. Because the list is a List<Object> there's no guarantee that the contents are customers, so you'll have to provide your own casting on retrieval. (Or be really, absolutely, doubly sure that the list will only contain Customers and use a double-cast from one of the other answers, but do realise that you're completely circumventing the compile-time type-safety you get from generics in this case).

Broadly speaking it's always good to consider the broadest possible generic bounds that would be acceptable when writing a method, doubly so if it's going to be used as a library method. If you're only going to read from a list, use List<? extends T> instead of List<T>, for example - this gives your callers much more scope in the arguments they can pass in and means they are less likely to run into avoidable issues similar to the one you're having here.

Bound method error

I think you meant print test.sorted_word_list instead of print test.sort_word_list.

In addition list.sort() sorts a list in place and returns None, so you probably want to change sort_word_list() to do the following:

self.sorted_word_list = sorted(self.word_list)

You should also consider either renaming your num_words() function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call.

CSS table td width - fixed, not flexible

The above suggestions trashed the layout of my table so I ended up using:

td {
  min-width: 30px;
  max-width: 30px;
  overflow: hidden;
}

This is horrible to maintain but was easier than re-doing all the existing css for the site. Hope it helps someone else.

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.

How can you detect the version of a browser?

function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
}

This will return an array, first element is the browser name, second element is the complete version number in string format.

Convert Swift string to array

It is even easier in Swift:

let string : String = "Hello  "
let characters = Array(string)
println(characters)
// [H, e, l, l, o,  , , ,  , ]

This uses the facts that

  • an Array can be created from a SequenceType, and
  • String conforms to the SequenceType protocol, and its sequence generator enumerates the characters.

And since Swift strings have full support for Unicode, this works even with characters outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme clusters (such as , which is actually composed of two Unicode scalars).


Update: As of Swift 2, String does no longer conform to SequenceType, but the characters property provides a sequence of the Unicode characters:

let string = "Hello  "
let characters = Array(string.characters)
print(characters)

This works in Swift 3 as well.


Update: As of Swift 4, String is (again) a collection of its Characters:

let string = "Hello  "
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "", "", " ", ""]

Immutable array in Java

There is one way to make an immutable array in Java:

final String[] IMMUTABLE = new String[0];

Arrays with 0 elements (obviously) cannot be mutated.

This can actually come in handy if you are using the List.toArray method to convert a List to an array. Since even an empty array takes up some memory, you can save that memory allocation by creating a constant empty array, and always passing it to the toArray method. That method will allocate a new array if the array you pass doesn't have enough space, but if it does (the list is empty), it will return the array you passed, allowing you to reuse that array any time you call toArray on an empty List.

final static String[] EMPTY_STRING_ARRAY = new String[0];

List<String> emptyList = new ArrayList<String>();
return emptyList.toArray(EMPTY_STRING_ARRAY); // returns EMPTY_STRING_ARRAY

Can you have multiline HTML5 placeholder text in a <textarea>?

For <textarea>s the spec specifically outlines that carriage returns + line breaks in the placeholder attribute MUST be rendered as linebreaks by the browser.

User agents should present this hint to the user when the element's value is the empty string and the control is not focused (e.g. by displaying it inside a blank unfocused control). All U+000D CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF) characters in the hint, must be treated as line breaks when rendering the hint.

Also reflected on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder

FWIW, when I try on Chrome 63.0.3239.132, it does indeed work as it says it should.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

Why not use Double or Float to represent currency?

Many of the answers posted to this question discuss IEEE and the standards surrounding floating-point arithmetic.

Coming from a non-computer science background (physics and engineering), I tend to look at problems from a different perspective. For me, the reason why I wouldn't use a double or float in a mathematical calculation is that I would lose too much information.

What are the alternatives? There are many (and many more of which I am not aware!).

BigDecimal in Java is native to the Java language. Apfloat is another arbitrary-precision library for Java.

The decimal data type in C# is Microsoft's .NET alternative for 28 significant figures.

SciPy (Scientific Python) can probably also handle financial calculations (I haven't tried, but I suspect so).

The GNU Multiple Precision Library (GMP) and the GNU MFPR Library are two free and open-source resources for C and C++.

There are also numerical precision libraries for JavaScript(!) and I think PHP which can handle financial calculations.

There are also proprietary (particularly, I think, for Fortran) and open-source solutions as well for many computer languages.

I'm not a computer scientist by training. However, I tend to lean towards either BigDecimal in Java or decimal in C#. I haven't tried the other solutions I've listed, but they are probably very good as well.

For me, I like BigDecimal because of the methods it supports. C#'s decimal is very nice, but I haven't had the chance to work with it as much as I'd like. I do scientific calculations of interest to me in my spare time, and BigDecimal seems to work very well because I can set the precision of my floating point numbers. The disadvantage to BigDecimal? It can be slow at times, especially if you're using the divide method.

You might, for speed, look into the free and proprietary libraries in C, C++, and Fortran.

How to unload a package without restarting R

I tried what kohske wrote as an answer and I got error again, so I did some search and found this which worked for me (R 3.0.2):

require(splines) # package
detach(package:splines)

or also

library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)

What is the cleanest way to disable CSS transition effects temporarily?

I'd have a class in your CSS like this:

.no-transition { 
  -webkit-transition: none;
  -moz-transition: none;
  -o-transition: none;
  -ms-transition: none;
  transition: none;
}

and then in your jQuery:

$('#elem').addClass('no-transition'); //will disable it
$('#elem').removeClass('no-transition'); //will enable it

jQuery form input select by id

You can do that using the descendant selectors:

 $("#a #b")

However, id values are supposed to be unique on a page.

if statement checks for null but still throws a NullPointerException

The problem here is that in your code the program is calling 'null.length()' which is not defined if the argument passed to the function is null. That's why the exception is thrown.

Check substring exists in a string in C

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

int findSubstr(char *inpText, char *pattern);
int main()
{
    printf("Hello, World!\n");
    char *Text = "This is my sample program";
    char *pattern = "sample";
    int pos = findSubstr(Text, pattern);
    if (pos > -1) {
        printf("Found the substring at position %d \n", pos);
    }
    else
        printf("No match found \n");

    return 0;
}

int findSubstr(char *inpText, char *pattern) {
    int inplen = strlen(inpText);
    while (inpText != NULL) {

        char *remTxt = inpText;
        char *remPat = pattern;

        if (strlen(remTxt) < strlen(remPat)) {
            /* printf ("length issue remTxt %s \nremPath %s \n", remTxt, remPat); */
            return -1;
        }

        while (*remTxt++ == *remPat++) {
            printf("remTxt %s \nremPath %s \n", remTxt, remPat);
            if (*remPat == '\0') {
                printf ("match found \n");
                return inplen - strlen(inpText+1);
            }
            if (remTxt == NULL) {
                return -1;
            }
        }
        remPat = pattern;

        inpText++;
    }
}

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

Convert char array to a int number in C

I personally don't like atoi function. I would suggest sscanf:

char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

It's very standard, it's in the stdio.h library :)

And in my opinion, it allows you much more freedom than atoi, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.

EDIT I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi, sscanf and strtol. Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).

EDIT2 Looks like it's not just me personally disliking the atoi function. Here's a link to an answer explaining that the atoi function is deprecated and should not be used in newer code.

Is there a way to make text unselectable on an HTML page?

Try this:

<div onselectstart="return false">some stuff</div>

Simple, but effective... works in current versions of all major browsers.

What is the optimal way to compare dates in Microsoft SQL server?

You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN would be faster; however, in actual testing they performed the same.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
      
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
      
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
      
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
    

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

How can I clear an HTML file input with JavaScript?

I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

all the credit goes to Chris Coyier.

_x000D_
_x000D_
// Referneces_x000D_
var control = $("#control"),_x000D_
    clearBn = $("#clear");_x000D_
_x000D_
// Setup the clear functionality_x000D_
clearBn.on("click", function(){_x000D_
    control.replaceWith( control.val('').clone( true ) );_x000D_
});_x000D_
_x000D_
// Some bound handlers to preserve when cloning_x000D_
control.on({_x000D_
    change: function(){ console.log( "Changed" ) },_x000D_
     focus: function(){ console.log(  "Focus"  ) }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="control">_x000D_
<br><br>_x000D_
<a href="#" id="clear">Clear</a>
_x000D_
_x000D_
_x000D_

How do I convert strings in a Pandas data frame to a 'date' data type?

 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  object
 1   endDay          110526 non-null  object

import pandas as pd

df['startDay'] = pd.to_datetime(df.startDay)

df['endDay'] = pd.to_datetime(df.endDay)

 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  datetime64[ns]
 1   endDay          110526 non-null  datetime64[ns]

How can I set a cookie in react?

It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

What is the difference between public, protected, package-private and private in Java?

Access modifiers in Java.

Java access modifiers are used to provide access control in Java.

1. Default:

Accessible to the classes in the same package only.

For example,

// Saved in file A.java
package pack;

class A{
  void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A(); // Compile Time Error
   obj.msg(); // Compile Time Error
  }
}

This access is more restricted than public and protected, but less restricted than private.

2. Public

Can be accessed from anywhere. (Global Access)

For example,

// Saved in file A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

// Saved in file B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
    A obj = new A();
    obj.msg();
  }
}

Output:Hello

3. Private

Accessible only inside the same class.

If you try to access private members on one class in another will throw compile error. For example,

class A{
  private int data = 40;
  private void msg(){System.out.println("Hello java");}
}

public class Simple{
  public static void main(String args[]){
    A obj = new A();
    System.out.println(obj.data); // Compile Time Error
    obj.msg(); // Compile Time Error
  }
}

4. Protected

Accessible only to the classes in the same package and to the subclasses

For example,

// Saved in file A.java
package pack;
public class A{
  protected void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B extends A{
  public static void main(String args[]){
    B obj = new B();
    obj.msg();
  }
}

Output: Hello

Enter image description here

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

Putting text in top left corner of matplotlib plot

You can use text.

text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::

text(0.5, 0.5,'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:

enter image description here

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

uppercase first character in a variable with bash

just for fun here you are :

foo="bar";    

echo $foo | awk '{$1=toupper(substr($1,0,1))substr($1,2)}1'
# or
echo ${foo^}
# or
echo $foo | head -c 1 | tr [a-z] [A-Z]; echo $foo | tail -c +2
# or
echo ${foo:1} | sed -e 's/^./\B&/'

How to extract this specific substring in SQL Server?

Combine the SUBSTRING(), LEFT(), and CHARINDEX() functions.

SELECT LEFT(SUBSTRING(YOUR_FIELD,
                      CHARINDEX(';', YOUR_FIELD) + 1, 100),
                      CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;

This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN() function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.

Locate Git installation folder on Mac OS X

You can also try with /usr/local/bin/git it worked for me

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

A very short way to do it is just right click on the activity_main.xml design background and select convert view then select Relativealayout. Your code in Xml Text will auto. Change. Goodluck

What does the restrict keyword mean in C++?

This is the original proposal to add this keyword. As dirkgently pointed out though, this is a C99 feature; it has nothing to do with C++.

How to get access to raw resources that I put in res folder?

InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

setting request headers in selenium

You can do it with PhantomJSDriver.

PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
            "this.onResourceRequested = function(request, net) {" +
            "   net.setHeader('header-name', 'header-value')" +
            "};");

Using the request object, you can filter also so the header won't be set for every request.

C# Reflection: How to get class reference from string?

You can use Type.GetType(string), but you'll need to know the full class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use Assembly.GetType(typeName) instead - I find that easier in terms of getting the assembly reference right!)

For instance:

// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");

// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");

// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " + 
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
    "PublicKeyToken=b77a5c561934e089");

Adding a column to a data.frame

You can add a column to your data using various techniques. The quotes below come from the "Details" section of the relevant help text, [[.data.frame.

Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list.

my.dataframe["new.col"] <- a.vector
my.dataframe[["new.col"]] <- a.vector

The data.frame method for $, treats x as a list

my.dataframe$new.col <- a.vector

When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix

my.dataframe[ , "new.col"] <- a.vector

Since the method for data.frame assumes that if you don't specify if you're working with columns or rows, it will assume you mean columns.


For your example, this should work:

# make some fake data
your.df <- data.frame(no = c(1:4, 1:7, 1:5), h_freq = runif(16), h_freqsq = runif(16))

# find where one appears and 
from <- which(your.df$no == 1)
to <- c((from-1)[-1], nrow(your.df)) # up to which point the sequence runs

# generate a sequence (len) and based on its length, repeat a consecutive number len times
get.seq <- mapply(from, to, 1:length(from), FUN = function(x, y, z) {
            len <- length(seq(from = x[1], to = y[1]))
            return(rep(z, times = len))
         })

# when we unlist, we get a vector
your.df$group <- unlist(get.seq)
# and append it to your original data.frame. since this is
# designating a group, it makes sense to make it a factor
your.df$group <- as.factor(your.df$group)


   no     h_freq   h_freqsq group
1   1 0.40998238 0.06463876     1
2   2 0.98086928 0.33093795     1
3   3 0.28908651 0.74077119     1
4   4 0.10476768 0.56784786     1
5   1 0.75478995 0.60479945     2
6   2 0.26974011 0.95231761     2
7   3 0.53676266 0.74370154     2
8   4 0.99784066 0.37499294     2
9   5 0.89771767 0.83467805     2
10  6 0.05363139 0.32066178     2
11  7 0.71741529 0.84572717     2
12  1 0.10654430 0.32917711     3
13  2 0.41971959 0.87155514     3
14  3 0.32432646 0.65789294     3
15  4 0.77896780 0.27599187     3
16  5 0.06100008 0.55399326     3

Validate Dynamically Added Input fields

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate();
    });

    function addInput() {

        var indexVal = $("#index").val();
        var index = parseInt(indexVal) + 1
        var obj = '<input id="list'+index+'" name=list['+index+']  class="required" />'
        $("#parent").append(obj);

        $("#list"+index).rules("add", "required");
        $("#index").val(index)
    }
</script>

<form id="commentForm" method="get" action="">
    <input type="hidden" name="index" name="list[1]" id="index" value="1">
    <p id="parent">
        <input id="list1"  class="required" />
    </p>
    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

Variable is accessed within inner class. Needs to be declared final

The error says it all, change:

ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

to

final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

Opening Chrome From Command Line

C:\>start chrome "http://site1.com" works on Windows Vista.

How to get height of entire document with JavaScript?

I don't know about determining height just now, but you can use this to put something on the bottom:

<html>
<head>
<title>CSS bottom test</title>
<style>
.bottom {
  position: absolute;
  bottom: 1em;
  left: 1em;
}
</style>
</head>

<body>

<p>regular body stuff.</p>

<div class='bottom'>on the bottom</div>

</body>
</html>

C# Create New T()

Since this is tagged C# 4. With the open sourece framework ImpromptuIntereface it will use the dlr to call the constructor it is significantly faster than Activator when your constructor has arguments, and negligibly slower when it doesn't. However the main advantage is that it will handle constructors with C# 4.0 optional parameters correctly, something that Activator won't do.

protected T GetObject(params object[] args)
{
    return (T)Impromptu.InvokeConstructor(typeof(T), args);
}

Android, How to create option Menu

Good Day I was checked And if You choose Empty Activity You Don't have build in Menu functions For Build in You must choose Basic Activity In this way You Activity will run onCreateOptionsMenu

Or if You work in Empty Activity from start Chenge in styles.xml the

What is (functional) reactive programming?

It is about mathematical data transformations over time (or ignoring time).

In code this means functional purity and declarative programming.

State bugs are a huge problem in the standard imperative paradigm. Various bits of code may change some shared state at different "times" in the programs execution. This is hard to deal with.

In FRP you describe (like in declarative programming) how data transforms from one state to another and what triggers it. This allows you to ignore time because your function is simply reacting to its inputs and using their current values to create a new one. This means that the state is contained in the graph (or tree) of transformation nodes and is functionally pure.

This massively reduces complexity and debugging time.

Think of the difference between A=B+C in math and A=B+C in a program. In math you are describing a relationship that will never change. In a program, its says that "Right now" A is B+C. But the next command might be B++ in which case A is not equal to B+C. In math or declarative programming A will always be equal to B+C no matter what point in time you ask.

So by removing the complexities of shared state and changing values over time. You program is much easier to reason about.

An EventStream is an EventStream + some transformation function.

A Behaviour is an EventStream + Some value in memory.

When the event fires the value is updated by running the transformation function. The value that this produces is stored in the behaviours memory.

Behaviours can be composed to produce new behaviours that are a transformation on N other behaviours. This composed value will recalculate as the input events (behaviours) fire.

"Since observers are stateless, we often need several of them to simulate a state machine as in the drag example. We have to save the state where it is accessible to all involved observers such as in the variable path above."

Quote from - Deprecating The Observer Pattern http://infoscience.epfl.ch/record/148043/files/DeprecatingObserversTR2010.pdf

How to run C program on Mac OS X using Terminal?

First make sure you correct your program:

#include <stdio.h>

int main(void) {
   printf("Hello, world!\n"); //printf instead of pintf
   return 0;
}

Save the file as HelloWorld.c and type in the terminal:

gcc -o HelloWorld HelloWorld.c

Afterwards just run the executable like this:

./HelloWorld

You should be seeing Hello World!

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

How can I declare enums using java

enums are classes in Java. They have an implicit ordinal value, starting at 0. If you want to store an additional field, then you do it like for any other class:

public enum MyEnum {

    ONE(1),
    TWO(2);

    private final int value;

    private MyEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

This solution shows a list of applications in a ListView dialog that resembles the chooser:

screenshot

It is up to you to:

  1. obtain the list of relevant application packages
  2. given a package name, invoke the relevant intent

The adapter class:

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChooserArrayAdapter extends ArrayAdapter<String> {
    PackageManager mPm;
    int mTextViewResourceId;
    List<String> mPackages;

    public ChooserArrayAdapter(Context context, int resource, int textViewResourceId, List<String> packages) {
        super(context, resource, textViewResourceId, packages);
        mPm = context.getPackageManager();
        mTextViewResourceId = textViewResourceId;
        mPackages = packages;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String pkg = mPackages.get(position);
        View view = super.getView(position, convertView, parent);

        try {
            ApplicationInfo ai = mPm.getApplicationInfo(pkg, 0);

            CharSequence appName = mPm.getApplicationLabel(ai);
            Drawable appIcon = mPm.getApplicationIcon(pkg);

            TextView textView = (TextView) view.findViewById(mTextViewResourceId);
            textView.setText(appName);
            textView.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null);
            textView.setCompoundDrawablePadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return view;
    }

}

and its usage:

    void doXxxButton() {
        final List<String> packages = ...;
        if (packages.size() > 1) {
            ArrayAdapter<String> adapter = new ChooserArrayAdapter(MyActivity.this, android.R.layout.select_dialog_item, android.R.id.text1, packages);

            new AlertDialog.Builder(MyActivity.this)
            .setTitle(R.string.app_list_title)
            .setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item ) {
                    invokeApplication(packages.get(item));
                }
            })
            .show();
        } else if (packages.size() == 1) {
            invokeApplication(packages.get(0));
        }
    }

    void invokeApplication(String packageName) {
        // given a package name, create an intent and fill it with data
        ...
        startActivityForResult(intent, rq);
    }

How to pass command line argument to gnuplot?

You may use trick in unix/linux environment:

  1. in gnuplot program: plot "/dev/stdin" ...

  2. In command line: gnuplot program.plot < data.dat

What is the difference between MVC and MVVM?

Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)

enter image description here

MVC (Model View Controller)

  1. Models: Models contain data information. Does not call or use Controller and View. Contains the business logic and ways to represent data. Some of this data, in some form, may be displayed in the view. It can also contain logic to retrieve the data from some source.
  2. Controller: Acts as the connection between view and model. View calls Controller and Controller calls the model. It basically informs the model and/or the view to change as appropriate.
  3. View: Deals with UI part. Interacts with the user.

MVVM (Model View View Model)

ViewModel:

  1. It is the representation of the state of the view.
  2. It holds the data that’s displayed in the view.
  3. Responds to view events, aka presentation logic.
  4. Calls other functionalities for business logic processing.
  5. Never directly asks the view to display anything.

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

How to share my Docker-Image without using the Docker-Hub?

Docker images are stored as filesystem layers. Every command in the Dockerfile creates a layer. You can also create layers by using docker commit from the command line after making some changes (via docker run probably).

These layers are stored by default under /var/lib/docker. While you could (theoretically) cherry pick files from there and install it in a different docker server, is probably a bad idea to play with the internal representation used by Docker.

When you push your image, these layers are sent to the registry (the docker hub registry, by default… unless you tag your image with another registry prefix) and stored there. When pushing, the layer id is used to check if you already have the layer locally or it needs to be downloaded. You can use docker history to peek at which layers (other images) are used (and, to some extent, which command created the layer).

As for options to share an image without pushing to the docker hub registry, your best options are:

  • docker save an image or docker export a container. This will output a tar file to standard output, so you will like to do something like docker save 'dockerizeit/agent' > dk.agent.latest.tar. Then you can use docker load or docker import in a different host.

  • Host your own private registry. - Outdated, see comments See the docker registry image. We have built an s3 backed registry which you can start and stop as needed (all state is kept on the s3 bucket of your choice) which is trivial to setup. This is also an interesting way of watching what happens when pushing to a registry

  • Use another registry like quay.io (I haven't personally tried it), although whatever concerns you have with the docker hub will probably apply here too.

Get the date of next monday, tuesday, etc

The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.

How can I use random numbers in groovy?

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

As said, JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

A simpler solution could be replacing the method getLocations with:

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the other hand, if you don't have a pojo like Location, you could use:

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

jQuery get the rendered height of an element?

If i understood your question correctly, then maybe something like this would help:

function testDistance(node1, node2) {
    /* get top position of node 1 */
    let n1Pos = node1.offsetTop;
    /* get height of node 1 */
    let n1Height = node1.clientHeight;
    /* get top position of node 2 */
    let n2Pos = node2.offsetTop;
    /* get height of node 2 */
    let n2Height = node2.clientHeight;

    /* add height of both nodes */
    let heightTogether = n1Height + n2Height;
    /* calculate distance from top of node 1 to bottom of node 2 */
    let actualDistance = (n2Pos + n2Height) - n1Pos;

    /* if the distance between top of node 1 and bottom of node 2
       is bigger than their heights combined, than there is something between them */
    if (actualDistance > heightTogether) {
        /* do something here if they are not together */
        console.log('they are not together');
    } else {
        /* do something here if they are together */
        console.log('together');
    } 
}

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

How to loop through files matching wildcard in batch file

Assuming you have two programs that process the two files, process_in.exe and process_out.exe:

for %%f in (*.in) do (
    echo %%~nf
    process_in "%%~nf.in"
    process_out "%%~nf.out"
)

%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.

How to force a web browser NOT to cache images

I would use:

<img src="picture.jpg?20130910043254">

where "20130910043254" is the modification time of the file.

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.

I think there are two types of simple solutions: 1) those which come to mind first (straightforward solutions, because they are easy to come up with), 2) those which you end up with after thinking things over (because they are easy to use). Apparently, you won't always benefit if you chose to think things over. But the second options is rather underestimated, I believe. Just think why php is so popular ;)

How to try convert a string to a Guid

If all you want is some very basic error checking, you could just check the length of the string.

              string guidStr = "";
              if( guidStr.Length == Guid.Empty.ToString().Length )
                 Guid g = new Guid( guidStr );

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

What is the difference between a static and a non-static initialization code block

You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.

You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..

A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.

How do you add an SDK to Android Studio?

For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...

Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).

When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.

At that point you'll get a tiny dialog to confirm with:

Java SDK:     1.7            (e.g.)
Build target: Android 6.0    (e.g.)

You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:

Android API 23 Platform (java version "1.7.0_67")

How to plot two histograms together in R?

Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.

generate the data

carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)

You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.

## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
     main = 'Distribution of carrots and cucumbers', 
     panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
       fill = c(carrotCol, cukeCol), bty = 'n',
       border = NA)

enter image description here

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads:

  • singleton
  • session (or request)
  • thread pool of jobs

The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request.

Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case).


I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore?

How do I return multiple values from a function in C?

Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:

void foo(int *a, char *s, int size);

and call it like this:

int a;
char *s = (char *)malloc(100); /* I never know how much to allocate :) */
foo(&a, s, 100);

In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Convert java.util.date default format to Timestamp in Java

You can use DateFormat(java.text.*) to parse the date:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")

You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.

ActiveX component can't create object

Check your browser settings.

For me, using IE, the fix was to go into Tools/Internet Options, Security tab, for the relevant zone, "custom level" and check the ActiveX settings. Setting "Initialize and script ActiveX controls not marked as safe for scripting" to "Enable" fixed this problem for me.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Python: TypeError: object of type 'NoneType' has no len()

What is the purpose of this

 names = list;

? Also, no ; required in Python.

Do you want

 names = []

or

 names = list()

at the start of your program instead? Though given your particular code, there's no need for this statement to create this names variable since you do so later when you read data into it from your file.

@JBernardo has already pointed out the other (and more major) problem with the code.

Angular: How to download a file from HttpClient?

Using Blob as a source for an img:

template:

<img [src]="url">

component:

 public url : SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('/api/image.jpg').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

Further reference about trusting save values

How can I divide two integers stored in variables in Python?

if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b

Try float(a)/b

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''

#or 

delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

Division of integers in Java

As explain by the JLS, integer operation are quite simple.

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

So to make it short, an operation would always result in a int at the only exception that there is a long value in it.

int = int + int
long = int + long
int = short + short

Note that the priority of the operator is important, so if you have

long = int * int + long

the int * int operation would result in an int, it would be promote into a long during the operation int + long

How to call Base Class's __init__ method from the child class?

You can call the super class's constructor like this

class A(object):
    def __init__(self, number):
        print "parent", number

class B(A):
    def __init__(self):
        super(B, self).__init__(5)

b = B()

NOTE:

This will work only when the parent class inherits object

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

Using a scanner to accept String input and storing in a String Array

There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

How to open a new file in vim in a new window

Check out gVim. You can launch that in its own window.

gVim makes it really easy to manage multiple open buffers graphically.

You can also do the usual :e to open a new file, CTRL+^ to toggle between buffers, etc...

Another cool feature lets you open a popup window that lists all the buffers you've worked on.

This allows you to switch between open buffers with a single click.

To do this, click on the Buffers menu at the top and click the dotted line with the scissors.

enter image description here

Otherwise you can just open a new tab from your terminal session and launch vi from there.

You can usually open a new tab from terminal with CTRL+T or CTRL+ALT+T

Once vi is launched, it's easy to open new files and switch between them.

Error while trying to run project: Unable to start program. Cannot find the file specified

I am only posting this because I had a specific issue with the command line arguments I was passing in. Being inexperienced with the command line I was using "<" and ">" in my arguments and it was redirecting the file on me. Hope this helps someone.

C# Help reading foreign characters using StreamReader

For swedish Å Ä Ö the only solution form the ones above working was:

Encoding.GetEncoding("iso-8859-1")

Hopefully this will save someone time.

Best way to handle multiple constructors in Java

A slightly simplified answer:

public class Book
{
    private final String title;

    public Book(String title)
    {
      this.title = title;
    }

    public Book()
    {
      this("Default Title");
    }

    ...
}

How do you uninstall MySQL from Mac OS X?

OS version: 10.14.6 MYSQL version: 8.0.14

Goto System preferences -> MYSQLenter image description here

Stop MySQL server

enter image description here

One option will be shown here to uninstall MYSQL 8 after stopping Mysql server

Adding three months to a date in PHP

Tchoupi's answer can be made a tad less verbose by concatenating the argument for strtotime() as follows:

$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );

(This relies on magic implementation details, but you can always go have a look at them if you're rightly mistrustful.)

How to find indices of all occurrences of one string in another in JavaScript?

I would recommend Tim's answer. However, this comment by @blazs states "Suppose searchStr=aaa and that str=aaaaaa. Then instead of finding 4 occurences your code will find only 2 because you're making skips by searchStr.length in the loop.", which is true by looking at Tim's code, specifically this line here: startIndex = index + searchStrLen; Tim's code would not be able to find an instance of the string that's being searched that is within the length of itself. So, I've modified Tim's answer:

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + 1;
    }
    return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);

document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Changing it to + 1 instead of + searchStrLen will allow the index 1 to be in the indices array if I have an str of aaaaaa and a searchStr of aaa.

P.S. If anyone would like comments in the code to explain how the code works, please say so, and I'll be happy to respond to the request.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

Reading a text file and splitting it into single words in python

with open(filename) as file:
    words = file.read().split()

Its a List of all words in your file.

import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())

Using LIKE in an Oracle IN clause

You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.

select tabl1.* FROM tabl1 LEFT JOIN 
(select column_value txt from table(sys.ODCIVARCHAR2LIST
('%val1%','%val2%','%val3%')
)) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL

Convert form data to JavaScript object with jQuery

Ok, I know this already has a highly upvoted answer, but another similar question was asked recently, and I was directed to this question as well. I'd like to offer my solution as well, because it offers an advantage over the accepted solution: You can include disabled form elements (which is sometimes important, depending on how your UI functions)

Here is my answer from the other SO question:

Initially, we were using jQuery's serializeArray() method, but that does not include form elements that are disabled. We will often disable form elements that are "sync'd" to other sources on the page, but we still need to include the data in our serialized object. So serializeArray() is out. We used the :input selector to get all input elements (both enabled and disabled) in a given container, and then $.map() to create our object.

var inputs = $("#container :input");
var obj = $.map(inputs, function(n, i)
{
    var o = {};
    o[n.name] = $(n).val();
    return o;
});
console.log(obj);

Note that for this to work, each of your inputs will need a name attribute, which will be the name of the property of the resulting object.

That is actually slightly modified from what we used. We needed to create an object that was structured as a .NET IDictionary, so we used this: (I provide it here in case it's useful)

var obj = $.map(inputs, function(n, i)
{
    return { Key: n.name, Value: $(n).val() };
});
console.log(obj);

I like both of these solutions, because they are simple uses of the $.map() function, and you have complete control over your selector (so, which elements you end up including in your resulting object). Also, no extra plugin required. Plain old jQuery.

Changing image size in Markdown

For R-Markdown, neither of the above solutions worked for me, so I turned to regular LaTeX syntax, which works just fine.

\begin{figure}
 \includegraphics[width=300pt, height = 125 pt]{drawing.jpg}
\end{figure}

Then you can use e.g. the \begin{center} statement to center the image.

Android: Bitmaps loaded from gallery are rotated in ImageView

Use a Utility to do the Heavy Lifting.

9re created a simple utility to handle the heavy lifting of dealing with EXIF data and rotating images to their correct orientation.

You can find the utility code here: https://gist.github.com/9re/1990019

Simply download this, add it to your project's src directory and use ExifUtil.rotateBitmap() to get the correct orientation, like so:

String imagePath = photoFile.getAbsolutePath();             // photoFile is a File class.
Bitmap myBitmap  = BitmapFactory.decodeFile(imagePath);

Bitmap orientedBitmap = ExifUtil.rotateBitmap(imagePath, myBitmap);

Clone an image in cv2 python

If you use cv2, correct method is to use .copy() method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.

eg:

In [1]: import numpy as np

In [2]: x = np.arange(10*10).reshape((10,10))

In [4]: y = x[3:7,3:7].copy()

In [6]: y[2,2] = 1000

In [8]: 1000 in x
Out[8]: False     # see, 1000 in y doesn't change values in x, parent array.

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

sh: 0: getcwd() failed: No such file or directory on cited drive

Even i was having the same problem with python virtualenv It got corrected by a simple restart

sudo shutdown -r now

How can I calculate divide and modulo for integers in C#?

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

How do I get my Maven Integration tests to run

You should use maven surefire plugin to run unit tests and maven failsafe plugin to run integration tests.

Please follow below if you wish to toggle the execution of these tests using flags.

Maven Configuration

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skipTests>${skipUnitTests}</skipTests>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*IT.java</include>
                </includes>
                <skipTests>${skipIntegrationTests}</skipTests>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <properties>
            <skipTests>false</skipTests>
            <skipUnitTests>${skipTests}</skipUnitTests>
            <skipIntegrationTests>${skipTests}</skipIntegrationTests>
        </properties>

So, tests will be skipped or switched according to below flag rules:

Tests can be skipped by below flags:

  • -DskipTests skips both unit and integration tests
  • -DskipUnitTests skips unit tests but executes integration tests
  • -DskipIntegrationTests skips integration tests but executes unit tests

Running Tests

Run below to execute only Unit Tests

mvn clean test

You can execute below command to run the tests (both unit and integration)

mvn clean verify

In order to run only Integration Tests, follow

mvn failsafe:integration-test

Or skip unit tests

mvn clean install -DskipUnitTests

Also, in order to skip integration tests during mvn install, follow

mvn clean install -DskipIntegrationTests

You can skip all tests using

mvn clean install -DskipTests

Combine several images horizontally with Python

Edit: DTing's answer is more applicable to your question since it uses PIL, but I'll leave this up in case you want to know how to do it in numpy.

Here is a numpy/matplotlib solution that should work for N images (only color images) of any size/shape.

import numpy as np
import matplotlib.pyplot as plt

def concat_images(imga, imgb):
    """
    Combines two color image ndarrays side-by-side.
    """
    ha,wa = imga.shape[:2]
    hb,wb = imgb.shape[:2]
    max_height = np.max([ha, hb])
    total_width = wa+wb
    new_img = np.zeros(shape=(max_height, total_width, 3))
    new_img[:ha,:wa]=imga
    new_img[:hb,wa:wa+wb]=imgb
    return new_img

def concat_n_images(image_path_list):
    """
    Combines N color images from a list of image paths.
    """
    output = None
    for i, img_path in enumerate(image_path_list):
        img = plt.imread(img_path)[:,:,:3]
        if i==0:
            output = img
        else:
            output = concat_images(output, img)
    return output

Here is example use:

>>> images = ["ronda.jpeg", "rhod.jpeg", "ronda.jpeg", "rhod.jpeg"]
>>> output = concat_n_images(images)
>>> import matplotlib.pyplot as plt
>>> plt.imshow(output)
>>> plt.show()

enter image description here

Neither BindingResult nor plain target object for bean name available as request attribute

I had a similar problem in IntelliJ IDEA. My code was 100% correct, but after starting the Tomcat, you receive an exception. java.lang.IllegalStateException: Neither BindingResult

I just removed and added again Tomcat configuration. And it worked for me.

A picture Tomcat configuration

enter image description here

to_string not declared in scope

You need to make some changes in the compiler. In Dev C++ Compiler: 1. Go to compiler settings/compiler Options. 2. Click on General Tab 3. Check the checkbox (Add the following commands when calling the compiler. 4. write -std=c++11 5. click Ok

Detecting touch screen devices with Javascript

For iPad development I am using:

  if (window.Touch)
  {
    alert("touchy touchy");
  }
  else
  {
    alert("no touchy touchy");
  }

I can then selectively bind to the touch based events (eg ontouchstart) or mouse based events (eg onmousedown). I haven't yet tested on android.

How do I include a pipe | in my linux find -exec command?

The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).

In your example you can either choose to use your top level shell to perform the piping like so:

find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'

In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.

This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.

If you for some reason would like to invoke agrep multiple times, you can do:

find . -name 'file_*' -follow -type f \
    -printf "zcat %p | agrep -dEOE 'grep'\n" | sh

This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)

In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.

The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.

How to increase the timeout period of web service in asp.net?

In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this

<binding name="WebServiceName" receiveTimeout="00:00:59" />

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can get Google Drive to automatically convert csv files to Google Sheets by appending

?convert=true

to the end of the api url you are calling.

EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert

Also, while searching for the above link, I found this question has already been answered here:

Upload CSV to Google Drive Spreadsheet using Drive v2 API

What is a JavaBean exactly?

A Java Bean is a component or the basic building block in the JavaBeans architecture. The JavaBeans architecture is a component architecture that benefits from reusability and interoperability of a component-based approach.

A valid component architecture should allow programs to be assembled from software building blocks (Beans in this case), perhaps provided by different vendors and also make it possible for an architect / developer to select a component (Bean), understand its capabilities, and incorporate it into an application.

Since classes/objects are the basic building blocks of an OOP language like Java, they are the natural contenders for being the Bean in the JavaBeans architecture.

The process of converting a plain Java class to a Java bean is actually nothing more than making it a reusable and interoperable component. This would translate into a Java class having abilities like:

  1. controlling the properties, events, and methods of a class that are exposed to another application. (You can have a BeanInfo class that reports only those properties, events and methods that the external application needs.)
  2. persistence (being serialisable or externizable - this would also imply having no-argument constructors, using transient for fields)
  3. ability to register for events and also to generate events (e.g., making use of bound and constraint properties)
  4. customizers (to customise the Bean via GUIs or by providing documentation)

In order for a Java class to be termed a Java bean it is not necessary that they need to possess all the above abilities. Instead, it implies to implement a subset of the above relevant to the context (e.g., a bean in a certain framework may not need customizers, some other bean may not need bound and constrained properties, etc.)

Almost all leading frameworks and libraries in Java adhere to the JavaBeans architecture implicitly, in order to reap the above benefits.

How does one generate a random number in Apple's Swift language?

Use arc4random_uniform(n) for a random integer between 0 and n-1.

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

How to Get a Specific Column Value from a DataTable?

As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

cannot connect to pc-name\SQLEXPRESS

My issue occurs when I add a PC to a domain. Restarting the service, making sure it's running, that it has the correct credentials to run, etc, as in other answers doesn't work. I don't know exactly what the problem is, but I can't even log in with the local user anymore to give the domain user access. Here's the steps that work for me:

In SSMS

  • View > Registered Servers
  • Database Engine > Local Server Groups > right-click pcname\sqlexpress
  • Delete > Yes
  • Right-click Local Server Groups > Tasks > Register Local Servers
  • It confirms that it re-registered. pcname\sqlexpress reappears.

I'm then able to log in with the local windows auth'd user again, my databases are all there and everything. I then go about my business adding the domain user to Security > Logins.

How to strip HTML tags with jQuery?

The safest way is to rely on the browser TextNode to correctly escape content. Here's an example:

_x000D_
_x000D_
function stripHTML(dirtyString) {_x000D_
  var container = document.createElement('div');_x000D_
  var text = document.createTextNode(dirtyString);_x000D_
  container.appendChild(text);_x000D_
  return container.innerHTML; // innerHTML will be a xss safe string_x000D_
}_x000D_
_x000D_
document.write( stripHTML('<p>some <span>content</span></p>') );_x000D_
document.write( stripHTML('<script><p>some <span>content</span></p>') );
_x000D_
_x000D_
_x000D_

The thing to remember here is that the browser escape the special characters of TextNodes when we access the html strings (innerHTML, outerHTML). By comparison, accessing text values (innerText, textContent) will yield raw strings, meaning they're unsafe and could contains XSS.

If you use jQuery, then using .text() is safe and backward compatible. See the other answers to this question.

The simplest way in pure JavaScript if you work with browsers <= Internet Explorer 8 is:

string.replace(/(<([^>]+)>)/ig,"");

But there's some issue with parsing HTML with regex so this won't provide very good security. Also, this only takes care of HTML characters, so it is not totally xss-safe.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Normally we face this issue when there is a problem mapping JSON node with that of Java object. I faced the same issue because in the swagger the node was defined as of Type array and the JSON object was having only one element , hence the system was having difficulty in mapping one element list to an array.

In Swagger the element was defined as

Test:
 "type": "array",
 "minItems": 1,
 "items": {
   "$ref": "#/definitions/TestNew"
  }

While it should be

Test:
    "$ref": "#/definitions/TestNew"

And TestNew should be of type array

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

mysql datatype for telephone number and address

Consider normalizing to E.164 format. For full international support, you'd need a VARCHAR of 15 digits.

See Twilio's recommendation for more information on localization of phone numbers.

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

How to remove space from string?

A funny way to remove all spaces from a variable is to use printf:

$ myvar='a cool variable    with   lots of   spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit

It turns out it's slightly more efficient than myvar="${myvar// /}", but not safe regarding globs (*) that can appear in the string. So don't use it in production code.

If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f (which disables globbing altogether):

$ ls
file1  file2
$ myvar='  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it'
$ echo "$myvar"
  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f

I posted this answer just because it's funny, not to use it in practice.

How to check if a file exists from a url

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

In PowerShell, how can I test if a variable holds a numeric value?

You can check whether the variable is a number like this: $val -is [int]

This will work for numeric values, but not if the number is wrapped in quotes:

1 -is [int]
True
"1" -is [int]
False

How to create an array of object literals in a loop?

var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
    arr.push({
        key: oFullResponse.results[i].label,
        sortable: true,
        resizeable: true
    });
}

How to set JAVA_HOME environment variable on Mac OS X 10.9?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

Is there an easy way to strike through text in an app widget?

You can use this:

remoteviews.setInt(R.id.YourTextView, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

Of course you can also add other flags from the android.graphics.Paint class.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

Mine was more of a mistake, what happened was loop click(i guess) basically by clicking on the login the parent was also clicked which ended up causing Maximum call stack size exceeded.

$('.clickhere').click(function(){
   $('.login').click();
});

<li class="clickhere">
  <a href="#" class="login">login</a>
</li>

Working Copy Locked

I am sure It working fine for you

Goto top level SVN folder.

Right Click on folder(that has your svn files) -> TortoiseSVN -> CleanUp

This will surely solve your problem.

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

How to clear Flutter's Build cache?

you can run flutter clean command

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

I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).

Using Javac

If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac with the @ prefix.

If you can create a list of all the *.java files in your project, it's easy:

# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt

:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
  • The advantage is that is is a quick and easy solution.
  • The drawback is that you have to regenerate the sources.txt file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.

Using a build tool

On the long run it is better to use a tool that was designed to build software.

Using Ant

If you create a simple build.xml file that describes how to build the software:

<project default="compile">
    <target name="compile">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin"/>
    </target>
</project>

you can compile the whole software by running the following command:

$ ant
  • The advantage is that you are using a standard build tool that is easy to extend.
  • The drawback is that you have to download, set up and learn an additional tool. Note that most of the IDEs (like NetBeans and Eclipse) offer great support for writing build files so you don't have to download anything in this case.

Using Maven

Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.

  • It's main advantage (for me) is that it handles dependencies too, so you won't need to download any more Jar files and manage them by hand and I found it more useful for building, packaging and testing larger projects.
  • The drawback is that it has a steep learning curve, and if Maven plugins like to suppress errors :-) Another thing is that quite a lot of tools also operate with Maven repositories (like Sbt for Scala, Ivy for Ant, Graddle for Groovy).

Using an IDE

Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.

They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException.

One additional note

For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.