Programs & Examples On #Sunrpc

Sun's Remote Procedure Call is a set of services used by many Unix systems, like NFS (Network File System).

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

WPF loading spinner

use an enum type to indicate your ViewModel's State

public enum ViewModeType
{
    Default, 
    Busy
    //etc.
}

then in your ViewModels Base class use a property

public ViewModeType ViewMode
{
    get { return this.viewMode; }
    set
    {
        if (this.viewMode != value)
        {
            this.viewMode = value;
                            //You should notify property changed here
        }
    }
}

and in view trigger the ViewMode and if it is busy show busyindicator:

<Trigger Property="ViewMode" Value="Busy">
    <!-- Show BusyIndicator -->
</Trigger>

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

If you are upgrading from an older version of apache2, make sure your apache sites-available conf files end in .conf and are enabled with a2ensite

Could not find method android() for arguments

My issue was inside of my app.gradle. I ran into this issue when I moved

apply plugin: "com.android.application"

from the top line to below a line with

apply from:

I switched the plugin back to the top and violá

My exact error was

Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.

The top of my app.gradle now looks like this

project.ext.envConfigFiles = [
        debug: ".env",
        release: ".env",
        anothercustombuild: ".env",
]


apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

Comparing two columns, and returning a specific adjacent cell in Excel

Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)

You should then be able to copy this down to the rest of column D.

What are unit tests, integration tests, smoke tests, and regression tests?

  • Unit test: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are stubbed or mocked.

  • Integration test: Test the correct inter-operation of multiple subsystems. There is whole spectrum there, from testing integration between two classes, to testing integration with the production environment.

  • Smoke test (aka sanity check): A simple integration test where we just check that when the system under test is invoked it returns normally and does not blow up.

    • Smoke testing is both an analogy with electronics, where the first test occurs when powering up a circuit (if it smokes, it's bad!)...
    • ... and, apparently, with plumbing, where a system of pipes is literally filled by smoke and then checked visually. If anything smokes, the system is leaky.
  • Regression test: A test that was written when a bug was fixed. It ensures that this specific bug will not occur again. The full name is "non-regression test". It can also be a test made prior to changing an application to make sure the application provides the same outcome.

To this, I will add:

  • Acceptance test: Test that a feature or use case is correctly implemented. It is similar to an integration test, but with a focus on the use case to provide rather than on the components involved.

  • System test: Tests a system as a black box. Dependencies on other systems are often mocked or stubbed during the test (otherwise it would be more of an integration test).

  • Pre-flight check: Tests that are repeated in a production-like environment, to alleviate the 'builds on my machine' syndrome. Often this is realized by doing an acceptance or smoke test in a production like environment.

Yarn: How to upgrade yarn version using terminal?

I updated yarn on my Ubuntu by running the following command from my terminal

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

source:https://yarnpkg.com/lang/en/docs/cli/self-update

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

Getting Excel to refresh data on sheet from within VBA

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

Path.Combine for URLs?

An easy way to combine them and ensure it's always correct is:

string.Format("{0}/{1}", Url1.Trim('/'), Url2);

Pass parameter to controller from @Html.ActionLink MVC 4

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

In git how is fetch different than pull and how is merge different than rebase?

pull vs fetch:

The way I understand this, is that git pull is simply a git fetch followed by git merge. I.e. you fetch the changes from a remote branch and then merge it into the current branch.


merge vs rebase:

A merge will do as the command says; merge the differences between current branch and the specified branch (into the current branch). I.e. the command git merge another_branch will the merge another_branch into the current branch.

A rebase works a bit differently and is kind of cool. Let's say you perform the command git rebase another_branch. Git will first find the latest common version between the current branch and another_branch. I.e. the point before the branches diverged. Then git will move this divergent point to the head of the another_branch. Finally, all the commits in the current branch since the original divergent point are replayed from the new divergent point. This creates a very clean history, with fewer branches and merges.

However, it is not without pitfalls! Since the version history is "rewritten", you should only do this if the commits only exists in your local git repo. That is: Never do this if you have pushed the commits to a remote repo.

The explanation on rebasing given in this online book is quite good, with easy-to-understand illustrations.


pull with rebasing instead of merge

I'm actually using rebase quite a lot, but usually it is in combination with pull:

git pull --rebase

will fetch remote changes and then rebase instead of merge. I.e. it will replay all your local commits from the last time you performed a pull. I find this much cleaner than doing a normal pull with merging, which will create an extra commit with the merges.

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

How to add line breaks to an HTML textarea?

Maybe someone find this useful:

I had problem with line breaks which were passed from server variable to javascript variable, and then javascript was writing them to textarea (using knockout.js value bindings).

the solution was double escaping new lines:

orginal.Replace("\r\n", "\\r\\n")

on the server side, because with just single escape chars javascript was not parsing.

Difference between JSON.stringify and JSON.parse

JSON.stringify(obj [, replacer [, space]]) - Takes any serializable object and returns the JSON representation as a string.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Is there a way to check if a file is in use?

Use this to check if a file is locked:

using System.IO;
using System.Runtime.InteropServices;
internal static class Helper
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
    int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
    return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}

internal static bool CanReadFile(string filePath)
{
    //Try-Catch so we dont crash the program and can check the exception
    try {
        //The "using" is important because FileStream implements IDisposable and
        //"using" will avoid a heap exhaustion situation when too many handles  
        //are left undisposed.
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
            if (fileStream != null) fileStream.Close();  //This line is me being overly cautious, fileStream will never be null unless an exception occurs... and I know the "using" does it but its helpful to be explicit - especially when we encounter errors - at least for me anyway!
        }
    }
    catch (IOException ex) {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex)) {
            // do something, eg File.Copy or present the user with a MsgBox - I do not recommend Killing the process that is locking the file
            return false;
        }
    }
    finally
    { }
    return true;
}
}

For performance reasons I recommend you read the file content in the same operation. Here are some examples:

public static byte[] ReadFileBytes(string filePath)
{
    byte[] buffer = null;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                sum += count;  // sum is a buffer offset for next reading

            fileStream.Close(); //This is not needed, just me being paranoid and explicitly releasing resources ASAP
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
    return buffer;
}

public static string ReadFileTextWithEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            //Depending on the encoding you wish to use - I'll leave that up to you
            fileContents = System.Text.Encoding.Default.GetString(buffer);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    { }     
    return fileContents;
}

public static string ReadFileTextNoEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) 
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            char[] chars = new char[buffer.Length / sizeof(char) + 1];
            System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
            fileContents = new string(chars);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }

    return fileContents;
}

Try it out yourself:

byte[] output1 = Helper.ReadFileBytes(@"c:\temp\test.txt");
string output2 = Helper.ReadFileTextWithEncoding(@"c:\temp\test.txt");
string output3 = Helper.ReadFileTextNoEncoding(@"c:\temp\test.txt");

Sharing a URL with a query string on Twitter

As @onteria_ mentioned, you need to encode the entire parameter. For anyone else facing the same issue, you can use the following bookmarklet to generate the properly encoded url. Copy paste it into your browser's address bar to create the twitter share url. Make sure that the javascript: prefix is there when you copy it into address bar, Google Chrome removes it when copying.

javascript:(function(){var url=prompt("Enter the url to share");if(url)prompt("Share the following url - ","http://www.twitter.com/share?url="+encodeURIComponent(url))})();

Source on JS Fiddle http://jsfiddle.net/2frkV/

warning: assignment makes integer from pointer without a cast

The warning comes from the fact that you're dereferencing src in the assignment. The expression *src has type char, which is an integral type. The expression "anotherstring" has type char [14], which in this particular context is implicitly converted to type char *, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the * from *src, and it should work as expected:

src = "anotherstring";

since the type of src is char *.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I had this problem when i was trying to query by passing a Set and i didn't used In

example

problem : repository.findBySomeSetOfData(setOfData);

solution : repository.findBySomeSetOfDataIn(setOfData);

Can I use VARCHAR as the PRIMARY KEY?

A blanket "no you shouldn't" is terrible advice. This is perfectly reasonable in many situations depending on your use case, workload, data entropy, hardware, etc.. What you shouldn't do is make assumptions.

It should be noted that you can specify a prefix which will limit MySQL's indexing, thereby giving you some help in narrowing down the results before scanning the rest. This may, however, become less useful over time as your prefix "fills up" and becomes less unique.

It's very simple to do, e.g.:

CREATE TABLE IF NOT EXISTS `foo` (
  `id` varchar(128),
  PRIMARY KEY (`id`(4))
)

Also note that the prefix (4) appears after the column quotes. Where the 4 means that it should use the first 4 characters of the 128 possible characters that can exist as the id.

Lastly, you should read how index prefixes work and their limitations before using them: https://dev.mysql.com/doc/refman/8.0/en/create-index.html

How to select all records from one table that do not exist in another table?

This is pure set theory which you can achieve with the minus operation.

select id, name from table1
minus
select id, name from table2

Spark specify multiple column conditions for dataframe join

There is a Spark column/expression API join for such case:

Leaddetails.join(
    Utm_Master, 
    Leaddetails("LeadSource") <=> Utm_Master("LeadSource")
        && Leaddetails("Utm_Source") <=> Utm_Master("Utm_Source")
        && Leaddetails("Utm_Medium") <=> Utm_Master("Utm_Medium")
        && Leaddetails("Utm_Campaign") <=> Utm_Master("Utm_Campaign"),
    "left"
)

The <=> operator in the example means "Equality test that is safe for null values".

The main difference with simple Equality test (===) is that the first one is safe to use in case one of the columns may have null values.

Limit on the WHERE col IN (...) condition

Why not do a where IN a sub-select...

Pre-query into a temp table or something...

CREATE TABLE SomeTempTable AS
    SELECT YourColumn
    FROM SomeTable
    WHERE UserPickedMultipleRecordsFromSomeListOrSomething

then...

SELECT * FROM OtherTable
WHERE YourColumn IN ( SELECT YourColumn FROM SomeTempTable )

how to kill hadoop jobs

Use of folloing command is depreciated

hadoop job -list
hadoop job -kill $jobId

consider using

mapred job -list
mapred job -kill $jobId

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Difference between a Seq and a List in Scala

In Java terms, Scala's Seq would be Java's List, and Scala's List would be Java's LinkedList.

Note that Seq is a trait, which is equivalent to Java's interface, but with the equivalent of up-and-coming defender methods. Scala's List is an abstract class that is extended by Nil and ::, which are the concrete implementations of List.

So, where Java's List is an interface, Scala's List is an implementation.

Beyond that, Scala's List is immutable, which is not the case of LinkedList. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).

Scala's List is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector is a better choice than List, but habit is hard to break.

Seq is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq, collection.mutable.Seq and collection.immutable.Seq, and it is the latter one that is the "default" imported into scope.

There's also GenSeq and ParSeq. The latter methods run in parallel where possible, while the former is parent to both Seq and ParSeq, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

Why do I get the "Unhandled exception type IOException"?

add "throws IOException" to your method like this:

public static void main(String args[]) throws  IOException{

        FileReader reader=new FileReader("db.properties");

        Properties p=new Properties();
        p.load(reader);


    }

Android Studio Run/Debug configuration error: Module not specified

Resync your project gradle files to add the app module through Gradle

  1. In the root folder of your project, open the settings.gradle file for editing.

  2. Cut line include ':app' from the file.

  3. On Android Studio, click on the File Menu, and select Sync Project with Gradle files.

  4. After synchronisation, paste back line include ':app' to the settings.gradle file.

  5. Re-run Sync Project with Gradle files again.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

Try this:

@Override
public void onBackPressed() {
    finish();
}

UIAlertView first deprecated IOS 9

Swift version of new implementation is :

 let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
 alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
 self.presentViewController(alert, animated: true){}

How do I create a folder in VB if it doesn't exist?

Just do this:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.

Hope it helps!

-nfell2009

How to disable button in React.js

There are few typical methods how we control components render in React. enter image description here

But, I haven't used any of these in here, I just used the ref's to namespace underlying children to the component.

_x000D_
_x000D_
class AddItem extends React.Component {_x000D_
    change(e) {_x000D_
      if ("" != e.target.value) {_x000D_
        this.button.disabled = false;_x000D_
      } else {_x000D_
        this.button.disabled = true;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    add(e) {_x000D_
      console.log(this.input.value);_x000D_
      this.input.value = '';_x000D_
      this.button.disabled = true;_x000D_
    }_x000D_
_x000D_
    render() {_x000D_
        return (_x000D_
          <div className="add-item">_x000D_
          <input type="text" className = "add-item__input" ref = {(input) => this.input=input} onChange = {this.change.bind(this)} />_x000D_
          _x000D_
          <button className="add-item__button" _x000D_
          onClick= {this.add.bind(this)} _x000D_
          ref={(button) => this.button=button}>Add_x000D_
          </button>_x000D_
          </div>_x000D_
        );_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<AddItem / > , document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Build project into a JAR automatically in Eclipse

Using Thomas Bratt's answer above, just make sure your build.xml is configured properly :

<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file --> 
<project name="TestMain" default="CreateJar">
  <target name="CreateJar" description="Create Jar file">
        <jar jarfile="Test.jar" basedir="bin/" includes="**/*.class" />
  </target>
</project>

(Notice the double asterisk - it will tell build to look for .class files in all sub-directories.)

Submit form and stay on same page?

Use XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

How to get first character of string?

var string  = "Hello World";
console.log(charAt(0));

The charAt(0) is JavaScript method, It will return value based on index, here 0 is the index for first letter.

Append text to input field

If you are planning to use appending more then once, you might want to write a function:

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);
}

After you can just call it:

jQ_append('my_input_id', 'add this text');

Convert Promise to Observable

You can add a wrapper around promise functionality to return an Observable to observer.

  • Creating a Lazy Observable using defer() operator which allows you to create the Observable only when the Observer subscribes.
import { of, Observable, defer } from 'rxjs'; 
import { map } from 'rxjs/operators';


function getTodos$(): Observable<any> {
  return defer(()=>{
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        return json;
      })
  });
}

getTodos$().
 subscribe(
   (next)=>{
     console.log('Data is:', next);
   }
)

Position absolute but relative to parent

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

Example 1::

http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body.

Example 2::

http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent.

How to use OpenSSL to encrypt/decrypt files?

There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.

Here the link it is on github

https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py

Use jquery to set value of div tag

try this function $('div.total-title').text('test');

npm install errors with Error: ENOENT, chmod

The same error during global install (npm install -g mymodule) for package with a non-existing script.

In package.json:

    ...
    "bin": {
      "module": "./bin/module"
    },
    ...

But the ./bin/module did not exist, as it was named modulejs.

How to mock static methods in c# using MOQ framework?

Moq cannot mock a static member of a class.

When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.

This means changing this:

public class Foo
{
    public Foo()
    {
        Bar = new Bar();
    }
}

to

public Foo(IBar bar)
{
    Bar = bar;
}

This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.

I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?

Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.

How to get current domain name in ASP.NET

Try getting the “left part” of the url, like this:

string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.

Do note that the resulting URL will not have a trailing slash.

Should I use the datetime or timestamp data type in MySQL?

I would always use a Unix timestamp when working with MySQL and PHP. The main reason for this being the default date method in PHP uses a timestamp as the parameter, so there would be no parsing needed.

To get the current Unix timestamp in PHP, just do time();
and in MySQL do SELECT UNIX_TIMESTAMP();.

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

How do I use WPF bindings with RelativeSource?

I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.

Stylesheet not loaded because of MIME-type

I almost tried all given solutions, the problem for me was I had no MIME types option in IIS, that is I was missing this Windows feature.

The solution for me was:

"And if you're on a non-server OS like Windows 8 or 10, do a search on the start page for "Turn Windows features on or off" and enable: Internet Information Services -> World Wide Web Services -> Common HTTP Features -> Static Content"

Enable IIS Static Content

Enable IIS Static Content

Convert varchar into datetime in SQL Server

DECLARE @d char(8)
SET @d = '06082020'    /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (@d AS INT), '##/##/####') as DATETIME)

Result returned is the original date string in @d as a DateTime.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

Apply proper charset and collation to database, table and columns/fields.

I creates database and table structure using sql queries from one server to another. it creates database structure as follows:

  1. database with charset of "utf8", collation of "utf8_general_ci"
  2. tables with charset of "utf8" and collation of "utf8_bin".
  3. table columns / fields have charset "utf8" and collation of "utf8_bin".

I change collation of table and column to utf8_general_ci, and it resolves the error.

Difference between npx and npm?

Introducing npx: an npm package runner

NPM - Manages packages but doesn't make life easy executing any.
NPX - A tool for executing Node packages.

NPX comes bundled with NPM version 5.2+

NPM by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json file.

When executables are installed via NPM packages, NPM links to them:

  1. local installs have "links" created at ./node_modules/.bin/ directory.
  2. global installs have "links" created from the global bin/ directory (e.g. /usr/local/bin) on Linux or at %AppData%/npm on Windows.

Documentation you should read


NPM:

One might install a package locally on a certain project:

npm install some-package

Now let's say you want NodeJS to execute that package from the command line:

$ some-package

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

$ ./node_modules/.bin/some-package

You can technically run a locally installed package by editing your packages.json file and adding that package in the scripts section:

{
  "name": "whatever",
  "version": "1.0.0",
  "scripts": {
    "some-package": "some-package"
  }
}

Then run the script using npm run-script (or npm run):

npm run some-package

NPX:

npx will check whether <command> exists in $PATH, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package all you need to do is type:

npx some-package

Another major advantage of npx is the ability to execute a package which wasn't previously installed:

$ npx create-react-app my-app

The above example will generate a react app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.


Use-Case Example:

npx command may be helpful in the script section of a package.json file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

"scripts": {
    "start": "npx [email protected]",
    "serve": "npx http-server"
}

Call with: npm run serve


Related questions:

  1. How to use package installed locally in node_modules?
  2. NPM: how to source ./node_modules/.bin folder?
  3. How do you run a js file using npm scripts?

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

I tend to think that people are impressed with stuff that they can relate to or is relevant to their lives. I'd try and base my 10 lines of code around something that they know and understand. Take, for example, Twitter and its API. Why not use this API to build something that's cool. The following 10 lines of code will return the "public timeline" from Twitter and display it in a console application...

using (var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss"))
    {
        SyndicationFeed
            .Load(xmlr)
            .GetRss20Formatter()
            .Feed
            .Items        
            .ToList()
            .ForEach( x => Console.WriteLine(x.Title.Text));
    }

My code sample might not be the best for your students. It's written in C# and uses .NET 3.5. So if you're going to teach them PHP, Java, or C++ this won't be useful. However, my point is that by associating your 10 lines of code with something "cool, interesting, and relevant to the students your sample also becomes cool, interesting, and relevant.

Good luck!

[Yes, I know that I've missed out a few lines of using statements and the Main method, but I'm guessing that the 10 lines didn't need to be literally 10 lines]

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.

$.ajaxPrefilter( "json script", function( options ) {
  options.crossDomain = true;
});

Selecting data from two different servers in SQL Server

These are all fine answers, but this one is missing and it has it's own powerful uses. Possibly it doesn't fit what the OP wanted, but the question was vague and I feel others may find their way here. Basically you can use 1 window to simultaneously run a query against multiple servers, here's how:

In SSMS open Registered Servers and create a New Server Group under Local Server Groups.

Under this group create New Server Registration for each server you wish to query. If the DB names are different ensure to set a default for each in the properties.

Now go back to the Group you created in the first step, right click and select New Query. A new query window will open and any query you run will be executed on each server in the group. The results are presented in a single data set with an extra column name indicating which server the record came from. If you use the status bar you will note the server name is replaced with multiple.

align divs to the bottom of their container

The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".

For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".

enter image description here

By setting this layout up with flexbox, you can set flex-grow: 1; on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:

enter image description here

(apologies for the terrible, quick-and-dirty graphics)

How do I calculate percentiles with python/numpy?

To calculate the percentile of a series, run:

from scipy.stats import rankdata
import numpy as np

def calc_percentile(a, method='min'):
    if isinstance(a, list):
        a = np.asarray(a)
    return rankdata(a, method=method) / float(len(a))

For example:

a = range(20)
print {val: round(percentile, 3) for val, percentile in zip(a, calc_percentile(a))}
>>> {0: 0.05, 1: 0.1, 2: 0.15, 3: 0.2, 4: 0.25, 5: 0.3, 6: 0.35, 7: 0.4, 8: 0.45, 9: 0.5, 10: 0.55, 11: 0.6, 12: 0.65, 13: 0.7, 14: 0.75, 15: 0.8, 16: 0.85, 17: 0.9, 18: 0.95, 19: 1.0}

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Based on Dirk Stöcker's answer, here's a neat wrapper function for Python 3's print function. Use it just like you would use print.

As an added bonus, compared to the other answers, this won't print your text as a bytearray ('b"content"'), but as normal strings ('content'), because of the last decode step.

def uprint(*objects, sep=' ', end='\n', file=sys.stdout):
    enc = file.encoding
    if enc == 'UTF-8':
        print(*objects, sep=sep, end=end, file=file)
    else:
        f = lambda obj: str(obj).encode(enc, errors='backslashreplace').decode(enc)
        print(*map(f, objects), sep=sep, end=end, file=file)

uprint('foo')
uprint(u'Antonín Dvorák')
uprint('foo', 'bar', u'Antonín Dvorák')

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This can be caused by a full disk (Ubuntu/Nginx).

My situation:

Finding longest string in array

I was inspired of Jason's function and made a little improvements to it and got as a result rather fast finder:

function timo_longest(a) {
  var c = 0, d = 0, l = 0, i = a.length;
  if (i) while (i--) {
    d = a[i].length;
    if (d > c) {
      l = i; c = d;
    }
  }
  return a[l];
}
arr=["First", "Second", "Third"];
var longest = timo_longest(arr);

Speed results: http://jsperf.com/longest-string-in-array/7

annotation to make a private method public only for test classes

Okay, so here we have two things that are being mixed. First thing, is when you need to mark something to be used only on test, which I agree with @JB Nizet, using the guava annotation would be good.

A different thing, is to test private methods. Why should you test private methods from the outside? I mean.. You should be able to test the object by their public methods, and at the end that its behavior. At least, that we are doing and trying to teach to junior developers, that always try to test private methods (as a good practice).

How to set only time part of a DateTime variable in C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

String Padding in C

Oh okay, makes sense. So I did this:

    char foo[10] = "hello";
    char padded[16];
    strcpy(padded, foo);
    printf("%s", StringPadRight(padded, 15, " "));

Thanks!

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

What is a semaphore?

So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.

Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).

There are also differences between binary/mutex & counting semaphores.

Check out the lecture notes at http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html.

How do I concatenate strings?

To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.

The nicest I have seen is using the join method on an array:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = [a, b].join("\n");

    print!("{}", result);
}

Depending on your use case you might also prefer more control:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = format!("{}\n{}", a, b);

    print!("{}", result);
}

There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Why call super() in a constructor?

We can access super class elements by using super keyword

Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.

    class parent {
    String str="I am parent";
    //method of parent Class
    public void foo() {
        System.out.println("Hello World " + str);
    }
}

class child extends parent {
    String str="I am child";
    // different foo implementation in child Class
    public void foo() {
        System.out.println("Hello World "+str);
    }

    // calling the foo method of parent class
    public void parentClassFoo(){
        super.foo();
    }

    // changing the value of str in parent class and calling the foo method of parent class
    public void parentClassFooStr(){
        super.str="parent string changed";
        super.foo();
    }
}


public class Main{
        public static void main(String args[]) {
            child obj = new child();
            obj.foo();
            obj.parentClassFoo();
            obj.parentClassFooStr();
        }
    }

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

How to get the month name in C#?

Use the "MMMM" format specifier:

string month = dateTime.ToString("MMMM");

Database, Table and Column Naming Conventions?

Essential Database Naming Conventions (and Style) (click here for more detailed description)

table names choose short, unambiguous names, using no more than one or two words distinguish tables easily facilitates the naming of unique field names as well as lookup and linking tables give tables singular names, never plural (update: i still agree with the reasons given for this convention, but most people really like plural table names, so i’ve softened my stance)... follow the link above please

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Fastest way to check a string is alphanumeric in Java

A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:

boolean isAlphanumeric(String str) {
    for (int i=0; i<str.length(); i++) {
        char c = str.charAt(i);
        if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
            return false;
    }

    return true;
}

I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.

Uninstalling Android ADT

If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

Array functions in jQuery

Have a look at https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!

window.onload vs $(document).ready()

Document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready executes when the HTML document is loaded.

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

The window.load however will wait for the page to be fully loaded. This includes inner frames, images, etc.

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});

Node.js console.log() not logging anything

In a node.js server console.log outputs to the terminal window, not to the browser's console window.

How are you running your server? You should see the output directly after you start it.

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How to print a query string with parameter values when using Hibernate

The simplest solution for me is implementing a regular stringReplace to replace parameter inputs with parameter values (treating all parameters as string, for simplicity):

 String debugedSql = sql;
 //then, for each named parameter
     debugedSql = debugedSql.replaceAll(":"+key, "'"+value.toString()+"'");
 //and finnaly
 println(debugedSql);

or something similar for positional parameters (?).
Take care of null values and specific value types like date, if you want a run ready sql to be logged.

How to delete specific characters from a string in Ruby?

For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.

text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04

How to install trusted CA certificate on Android device?

Did you try: Settings -> Security -> Install from SD Card? – Alexander Egger Dec 20 '10 at 20:11

I'm not sure why is this not an answer already, but I just followed this advice and it worked.

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

How can I determine if a date is between two dates in Java?

You might want to take a look at Joda Time which is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

SearchTools-Avi said "MySQL text search, which doesn't even index words of three letters or fewer."

FYIs, The MySQL fulltext min word length is adjustable since at least MySQL 5.0. Google 'mysql fulltext min length' for simple instructions.

That said, MySQL fulltext has limitations: for one, it gets slow to update once you reach a million records or so, ...

Removing Java 8 JDK from Mac

I was able to unistall jdk 8 in mavericks successfully doing the following steps:

Run this command to just remove the JDK

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk<version>.jdk

Run these commands if you want to remove plugins

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

How do I check if the mouse is over an element in jQuery?

I combined ideas from this topic and came up with this, which is useful for showing/hiding a submenu:

$("#menu_item_a").mouseenter(function(){
   clearTimeout($(this).data('timeoutId'));
   $("#submenu_a").fadeIn("fast");
}).mouseleave(function(){
   var menu_item = $(this);

   var timeoutId = setTimeout(function(){
      if($('#submenu_a').is(':hover'))
      {
        clearTimeout(menu_item.data('timeoutId'));
      }
      else
      {
        $("#submenu_a").fadeOut("fast");
      }
   }, 650);

    menu_item.data('timeoutId', timeoutId); 
});

 $("#submenu_a").mouseleave(function(){
   $(this).fadeOut("fast");
 });

Seems to work for me. Hope this helps someone.

EDIT: Now realizing this approach is not working correctly in IE.

How can I list all tags for a Docker image on a remote registry?

If folks want to read tags from the RedHat registry at https://registry.redhat.io/v2 then the steps are:

# example nodejs-12 image
IMAGE_STREAM=nodejs-12
REDHAT_REGISTRY_API="https://registry.redhat.io/v2/rhel8/$IMAGE_STREAM"
# Get an oAuth token based on a service account username and password https://access.redhat.com/articles/3560571
TOKEN=$(curl --silent -u "$REGISTRY_USER":"$REGISTRY_PASSWORD" "https://sso.redhat.com/auth/realms/rhcc/protocol/redhat-docker-v2/auth?service=docker-registry&client_id=curl&scope=repository:rhel:pull" |  jq --raw-output '.token')
# Grab the tags
wget -q --header="Accept: application/json" --header="Authorization: Bearer $TOKEN" -O - "$REDHAT_REGISTRY_API/tags/list" | jq -r '."tags"[]' 

If you want to compare what you have in your local openshift registry against what is in the upstream registry.redhat.com then here is a complete script.

Email & Phone Validation in Swift

Swift 4 & Swift 5:

func isValidPhone(phone: String) -> Bool {
        let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phone)
    }

func isValidEmail(email: String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: email)
    }

How to run docker-compose up -d at system start up?

If your docker.service enabled on system startup

$ sudo systemctl enable docker

and your services in your docker-compose.yml has

restart: always

all of the services run when you reboot your system if you run below command only once

docker-compose up -d

Composer Warning: openssl extension is missing. How to enable in WAMP

opened wamp/bin/apache/apache2.4.4/bin/php config.. wamp/bin/php/php5.4.16/php conf settings, php-ini production, php-ini dev, phpForApache find extension=php_openssl.dll and uncomment by removing ;

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

You should only use &rsquo; if your intention is to make either a closed single quotation mark or an apostrophe. Both of these punctuation marks are curved in shape in most fonts. If your intent is to make a foot mark, go the other route. A foot mark is always a straight vertical mark.

It’s a matter of typography. One way is correct; the other is not.

How to determine if a number is positive or negative?

This solution uses modulus. And yes, it also works for 0.5 (tests are below, in the main method).

public class Num {

    public static int sign(long x) {
        if (x == 0L || x == 1L) return (int) x;
        return x == Long.MIN_VALUE || x % (x - 1L) == x ? -1 : 1;
    }

    public static int sign(double x) {
        if (x != x) throw new IllegalArgumentException("NaN");
        if (x == 0.d || x == 1.d) return (int) x;
        if (x == Double.POSITIVE_INFINITY) return 1;
        if (x == Double.NEGATIVE_INFINITY) return -1;
        return x % (x - 1.d) == x ? -1 : 1;
    }

    public static int sign(int x) {
        return Num.sign((long)x);
    }

    public static int sign(float x) {
        return Num.sign((double)x);
    }

    public static void main(String args[]) {

        System.out.println(Num.sign(Integer.MAX_VALUE)); // 1
        System.out.println(Num.sign(1)); // 1
        System.out.println(Num.sign(0)); // 0
        System.out.println(Num.sign(-1)); // -1
        System.out.println(Num.sign(Integer.MIN_VALUE)); // -1

        System.out.println(Num.sign(Long.MAX_VALUE)); // 1
        System.out.println(Num.sign(1L)); // 1
        System.out.println(Num.sign(0L)); // 0
        System.out.println(Num.sign(-1L)); // -1
        System.out.println(Num.sign(Long.MIN_VALUE)); // -1

        System.out.println(Num.sign(Double.POSITIVE_INFINITY)); // 1
        System.out.println(Num.sign(Double.MAX_VALUE)); // 1
        System.out.println(Num.sign(0.5d)); // 1
        System.out.println(Num.sign(0.d)); // 0
        System.out.println(Num.sign(-0.5d)); // -1
        System.out.println(Num.sign(Double.MIN_VALUE)); // -1
        System.out.println(Num.sign(Double.NEGATIVE_INFINITY)); // -1

        System.out.println(Num.sign(Float.POSITIVE_INFINITY)); // 1
        System.out.println(Num.sign(Float.MAX_VALUE)); // 1
        System.out.println(Num.sign(0.5f)); // 1
        System.out.println(Num.sign(0.f)); // 0
        System.out.println(Num.sign(-0.5f)); // -1
        System.out.println(Num.sign(Float.MIN_VALUE)); // -1
        System.out.println(Num.sign(Float.NEGATIVE_INFINITY)); // -1
        System.out.println(Num.sign(Float.NaN)); // Throws an exception

    }
}

Should I initialize variable within constructor or outside constructor

Both the options can be correct depending on your situation.

A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.

It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.

remove first element from array and return the array minus the first element

Try this

    var myarray = ["item 1", "item 2", "item 3", "item 4"];

    //removes the first element of the array, and returns that element apart from item 1.
    myarray.shift(); 
    console.log(myarray); 

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):

path =   'C:\Users\myUserName\project\subfolder'
path   # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path)              # gives windows error
path =   'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path)              # gives expected behavior

Entity Framework vs LINQ to SQL

Here's some metrics guys... (QUANTIFYING THINGS!!!!)

I took this query where I was using Entity Framework

var result = (from metattachType in _dbContext.METATTACH_TYPE
                join lineItemMetattachType in _dbContext.LINE_ITEM_METATTACH_TYPE on metattachType.ID equals lineItemMetattachType.METATTACH_TYPE_ID
                where (lineItemMetattachType.LINE_ITEM_ID == lineItemId && lineItemMetattachType.IS_DELETED == false
                && metattachType.IS_DELETED == false)
                select new MetattachTypeDto()
                {
                    Id = metattachType.ID,
                    Name = metattachType.NAME
                }).ToList();

and changed it into this where I'm using the repository pattern Linq

            return await _attachmentTypeRepository.GetAll().Where(x => !x.IsDeleted)
                .Join(_lineItemAttachmentTypeRepository.GetAll().Where(x => x.LineItemId == lineItemId && !x.IsDeleted),
                attachmentType => attachmentType.Id,
                lineItemAttachmentType => lineItemAttachmentType.MetattachTypeId,
                (attachmentType, lineItemAttachmentType) => new AttachmentTypeDto
                {
                    Id = attachmentType.Id,
                    Name = attachmentType.Name
                }).ToListAsync().ConfigureAwait(false);

Linq-to-sql

            return (from attachmentType in _attachmentTypeRepository.GetAll()
                    join lineItemAttachmentType in _lineItemAttachmentTypeRepository.GetAll() on attachmentType.Id equals lineItemAttachmentType.MetattachTypeId
                    where (lineItemAttachmentType.LineItemId == lineItemId && !lineItemAttachmentType.IsDeleted && !attachmentType.IsDeleted)
                    select new AttachmentTypeDto()
                    {
                        Id = attachmentType.Id,
                        Name = attachmentType.Name
                    }).ToList();

Also, please know that Linq-to-Sql is 14x faster than Linq...

enter image description here

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

The Prototype library has a uniq function, which returns the array without the dupes. That's only half of the work though.

clearing select using jquery

For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.

Example

<select id="mySelectOption">
   <option value="" selected disabled>Please select</option>
</select>

Answer

$('#mySelectOption').val('Please Select');

How to define constants in ReactJS

If you want to keep the constants in the React component, use statics property, like the example below. Otherwise, use the answer given by @Jim

var MyComponent = React.createClass({
    statics: {
        sizeToLetterMap: {
            small_square: 's',
            large_square: 'q',
            thumbnail: 't',
            small_240: 'm',
            small_320: 'n',
            medium_640: 'z',
            medium_800: 'c',
            large_1024: 'b',
            large_1600: 'h',
            large_2048: 'k',
            original: 'o'
        },
        someOtherStatic: 100
    },

    photoUrl: function (image, size_text) {
        var size = MyComponent.sizeToLetterMap[size_text];
    }

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

Vim and Ctags tips and tricks

One line that always goes in my .vimrc:

set tags=./tags;/

This will look in the current directory for "tags", and work up the tree towards root until one is found. IOW, you can be anywhere in your source tree instead of just the root of it.

upstream sent too big header while reading response header from upstream

upstream sent too big header while reading response header from upstream is nginx's generic way of saying "I don't like what I'm seeing"

  1. Your upstream server thread crashed
  2. The upstream server sent an invalid header back
  3. The Notice/Warnings sent back from STDERR overflowed their buffer and both it and STDOUT were closed

3: Look at the error logs above the message, is it streaming with logged lines preceding the message? PHP message: PHP Notice: Undefined index: Example snippet from a loop my log file:

2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
... // 20 lines of same
PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undef
2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "ta_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Firstname

you can see in the 3rd line from the bottom that the buffer limit was hit, broke, and the next thread wrote in over it. Nginx then closed the connection and returned 502 to the client.

2: log all the headers sent per request, review them and make sure they conform to standards (nginx does not permit anything older than 24 hours to delete/expire a cookie, sending invalid content length because error messages were buffered before the content counted...). getallheaders function call can usually help out in abstracted code situations php get all headers

examples include:

<?php
//expire cookie
setcookie ( 'bookmark', '', strtotime('2012-01-01 00:00:00') );
// nginx will refuse this header response, too far past to accept
....
?>

and this:

<?php
header('Content-type: image/jpg');
?>

<?php   //a space was injected into the output above this line
header('Content-length: ' . filesize('image.jpg') );
echo file_get_contents('image.jpg');
// error! the response is now 1-byte longer than header!!
?>

1: verify, or make a script log, to ensure your thread is reaching the correct end point and not exiting before completion.

ASP.NET Bundles how to disable minification

Conditional compilation directives are your friend:

#if DEBUG
            var jsBundle = new Bundle("~/Scripts/js");
#else
            var jsBundle = new ScriptBundle("~/Scripts/js");
#endif

ASP.NET Identity reset password

Best way to Reset Password in Asp.Net Core Identity use for Web API.

Note* : Error() and Result() are created for internal use. You can return you want.

        [HttpPost]
        [Route("reset-password")]
        public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                if (model is null)
                    return Error("No data found!");


                var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
                if (user == null)
                    return Error("No user found!");

                Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
                    await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);

                if (!checkOldPassword.Succeeded)
                    return Error("Old password does not matched.");

                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
                if (string.IsNullOrEmpty(resetToken))
                    return Error("Error while generating reset token.");

                var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);

                if (result.Succeeded)
                    return Result();
                else
                    return Error();
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

How to use a Java8 lambda to sort a stream in reverse order?

You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order? by wrapping it in a lambda:

.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())

note that f2 is the first argument of Long.compare, not the second, so the result will be reversed.

Select All as default value for Multivalue parameter

The accepted answer is correct, but not complete. In order for Select All to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.

Why do I get a C malloc assertion failure?

i got the same problem, i used malloc over n over again in a loop for adding new char *string data. i faced the same problem, but after releasing the allocated memory void free() problem were sorted

Batch File: ( was unexpected at this time

you need double quotes in all your three if statements, eg.:

IF "%a%"=="2" (

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.


set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection
    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if "!param1!"=="" goto :param1Prompt

    if "!param1!"=="1" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
         USB Write is Locked!
    )
    if "!param1!"=="2" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
         USB Write is Unlocked!
    )
)
pause

Create new user in MySQL and give it full access to one database

To me this worked.

CREATE USER 'spowner'@'localhost' IDENTIFIED BY '1234'; 
GRANT ALL PRIVILEGES ON test.* To 'spowner'@'localhost'; 
FLUSH PRIVILEGES;

where

  • spowner : user name
  • 1234 : password of spowner
  • test : database 'spowner' has access right to

Sorting A ListView By Column

You can use a manual sorting algorithm like this

public void ListItemSorter(object sender, ColumnClickEventArgs e)
    {
        ListView list = (ListView)sender;
        int total = list.Items.Count;
        list.BeginUpdate();
        ListViewItem[] items = new ListViewItem[total];
        for (int i = 0; i < total; i++)
        {
            int count = list.Items.Count;
            int minIdx = 0;
            for (int j = 1; j < count; j++)
                if (list.Items[j].SubItems[e.Column].Text.CompareTo(list.Items[minIdx].SubItems[e.Column].Text) < 0)
                    minIdx = j;
            items[i] = list.Items[minIdx];
            list.Items.RemoveAt(minIdx);
        }
        list.Items.AddRange(items);
        list.EndUpdate();
    }

this method uses selection sort in O^2 order and as Ascending. You can change the '>' with '<' for a descending or add an argument for this method. It sorts any column that is clicked and works perfect for small amount of data.

MongoDB: How to find out if an array field contains an element?

[edit based on this now being possible in recent versions]

[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.

db.student.find({},
 {_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})

and you will get back what you expected:

{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }

[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)

If you were storing (as an example) an Id and name in the course array like this:

{
        "_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
        "name" : "Physics",
        "students" : [
                {id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
                {id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
        ]
}

Your query then would simply be:

db.course.find( { }, 
                { students : 
                    { $elemMatch : 
                       { id : ObjectId("51780f796ec4051a536015d0"), 
                         name : "Sam" 
                       } 
                    } 
                } 
);

If that student was only enrolled in CS 101 you'd get back:

{ "name" : "Literature" }
{ "name" : "Physics" }
{
    "name" : "CS 101",
    "students" : [
        {
            "id" : ObjectId("51780f796ec4051a536015cf"),
            "name" : "John"
        }
    ]
}

Show / hide div on click with CSS

if 'focus' works for you (i.e. stay visible while element has focus after click) then see this existing SO answer:

Hide Show content-list with only CSS, no javascript used

How can I start an interactive console for Perl?

I wrote a script I call "psh":

#! /usr/bin/perl

while (<>) {
  chomp;
  my $result = eval;
  print "$_ = $result\n";
}

Whatever you type in, it evaluates in Perl:

> gmtime(2**30)
gmtime(2**30) = Sat Jan 10 13:37:04 2004

> $x = 'foo'
$x = 'foo' = foo

> $x =~ s/o/a/g
$x =~ s/o/a/g = 2

> $x
$x = faa

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

How to use comparison and ' if not' in python?

Why think? If not confuses you, switch your if and else clauses around to avoid the negation.

i want to make sure that ( u0 <= u < u0+step ) before do sth.

Just write that.

if u0 <= u < u0+step:
    "do sth" # What language is "sth"?  No vowels.  An odd-looking word.
else:
    u0 = u0+ step

Why overthink it?

If you need an empty if -- and can't work out the logic -- use pass.

 if some-condition-that's-too-complex-for-me-to-invert:
     pass
 else: 
     do real work here

Getting Google+ profile picture url with user_id

UPDATE: The method below DOES NOT WORK since 2015

It is possible to get the profile picture, and you can even set the size of it:

https://plus.google.com/s2/photos/profile/<user_id>?sz=<your_desired_size>

Example: My profile picture, with size set to 100 pixels:

https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100

Usage with an image tag:

<img src="https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100" width="100" height="100">

Hope you get it working!

Format date in a specific timezone

You can Try this ,

Here you can get the date based on the Client Timezone (Browser).

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

Cheers!!

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

Uncaught ReferenceError: jQuery is not defined

jQuery needs to be the first script you import. The first script on your page

<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>

appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

JUnit Testing Exceptions

are you sure you told it to expect the exception?

for newer junit (>= 4.7), you can use something like (from here)

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}

and for older junit, this:

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
  int i = 1/0;
}

Highlight all occurrence of a selected word?

First (or in your .vimrc):

:set hlsearch

Then position your cursor over the word you want highlighted, and hit *.

hlsearch means highlight all occurrences of the current search, and * means search for the word under the cursor.

How to change Git log date formats

After a long time looking for a way to get git log output the date in the format YYYY-MM-DD in a way that would work in less, I came up with the following format:

%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08

along with the switch --date=iso.

This will print the date in ISO format (a long one), and then print 14 times the backspace character (0x08), which, in my terminal, effectively removes everything after the YYYY-MM-DD part. For example:

git log --date=iso --pretty=format:'%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%aN %s'

This gives something like:

2013-05-24 bruno This is the message of the latest commit.
2013-05-22 bruno This is an older commit.
...

What I did was create an alias named l with some tweaks on the format above. It shows the commit graph to the left, then the commit's hash, followed by the date, the shortnames, the refnames and the subject. The alias is as follows (in ~/.gitconfig):

[alias]
        l = log --date-order --date=iso --graph --full-history --all --pretty=format:'%x08%x09%C(red)%h %C(cyan)%ad%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08 %C(bold blue)%aN%C(reset)%C(bold yellow)%d %C(reset)%s'

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Simple Steps

  1. 1 Open SQL Server Configuration Manager
  2. Under SQL Server Services Select Your Server
  3. Right Click and Select Properties
  4. Log on Tab Change Built-in-account tick
  5. in the drop down list select Network Service
  6. Apply and start The service

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

What is the Git equivalent for revision number?

We're using this command to get version and revision from git:

git describe --always --tags --dirty

It returns

  • commit hash as revision when no tagging is used (e.g. gcc7b71f)
  • tag name as version when on a tag (e.g. v2.1.0, used for releases)
  • tag name, revision number since last tag and commit hash when after a tag (e.g. v5.3.0-88-gcc7b71f)
  • same as above plus a "dirty" tag if the working tree has local modifications (e.g. v5.3.0-88-gcc7b71f-dirty)

See also: https://www.git-scm.com/docs/git-describe#Documentation/git-describe.txt

WPF What is the correct way of using SVG files as icons in WPF

We can use directly the path's code from the SVG's code:

    <Path>
        <Path.Data>
            <PathGeometry Figures="M52.8,105l-1.9,4.1c ... 

Exposing a port on a live Docker container

I wrote a blog post that explains how to access an unpublished port of a container In different ways depending on the needs:

  • by committing a new image and running a new container,
  • by using socat to avoid restarting the container.

The post also goes through a brief introduction of both how port mapping works, the difference between exposing and publishing a port, and what is socat.

Here’s the link: https://lmcaraig.com/accessing-an-unpublished-port-of-a-running-docker-container

How do you create a dropdownlist from an enum in ASP.NET MVC?

In .NET Core you can just use this:

@Html.DropDownListFor(x => x.Foo, Html.GetEnumSelectList<MyEnum>())

Create a circular button in BS3

With Font Awesome ICONS, I used the following code to produce a round button/image with the color of your choice.

<code>

<span class="fa fa-circle fa-lg" style="color:#ff0000;"></span>

</code>

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

How to convert a double to long without casting?

If you have a strong suspicion that the DOUBLE is actually a LONG, and you want to

1) get a handle on its EXACT value as a LONG

2) throw an error when its not a LONG

you can try something like this:

public class NumberUtils {

    /**
    * Convert a {@link Double} to a {@link Long}.
    * Method is for {@link Double}s that are actually {@link Long}s and we just
    * want to get a handle on it as one.
    */
    public static long getDoubleAsLong(double specifiedNumber) {
        Assert.isTrue(NumberUtils.isWhole(specifiedNumber));
        Assert.isTrue(specifiedNumber <= Long.MAX_VALUE && specifiedNumber >= Long.MIN_VALUE);
        // we already know its whole and in the Long range
        return Double.valueOf(specifiedNumber).longValue();
    }

    public static boolean isWhole(double specifiedNumber) {
        // http://stackoverflow.com/questions/15963895/how-to-check-if-a-double-value-has-no-decimal-part
        return (specifiedNumber % 1 == 0);
    }
}

Long is a subset of Double, so you might get some strange results if you unknowingly try to convert a Double that is outside of Long's range:

@Test
public void test() throws Exception {
    // Confirm that LONG is a subset of DOUBLE, so numbers outside of the range can be problematic
    Assert.isTrue(Long.MAX_VALUE < Double.MAX_VALUE);
    Assert.isTrue(Long.MIN_VALUE > -Double.MAX_VALUE); // Not Double.MIN_VALUE => read the Javadocs, Double.MIN_VALUE is the smallest POSITIVE double, not the bottom of the range of values that Double can possible be

    // Double.longValue() failure due to being out of range => results are the same even though I minus ten
    System.out.println("Double.valueOf(Double.MAX_VALUE).longValue(): " + Double.valueOf(Double.MAX_VALUE).longValue());
    System.out.println("Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + Double.valueOf(Double.MAX_VALUE - 10).longValue());

    // casting failure due to being out of range => results are the same even though I minus ten
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE): " + (long) Double.valueOf(Double.MAX_VALUE).doubleValue());
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + (long) Double.valueOf(Double.MAX_VALUE - 10).doubleValue());
}

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

I hope this can help someone who was faced with my same problem.

This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.

Make sure you install Bootstrap DatePicker through NuGet

Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.

if (!Modernizr.inputtypes.date) {
    $(function () {

       $(".datecontrol").datepicker();

    });
}

Set the bundles

bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js",
              "~/Scripts/bootstrap-datepicker.js",
              "~/Scripts/DatePickerReady.js",
              "~/Scripts/respond.js"))

bundles.Add(New StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/bootstrap-datepicker3.css",
              "~/Content/site.css"))

Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.

<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing

Your view code should be

@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})

and voila

enter image description here

Add Auto-Increment ID to existing table?

For PostgreSQL you have to use SERIAL instead of auto_increment.

ALTER TABLE your_table_name ADD COLUMN id SERIAL NOT NULL PRIMARY KEY

How do I export (and then import) a Subversion repository?

If you do not have file access to the repository, I prefer rsvndump (remote Subversion repository dump) to make the dump file.

How do I make a C++ console program exit?

#include <cstdlib>
...
exit( exit_code );

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

How to generate a Dockerfile from an image?

It is not possible at this point (unless the author of the image explicitly included the Dockerfile).

However, it is definitely something useful! There are two things that will help to obtain this feature.

  1. Trusted builds (detailed in this docker-dev discussion
  2. More detailed metadata in the successive images produced by the build process. In the long run, the metadata should indicate which build command produced the image, which means that it will be possible to reconstruct the Dockerfile from a sequence of images.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

@Html.Partial("nameOfPartial", Model)

Update

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

Get attribute name value of <input>

var theName;

theName = $("input selector goes here").attr("name");

HTML5 Canvas Rotate Image

Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

// no need to use save and restore between calls as it sets the transform rather 
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
} 

If you wish to control the rotation point use the next function

// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -cx, -cy);
} 

To reset the 2D context transform

ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore

Thus to rotate image to the left (anti clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);

Thus to rotate image to the right (clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);

Example draw 500 images translated rotated scaled

_x000D_
_x000D_
var image = new Image;_x000D_
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";_x000D_
var canvas = document.createElement("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.top = "0px";_x000D_
canvas.style.left = "0px";_x000D_
document.body.appendChild(canvas);_x000D_
var w,h;_x000D_
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}_x000D_
resize();_x000D_
window.addEventListener("resize",resize);_x000D_
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }_x000D_
function DO(count,callback){ while (count--) { callback(count) } }_x000D_
const sprites = [];_x000D_
DO(500,()=>{_x000D_
    sprites.push({_x000D_
       x : rand(w), y : rand(h),_x000D_
       xr : 0, yr : 0, // actual position of sprite_x000D_
       r : rand(Math.PI * 2),_x000D_
       scale : rand(0.1,0.25),_x000D_
       dx : rand(-2,2), dy : rand(-2,2),_x000D_
       dr : rand(-0.2,0.2),_x000D_
    });_x000D_
});_x000D_
function drawImage(image, spr){_x000D_
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin_x000D_
    ctx.rotate(spr.r);_x000D_
    ctx.drawImage(image, -image.width / 2, -image.height / 2);_x000D_
}_x000D_
function update(){_x000D_
    var ihM,iwM;_x000D_
    ctx.setTransform(1,0,0,1,0,0);_x000D_
    ctx.clearRect(0,0,w,h);_x000D_
    if(image.complete){_x000D_
      var iw = image.width;_x000D_
      var ih = image.height;_x000D_
      for(var i = 0; i < sprites.length; i ++){_x000D_
          var spr = sprites[i];_x000D_
          spr.x += spr.dx;_x000D_
          spr.y += spr.dy;_x000D_
          spr.r += spr.dr;_x000D_
          iwM = iw * spr.scale * 2 + w;_x000D_
          ihM = ih * spr.scale * 2 + h;_x000D_
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;_x000D_
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;_x000D_
          drawImage(image,spr);_x000D_
      }_x000D_
    }    _x000D_
    requestAnimationFrame(update);_x000D_
}_x000D_
requestAnimationFrame(update);
_x000D_
_x000D_
_x000D_

C# Convert a Base64 -> byte[]

I've written an extension method for this purpose:

public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
    string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
    return Convert.FromBase64String(base64String);
}

Call it like this:

byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();

I hope it helps someone.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

ng-repeat finish event

i would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.

but in my experience, as the OP states, its usually running some JQuery plugins or methods on the finnaly compiled DOM, which in that case i found that the most simple solution is to create a directive with a setTimeout, since the setTimeout function gets pushed to the end of the queue of the browser, its always right after everything is done in angular, usually ngReapet which continues after its parents postLinking function

angular.module('myApp', [])
.directive('pluginNameOrWhatever', function() {
  return function(scope, element, attrs) {        
    setTimeout(function doWork(){
      //jquery code and plugins
    }, 0);        
  };
});

for whoever wondering that in that case why not to use $timeout, its that it causes another digest cycle that is completely unnecessary

Name node is in safe mode. Not able to leave

try this, it will work

sudo -u hdfs hdfs dfsadmin -safemode leave

jquery ajax function not working

you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

How to completely uninstall Android Studio from windows(v10)?

I was having problem installing the latest v4.1.2 as it was having issue after I start it it shows my old blank project, so things I did were,

Caution: Please move your sdk and projects to a separate location before following steps if you haven't. So it might save your time downloading sdks and stuff.

1- Uninstall old Android Studio Completely (from Contorl panel -> Programs).

2- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Local\Google

3- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Roaming\Google

4- Delete these folders(.android ,.AndroidStudio*, .gradle) located at C:\Users<user_name>\

After doing all this I was managed to have fresh updated Android Studio v4.1.2

Custom designing EditText

enter image description here

For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#FFFFFF" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

Second file will be "bg_edittext_normal.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#F6F6F6" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/bg_edittext_normal"/>
</selector>

Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background

   <EditText
    :::::
    :::::  
    android:background="@drawable/bg_edittext"
    :::::
    :::::
    />

How do I Set Background image in Flutter?

I was able to apply a background below the Scaffold (and even it's AppBar) by putting the Scaffold under a Stack and setting a Container in the first "layer" with the background image set and fit: BoxFit.cover property.

Both the Scaffold and AppBar has to have the backgroundColor set as Color.transparent and the elevation of AppBar has to be 0 (zero).

Voilà! Now you have a nice background below the whole Scaffold and AppBar! :)

import 'package:flutter/material.dart';
import 'package:mynamespace/ui/shared/colors.dart';
import 'package:mynamespace/ui/shared/textstyle.dart';
import 'package:mynamespace/ui/shared/ui_helpers.dart';
import 'package:mynamespace/ui/widgets/custom_text_form_field_widget.dart';

class SignUpView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack( // <-- STACK AS THE SCAFFOLD PARENT
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/bg.png"), // <-- BACKGROUND IMAGE
              fit: BoxFit.cover,
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // <-- SCAFFOLD WITH TRANSPARENT BG
          appBar: AppBar(
            title: Text('NEW USER'),
            backgroundColor: Colors.transparent, // <-- APPBAR WITH TRANSPARENT BG
            elevation: 0, // <-- ELEVATION ZEROED
          ),
          body: Padding(
            padding: EdgeInsets.all(spaceXS),
            child: Column(
              children: [
                CustomTextFormFieldWidget(labelText: 'Email', hintText: 'Type your Email'),
                UIHelper.verticalSpaceSM,
                SizedBox(
                  width: double.maxFinite,
                  child: RaisedButton(
                    color: regularCyan,
                    child: Text('Finish Registration', style: TextStyle(color: white)),
                    onPressed: () => {},
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

How can I check if a Perl array contains a particular value?

There are two ways you can do this. You can use the throw the values into a hash for a lookup table, as suggested by the other posts. ( I'll add just another idiom. )

my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;

But if it's data of mostly word characters and not too many meta, you can dump it into a regex alternation:

use English qw<$LIST_SEPARATOR>;

my $regex_str = do { 
    local $LIST_SEPARATOR = '|';
    "(?:@bad_params)";
 };

 # $front_delim and $back_delim being any characters that come before and after. 
 my $regex = qr/$front_delim$regex_str$back_delim/;

This solution would have to be tuned for the types of "bad values" you're looking for. And again, it might be totally inappropriate for certain types of strings, so caveat emptor.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

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

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

What is the difference between background and background-color

This is the best answer. Shorthand (background) is for reset and DRY (combine with longhand).

Is it safe to use Project Lombok?

I have encountered a problem with Lombok and Jackson CSV, when I marshalized my object (java bean) to a CSV file, columns where duplicated, then I removed Lombok's @Data annotation and marshalizing worked fine.

See changes to a specific file using git

Or if you prefer to use your own gui tool:

git difftool ./filepath

You can set your gui tool guided by this post: How do I view 'git diff' output with a visual diff program?

How to center icon and text in a android button with width set to "fill parent"

I have seen solutions for aligning drawable at start/left but nothing for drawable end/right, so I came up with this solution. It uses dynamically calculated paddings for aligning drawable and text on both left and right side.

class IconButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyle) {

    init {
        maxLines = 1
    }

    override fun onDraw(canvas: Canvas) {
        val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()

        val textWidth = paint.measureText(text.toString())

        val drawable = compoundDrawables[0] ?: compoundDrawables[2]
        val drawableWidth = drawable?.intrinsicWidth ?: 0
        val drawablePadding = if (textWidth > 0 && drawable != null) compoundDrawablePadding else 0
        val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()

        canvas.save()

        val padding = (buttonContentWidth - bodyWidth).toInt() / 2
        val leftOrRight = if (compoundDrawables[0] != null) 1 else -1
        setPadding(leftOrRight * padding, 0, -leftOrRight * padding, 0)

        super.onDraw(canvas)
        canvas.restore()
    }
}

It is important to set gravity in your layout to either "center_vertical|start" or "center_vertical|end" depending on where do you set the icon. For example:

<com.stackoverflow.util.IconButton
        android:id="@+id/cancel_btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableStart="@drawable/cancel"
        android:drawablePadding="@dimen/padding_small"
        android:gravity="center_vertical|start"
        android:text="Cancel" />

Only problem with this implementation is that button can only have single line of text, otherwise the area of the text fills the button and paddings will be 0.

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How to check status of PostgreSQL server Mac OS X

It depends on where your postgresql server is installed. You use the pg_ctl to manually start the server like below.

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Insert string in beginning of another string

The first case is done using the insert() method:

_sb.insert(0, "Hello ");

The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:

String s2 = "Hello " + _s;

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Once Java(tm) Plug -In 2 SSV Helper was incompatible
Above solution did not work for me.
I solved it with the below instruction.
1. Go to IE settings
2. Internet options
3. Select Advanced tab
4. Scroll down to Security
5. Uncheck “Enable Enhanced Protected Mode”
6. Click OK and restart the browser

How do I make a Git commit in the past?

The advice you were given is flawed. Unconditionally setting GIT_AUTHOR_DATE in an --env-filter would rewrite the date of every commit. Also, it would be unusual to use git commit inside --index-filter.

You are dealing with multiple, independent problems here.

Specifying Dates Other Than “now”

Each commit has two dates: the author date and the committer date. You can override each by supplying values through the environment variables GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for any command that writes a new commit. See “Date Formats” in git-commit(1) or the below:

Git internal format = <unix timestamp> <time zone offset>, e.g.  1112926393 +0200
RFC 2822            = e.g. Thu, 07 Apr 2005 22:13:13 +0200
ISO 8601            = e.g. 2005-04-07T22:13:13

The only command that writes a new commit during normal use is git commit. It also has a --date option that lets you directly specify the author date. Your anticipated usage includes git filter-branch --env-filter also uses the environment variables mentioned above (these are part of the “env” after which the option is named; see “Options” in git-filter-branch(1) and the underlying “plumbing” command git-commit-tree(1).

Inserting a File Into a Single ref History

If your repository is very simple (i.e. you only have a single branch, no tags), then you can probably use git rebase to do the work.

In the following commands, use the object name (SHA-1 hash) of the commit instead of “A”. Do not forget to use one of the “date override” methods when you run git commit.

---A---B---C---o---o---o   master

git checkout master
git checkout A~0
git add path/to/file
git commit --date='whenever'
git tag ,new-commit -m'delete me later'
git checkout -
git rebase --onto ,new-commit A
git tag -d ,new-commit

---A---N                      (was ",new-commit", but we delete the tag)
        \
         B'---C'---o---o---o   master

If you wanted to update A to include the new file (instead of creating a new commit where it was added), then use git commit --amend instead of git commit. The result would look like this:

---A'---B'---C'---o---o---o   master

The above works as long as you can name the commit that should be the parent of your new commit. If you actually want your new file to be added via a new root commit (no parents), then you need something a bit different:

B---C---o---o---o   master

git checkout master
git checkout --orphan new-root
git rm -rf .
git add path/to/file
GIT_AUTHOR_DATE='whenever' git commit
git checkout -
git rebase --root --onto new-root
git branch -d new-root

N                       (was new-root, but we deleted it)
 \
  B'---C'---o---o---o   master

git checkout --orphan is relatively new (Git 1.7.2), but there are other ways of doing the same thing that work on older versions of Git.

Inserting a File Into a Multi-ref History

If your repository is more complex (i.e. it has more than one ref (branches, tags, etc.)), then you will probably need to use git filter-branch. Before using git filter-branch, you should make a backup copy of your entire repository. A simple tar archive of your entire working tree (including the .git directory) is sufficient. git filter-branch does make backup refs, but it is often easier to recover from a not-quite-right filtering by just deleting your .git directory and restoring it from your backup.

Note: The examples below use the lower-level command git update-index --add instead of git add. You could use git add, but you would first need to copy the file from some external location to the expected path (--index-filter runs its command in a temporary GIT_WORK_TREE that is empty).

If you want your new file to be added to every existing commit, then you can do this:

new_file=$(git hash-object -w path/to/file)
git filter-branch \
  --index-filter \
    'git update-index --add --cacheinfo 100644 '"$new_file"' path/to/file' \
  --tag-name-filter cat \
  -- --all
git reset --hard

I do not really see any reason to change the dates of the existing commits with --env-filter 'GIT_AUTHOR_DATE=…'. If you did use it, you would have make it conditional so that it would rewrite the date for every commit.

If you want your new file to appear only in the commits after some existing commit (“A”), then you can do this:

file_path=path/to/file
before_commit=$(git rev-parse --verify A)
file_blob=$(git hash-object -w "$file_path")
git filter-branch \
  --index-filter '

    if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$before_commit"') &&
       test -n "$x"; then
         git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
    fi

  ' \
  --tag-name-filter cat \
  -- --all
git reset --hard

If you want the file to be added via a new commit that is to be inserted into the middle of your history, then you will need to generate the new commit prior to using git filter-branch and add --parent-filter to git filter-branch:

file_path=path/to/file
before_commit=$(git rev-parse --verify A)

git checkout master
git checkout "$before_commit"
git add "$file_path"
git commit --date='whenever'
new_commit=$(git rev-parse --verify HEAD)
file_blob=$(git rev-parse --verify HEAD:"$file_path")
git checkout -

git filter-branch \
  --parent-filter "sed -e s/$before_commit/$new_commit/g" \
  --index-filter '

    if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$new_commit"') &&
       test -n "$x"; then
         git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
    fi

  ' \
  --tag-name-filter cat \
  -- --all
git reset --hard

You could also arrange for the file to be first added in a new root commit: create your new root commit via the “orphan” method from the git rebase section (capture it in new_commit), use the unconditional --index-filter, and a --parent-filter like "sed -e \"s/^$/-p $new_commit/\"".

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

C# send a simple SSH command

SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();

//using SSH.Net

How do I update a Linq to SQL dbml file?

In the case of stored procedure update, you should delete it from the .dbml file and reinsert it again. But if the stored procedure have two paths (ex: if something; display some columns; else display some other columns), make sure the two paths have the same columns aliases!!! Otherwise only the first path columns will exist.

PHP case-insensitive in_array function

you can use preg_grep():

$a= array(
 'one',
 'two',
 'three',
 'four'
);

print_r( preg_grep( "/ONe/i" , $a ) );

Bootstrap footer at the bottom of the page

When using bootstrap 4 or 5, flexbox could be used to achieve desired effect:

<body class="d-flex flex-column min-vh-100">
    <header>HEADER</header>
    <content>CONTENT</content>
    <footer class="mt-auto"></footer>
</body>

Please check the examples: Bootstrap 4 Bootstrap 5

In bootstrap 3 and without use of bootstrap. The simplest and cross browser solution for this problem is to set a minimal height for body object. And then set absolute position for the footer with bottom: 0 rule.

body {
  min-height: 100vh;
  position: relative;
  margin: 0;
  padding-bottom: 100px; //height of the footer
  box-sizing: border-box;
}

footer {
  position: absolute;
  bottom: 0;
  height: 100px;
}

Please check this example: Bootstrap 3

What does $_ mean in PowerShell?

$_ is an variable which iterates over each object/element passed from the previous | (pipe).

Serialize and Deserialize Json and Json Array in Unity

To Read JSON File, refer this simple example

Your JSON File (StreamingAssets/Player.json)

{
    "Name": "MyName",
    "Level": 4
}

C# Script

public class Demo
{
    public void ReadJSON()
    {
        string path = Application.streamingAssetsPath + "/Player.json";
        string JSONString = File.ReadAllText(path);
        Player player = JsonUtility.FromJson<Player>(JSONString);
        Debug.Log(player.Name);
    }
}

[System.Serializable]
public class Player
{
    public string Name;
    public int Level;
}

What is a Maven artifact?

An artifact is a file, usually a JAR, that gets deployed to a Maven repository.

A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.

Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact.

A project's dependencies are specified as artifacts.

Using (Ana)conda within PyCharm

this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -

  1. Used the cmd to install python and flask after creating environment as suggested above.

  2. Followed this answer.

  3. As suggested above, went to Run -> Edit Configurations and changed the environment there as well as in (2).

Obviously kept the correct python interpreter (the one in the environment) everywhere.

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

How to calculate sum of a formula field in crystal Reports?

The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.

In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)

EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!

Remove columns from dataframe where ALL values are NA

The two approaches offered thus far fail with large data sets as (amongst other memory issues) they create is.na(df), which will be an object the same size as df.

Here are two approaches that are more memory and time efficient

An approach using Filter

Filter(function(x)!all(is.na(x)), df)

and an approach using data.table (for general time and memory efficiency)

library(data.table)
DT <- as.data.table(df)
DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]

examples using large data (30 columns, 1e6 rows)

big_data <- replicate(10, data.frame(rep(NA, 1e6), sample(c(1:8,NA),1e6,T), sample(250,1e6,T)),simplify=F)
bd <- do.call(data.frame,big_data)
names(bd) <- paste0('X',seq_len(30))
DT <- as.data.table(bd)

system.time({df1 <- bd[,colSums(is.na(bd) < nrow(bd))]})
# error -- can't allocate vector of size ...
system.time({df2 <- bd[, !apply(is.na(bd), 2, all)]})
# error -- can't allocate vector of size ...
system.time({df3 <- Filter(function(x)!all(is.na(x)), bd)})
## user  system elapsed 
## 0.26    0.03    0.29 
system.time({DT1 <- DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]})
## user  system elapsed 
## 0.14    0.03    0.18 

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

Python Pandas - Find difference between two data frames

Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.

newDf = df1.set_index('Name1')
           .drop(df2['Name2'], errors='ignore')
           .reset_index(drop=False)

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Writing a dictionary to a text file?

For list comprehension lovers, this will write all the key : value pairs in new lines in dog.txt

my_dict = {'foo': [1,2], 'bar':[3,4]}

# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]

# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
    [ my_file.write(f'{st}\n') for st in list_of_strings ]

Set position / size of UI element as percentage of screen size

Take a look at this:

http://developer.android.com/reference/android/util/DisplayMetrics.html

You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

Converting Secret Key into a String and Vice Versa

try this, it's work without Base64 ( that is included only in JDK 1.8 ), this code run also in the previous java version :)

private static String SK = "Secret Key in HEX";


//  To Encrupt

public static String encrypt( String Message ) throws Exception{

    byte[] KeyByte = hexStringToByteArray( SK);
    SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");

    Cipher c = Cipher.getInstance("DES","SunJCE");
    c.init(1, k);
    byte mes_encrypted[] = cipher.doFinal(Message.getBytes());

    String MessageEncrypted = byteArrayToHexString(mes_encrypted);
    return MessageEncrypted;
}

//  To Decrypt

public static String decrypt( String MessageEncrypted )throws Exception{

    byte[] KeyByte = hexStringToByteArray( SK );
    SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");

    Cipher dcr =  Cipher.getInstance("DES","SunJCE");
    dc.init(Cipher.DECRYPT_MODE, k);
    byte[] MesByte  = hexStringToByteArray( MessageEncrypted );
    byte mes_decrypted[] = dcipher.doFinal( MesByte );
    String MessageDecrypeted = new String(mes_decrypted);

    return MessageDecrypeted;
}

public static String byteArrayToHexString(byte bytes[]){

    StringBuffer hexDump = new StringBuffer();
    for(int i = 0; i < bytes.length; i++){
    if(bytes[i] < 0)
    {   
        hexDump.append(getDoubleHexValue(Integer.toHexString(256 - Math.abs(bytes[i]))).toUpperCase());
    }else
    {
        hexDump.append(getDoubleHexValue(Integer.toHexString(bytes[i])).toUpperCase());
    }
    return hexDump.toString();

}



public static byte[] hexStringToByteArray(String s) {

    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2)
    {   
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
    }
    return data;

}