Programs & Examples On #Maintenance plan

Git - How to close commit editor?

Better yet, configure the editor to something you are comfortable with (gedit as an example):

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

You can also add the commit message from the command line.

git commit -m "blablabla"

and the editor will not be opened in the first place.

How to use multiprocessing queue in Python?

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
       msg = Msg(event, args)
       self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

Gradient borders

Try this, it worked for me.

_x000D_
_x000D_
div{_x000D_
  border-radius: 20px;_x000D_
  height: 70vh;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
div::before{_x000D_
  content: '';_x000D_
  display: block;_x000D_
  box-sizing: border-box;_x000D_
  height: 100%;_x000D_
_x000D_
  border: 1em solid transparent;_x000D_
  border-image: linear-gradient(to top, red 0%, blue 100%);_x000D_
  border-image-slice: 1;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

The link is to the fiddle https://jsfiddle.net/yash009/kayjqve3/1/ hope this helps

How to restore PostgreSQL dump file into Postgres databases?

By using pg_restore command you can restore postgres database

First open terminal type

sudo su postgres

Create new database

createdb [database name] -O [owner]

createdb test_db [-O openerp]

pg_restore -d [Database Name] [path of dump file]

pg_restore -d test_db /home/sagar/Download/sample_dbump

Wait for completion of database restoring.

Remember that dump file should have read, write, execute access, so for that you can apply chmod command

How to easily duplicate a Windows Form in Visual Studio?

1.Add a new folder to your project

2.Copy the form into that

3.Change the name in properties as well as change the file name

4.Check each form for their class name (they shouldn't be same)

How can I convert a long to int in Java?

If you want to make a safe conversion and enjoy the use of Java8 with Lambda expression You can use it like:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)

C - Convert an uppercase letter to lowercase

You messed up the second part of your if condition. That should be a <= 90.

Also, FYI, there is a C library function tolower that does this already:

#include <ctype.h>
#include <stdio.h>

int main() {
    putchar(tolower('A'));
}

How to delete an item in a list if it exists?

Here's another one-liner approach to throw out there:

next((some_list.pop(i) for i, l in enumerate(some_list) if l == thing), None)

It doesn't create a list copy, doesn't make multiple passes through the list, doesn't require additional exception handling, and returns the matched object or None if there isn't a match. Only issue is that it makes for a long statement.

In general, when looking for a one-liner solution that doesn't throw exceptions, next() is the way to go, since it's one of the few Python functions that supports a default argument.

Retrieve the maximum length of a VARCHAR column in SQL Server

For sql server (SSMS)

select MAX(LEN(ColumnName)) from table_name

This will returns number of characters.

 select MAX(DATALENGTH(ColumnName)) from table_name

This will returns number of bytes used/required.

IF some one use varchar then use DATALENGTH.More details

How to Copy Text to Clip Board in Android?

For copy any text in Android:

            TextView text = findViewById(R.id.text_id);
            ImageView icons = findViewById(R.id.copy_icon);

            icons.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);

                    Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
                }
            });

scale Image in an UIButton to AspectFit?

The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my UIButton and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.

Image UriSource and Data Binding

You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

And the class property is simply this

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            image.EndInit();
        }
        catch{
            return DependencyProperty.UnsetValue;
        }

        return image;
    }
}

I suppose it may be a little more work than the value converter, but it is another option.

JSONObject - How to get a value?

String loudScreaming = json.getJSONObject("LabelData").getString("slogan");

Loop backwards using indices in Python?

You might want to use the reversed function in python. Before we jump in to the code we must remember that the range function always returns a list (or a tuple I don't know) so range(5) will return [0, 1, 2, 3, 4]. The reversed function reverses a list or a tuple so reversed(range(5)) will be [4, 3, 2, 1, 0] so your solution might be:

for i in reversed(range(100)):
    print(i)

What are the differences between normal and slim package of jquery?

The jQuery blog, jQuery 3.1.1 Released!, says,

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k.

How do I solve this error, "error while trying to deserialize parameter"

In my case; my WCF service function was using List<byte> Types parameter and i was getting this exception in the client side. Then i changed it to byte[] Types, updated service reference and problem is solved.

Remove ListView items in Android

  • You should use only one adapter binded with the list of data you need to list
  • When you need to remove and replace all items, you have to clear all items from data-list using "list.clear()" and then add new data using "list.addAll(List)"

here an example:

List<String> myList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,       android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);

populateList(){
   List<String> result = getDataMethods();

   myList.addAll(result);
   adapter.notifyDataSetChanged();
}

repopulateList(){
   List<String> result = getDataMethods();

   myList.clear();
   myList.addAll(result);
   adapter.notifyDataSetChanged();
}

Could not find or load main class with a Jar File

I follow the following instruction to create a executable .jar in Eclipse. Then Run command "java -jar .jar " to launch the program.

It takes care of creating mainfest and includeing main class and library files parts for you.

http://java67.blogspot.com/2014/04/how-to-make-executable-jar-file-in-Java-Eclipse.html

How to create a String with carriage returns?

It depends on what you mean by "multiple lines". Different operating systems use different line separators.

In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.

But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.

Optimal way to Read an Excel file (.xls/.xlsx)

If you can restrict it to just (Open Office XML format) *.xlsx files, then probably the most popular library would be EPPLus.

Bonus is, there are no other dependencies. Just install using nuget:

Install-Package EPPlus

SQL Server - Adding a string to a text column (concat equivalent)

The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.

In fact, image, ntext, and text are all deprecated.

ntext, text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).

Is there a difference between "==" and "is"?

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True

# Make a new copy of list `a` via the slice operator, 
# and assign it to variable `b`
>>> b = a[:] 
>>> b is a
False
>>> b == a
True

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The same holds true for string literals:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

Please see this question as well.

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

Binding a list in @RequestParam

Change hidden field value with checkbox toggle like below...

HTML:

<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox"  onclick="toggle(this)"/> Delete All

Script:

function toggle(obj) {`var $input = $(obj);
    if ($input.prop('checked')) {

    $('#deleteAll').attr( 'value','Checked');

    } else {

    $('#deleteAll').attr( 'value','Unchecked');

    }

}

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

PL/SQL: numeric or value error: character string buffer too small

is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.

for example:

myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26

will fire such an error

Update int column in table with unique incrementing values

In oracle-based products you may use the following statement:

update table set interfaceID=RowNum where condition;

Filename timestamp in Windows CMD batch script getting truncated

BATCH/CMD FILE like DateAndTime.cmd (not in CMD-Console)

Code:

SETLOCAL EnableDelayedExpansion
(set d=%date:~8,2%-%date:~3,2%-%date:~0,2%) & (set t=%time::=.%) & (set t=!t: =0!) & (set STAMP=!d!__!t!)

Create output:

echo %stamp%

Output:

2020-02-25__08.43.38.90

Or also possible in for lines in CMD-Console and BATCH/CMD File

set d=%date:~6,4%-%date:~3,2%-%date:~0,2%
set t=%time::=.%
set t=%t: =0%
set stamp=%d%__%t%

"Create output" and "Output" same as above

How to specify a port to run a create-react-app based project?

It would be nice to be able to specify a port other than 3000, either as a command line parameter or an environment variable.

Right now, the process is pretty involved:

  1. Run npm run eject
  2. Wait for that to finish
  3. Edit scripts/start.js and find/replace 3000 with whatever port you want to use
  4. Edit config/webpack.config.dev.js and do the same
  5. npm start

How to force view controller orientation in iOS 8?

I tried a few solutions in here and the important thing to understand is that it's the root view controller that will determine if it will rotate or not.

I created the following objective-c project github.com/GabLeRoux/RotationLockInTabbedViewChild with a working example of a TabbedViewController where one child view is allowed rotating and the other child view is locked in portrait.

It's not perfect but it works and the same idea should work for other kind of root views such as NavigationViewController. :)

Child view locks parent orientation

Reload child component when variables on parent component changes. Angular2

In case, when we have no control over child component, like a 3rd party library component.

We can use *ngIf and setTimeout to reset the child component from parent without making any change in child component.

.template:

.ts:

show:boolean = true

resetChildForm(){
   this.show = false;

   setTimeout(() => {
      this.show = true
    }, 100);
}

How to remove specific elements in a numpy array

list comprehension could be an interesting approach as well.

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = np.array([2, 3, 6]) #index is changed to an array.  
out = [val for i, val in enumerate(a) if all(i != index)]
>>> [1, 2, 5, 6, 8, 9]

What is the fastest way to send 100,000 HTTP requests in Python?

A solution using tornado asynchronous networking library

from tornado import ioloop, httpclient

i = 0

def handle_request(response):
    print(response.code)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

http_client = httpclient.AsyncHTTPClient()
for url in open('urls.txt'):
    i += 1
    http_client.fetch(url.strip(), handle_request, method='HEAD')
ioloop.IOLoop.instance().start()

Is a GUID unique 100% of the time?

None seems to mention the actual math of the probability of it occurring.

First, let's assume we can use the entire 128 bit space (Guid v4 only uses 122 bits).

We know that the general probability of NOT getting a duplicate in n picks is:

(1-1/2128)(1-2/2128)...(1-(n-1)/2128)

Because 2128 is much much larger than n, we can approximate this to:

(1-1/2128)n(n-1)/2

And because we can assume n is much much larger than 0, we can approximate that to:

(1-1/2128)n^2/2

Now we can equate this to the "acceptable" probability, let's say 1%:

(1-1/2128)n^2/2 = 0.01

Which we solve for n and get:

n = sqrt(2* log 0.01 / log (1-1/2128))

Which Wolfram Alpha gets to be 5.598318 × 1019

To put that number into perspective, lets take 10000 machines, each having a 4 core CPU, doing 4Ghz and spending 10000 cycles to generate a Guid and doing nothing else. It would then take ~111 years before they generate a duplicate.

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

What is the difference between Amazon SNS and Amazon SQS?

In simple terms,

  • SNS - sends messages to the subscriber using push mechanism and no need of pull.

  • SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.

Check if input is number or letter javascript

Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[a-zA-Z]+$/;
    if (!x.match(regex))
    {
        alert("Must input string");
        return false;
    }
}

Even better would be to deny anything but numbers:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[0-9]+$/;
    if (x.match(regex))
    {
        alert("Must input numbers");
        return false;
    }
}

Angular2 RC6: '<component> is not a known element'

I fetch same problem for <flash-messages></flash-messages> with angular 5.

You just need add below lines in app.module.ts file

import { ---, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FlashMessageModule } from "angular-flash-message";


@NgModule({
  ---------------
  imports: [
    FlashMessageModule,
    ------------------         
  ], 
  -----------------
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  ------------
})

NB: I am using this one for message flash-messages

How to retrieve data from a SQL Server database in C#?

create a class called DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Tomcat won't stop or restart

I faced the same problem as mentioned below.

PID file found but no matching process was found. Stop aborted.

Solution is to find the free space of the linux machine by using the following command

df -h

The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command

du -h .

After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.

Strip out HTML and Special Characters

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

JSP tricks to make templating easier?

As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.

Let's take your simple example.

Put the following in WEB-INF/tags/wrapper.tag

<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
  <jsp:doBody/>
</body></html>

Now in your example.jsp page:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>
    <h1>Welcome</h1>
</t:wrapper>

That does exactly what you think it does.


So, lets expand upon that to something a bit more general. WEB-INF/tags/genericpage.tag

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
  <body>
    <div id="pageheader">
      <jsp:invoke fragment="header"/>
    </div>
    <div id="body">
      <jsp:doBody/>
    </div>
    <div id="pagefooter">
      <jsp:invoke fragment="footer"/>
    </div>
  </body>
</html>

To use this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <p>Hi I'm the heart of the message</p>
    </jsp:body>
</t:genericpage>

What does that buy you? A lot really, but it gets even better...


WEB-INF/tags/userpage.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome ${userName}</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <jsp:doBody/>
    </jsp:body>
</t:genericpage>

To use this: (assume we have a user variable in the request)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    First Name: ${user.firstName} <br/>
    Last Name: ${user.lastName} <br/>
    Phone: ${user.phone}<br/>
  </p>
</t:userpage>

But it turns you like to use that user detail block in other places. So, we'll refactor it. WEB-INF/tags/userdetail.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>

First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>

Now the previous example becomes:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    <t:userdetail user="${user}"/>
  </p>
</t:userpage>

The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.

JSP Tag Files have pretty much usurped things like Tiles etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).

Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:

<t:table items="${actionBean.customerList}" var="obj" css_class="display">
  <t:col css_class="checkboxcol">
    <s:checkbox name="customerIds" value="${obj.customerId}"
                onclick="handleCheckboxRangeSelection(this, event);"/>
  </t:col>
  <t:col name="customerId" title="ID"/>
  <t:col name="firstName" title="First Name"/>
  <t:col name="lastName" title="Last Name"/>
  <t:col>
    <s:link href="/Customer.action" event="preEdit">
      Edit
      <s:param name="customer.customerId" value="${obj.customerId}"/>
      <s:param name="page" value="${actionBean.page}"/>
    </s:link>
  </t:col>
</t:table>

Of course the tags work with the JSTL tags (like c:if, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.

So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.

At a higher level, you can do sophisticated things like this table tag I have here.

How to move an element into another element?

For the sake of completeness, there is another approach wrap() or wrapAll() mentioned in this article. So the OP's question could possibly be solved by this (that is, assuming the <div id="destination" /> does not yet exist, the following approach will create such a wrapper from scratch - the OP was not clear about whether the wrapper already exists or not):

$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')

It sounds promising. However, when I was trying to do $("[id^=row]").wrapAll("<fieldset></fieldset>") on multiple nested structure like this:

<div id="row1">
    <label>Name</label>
    <input ...>
</div>

It correctly wraps those <div>...</div> and <input>...</input> BUT SOMEHOW LEAVES OUT the <label>...</label>. So I ended up use the explicit $("row1").append("#a_predefined_fieldset") instead. So, YMMV.

Maven2: Best practice for Enterprise Project (EAR file)

i have made a github repository to show what i think is a good (or best practices) startup project structure...

https://github.com/StefanHeimberg/stackoverflow-1134894

some keywords:

  • Maven 3
  • BOM (DependencyManagement of own dependencies)
  • Parent for all Projects (DependencyManagement from external dependencies and PluginManagement for global Project configuration)
  • JUnit / Mockito / DBUnit
  • Clean War project without WEB-INF/lib because dependencies are in EAR/lib folder.
  • Clean Ear project.
  • Minimal deployment descriptors for Java EE7
  • No Local EJB Interface because @LocalBean is sufficient.
  • Minimal maven configuration through maven user properties
  • Actual Deployment Descriptors for Servlet 3.1 / EJB 3.2 / JPA 2.1
  • usage of macker-maven-plugin to check architecture rules
  • Integration Tests enabled, but skipped. (skipITs=false) useful to enable on CI Build Server

Maven Output:

Reactor Summary:

MyProject - BOM .................................... SUCCESS [  0.494 s]
MyProject - Parent ................................. SUCCESS [  0.330 s]
MyProject - Common ................................. SUCCESS [  3.498 s]
MyProject - Persistence ............................ SUCCESS [  1.045 s]
MyProject - Business ............................... SUCCESS [  1.233 s]
MyProject - Web .................................... SUCCESS [  1.330 s]
MyProject - Application ............................ SUCCESS [  0.679 s]
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.817 s
Finished at: 2015-01-27T00:51:59+01:00
Final Memory: 24M/207M
------------------------------------------------------------------------

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

Python: pandas merge multiple dataframes

There are 2 solutions for this, but it return all columns separately:

import functools

dfs = [df1, df2, df3]

df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
          date     a_x   b_x       a_y      b_y   c_x         a        b   c_y
0  May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
                0_a   0_b       1_a      1_b   1_c       2_a      2_b   2_c
date                                                                       
May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

Using os.walk() to recursively traverse directories in Python

try this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""FileTreeMaker.py: ..."""

__author__  = "legendmohe"

import os
import argparse
import time

class FileTreeMaker(object):

    def _recurse(self, parent_path, file_list, prefix, output_buf, level):
        if len(file_list) == 0 \
            or (self.max_level != -1 and self.max_level <= level):
            return
        else:
            file_list.sort(key=lambda f: os.path.isfile(os.path.join(parent_path, f)))
            for idx, sub_path in enumerate(file_list):
                if any(exclude_name in sub_path for exclude_name in self.exn):
                    continue

                full_path = os.path.join(parent_path, sub_path)
                idc = "??"
                if idx == len(file_list) - 1:
                    idc = "??"

                if os.path.isdir(full_path) and sub_path not in self.exf:
                    output_buf.append("%s%s[%s]" % (prefix, idc, sub_path))
                    if len(file_list) > 1 and idx != len(file_list) - 1:
                        tmp_prefix = prefix + "?  "
                    else:
                        tmp_prefix = prefix + "    "
                    self._recurse(full_path, os.listdir(full_path), tmp_prefix, output_buf, level + 1)
                elif os.path.isfile(full_path):
                    output_buf.append("%s%s%s" % (prefix, idc, sub_path))

    def make(self, args):
        self.root = args.root
        self.exf = args.exclude_folder
        self.exn = args.exclude_name
        self.max_level = args.max_level

        print("root:%s" % self.root)

        buf = []
        path_parts = self.root.rsplit(os.path.sep, 1)
        buf.append("[%s]" % (path_parts[-1],))
        self._recurse(self.root, os.listdir(self.root), "", buf, 0)

        output_str = "\n".join(buf)
        if len(args.output) != 0:
            with open(args.output, 'w') as of:
                of.write(output_str)
        return output_str

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--root", help="root of file tree", default=".")
    parser.add_argument("-o", "--output", help="output file name", default="")
    parser.add_argument("-xf", "--exclude_folder", nargs='*', help="exclude folder", default=[])
    parser.add_argument("-xn", "--exclude_name", nargs='*', help="exclude name", default=[])
    parser.add_argument("-m", "--max_level", help="max level",
                        type=int, default=-1)
    args = parser.parse_args()
    print(FileTreeMaker().make(args))

you will get this:

root:.
[.]
??[.idea]
?  ??[scopes]
?  ?  ??scope_settings.xml
?  ??.name
?  ??Demo.iml
?  ??encodings.xml
?  ??misc.xml
?  ??modules.xml
?  ??vcs.xml
?  ??workspace.xml
??[test1]
?  ??test1.txt
??[test2]
?  ??[test2-2]
?  ?  ??[test2-3]
?  ?      ??test2
?  ?      ??test2-3-1
?  ??test2
??folder_tree_maker.py
??tree.py

Does Google Chrome work with Selenium IDE (as Firefox does)?

Just fyi . This is available as nuget package in visual studio environment. Please let me know if you need more information as I have used it. URL can be found Link to nuget

You can also find some information here. Blog with more details

C/C++ Struct vs Class

Other that the differences in the default access (public/private), there is no difference.

However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."

Note that C unions work with C++, but not the other way around. For example

union WorksWithCppOnly{
    WorksWithCppOnly():a(0){}
    friend class FloatAccessor;
    int a;
private:
    float b;
};

And likewise

typedef union friend{
    int a;
    float b;
} class;

only works in C

Get CPU Usage from Windows Command Prompt

typeperf gives me issues when it randomly doesn't work on some computers (Error: No valid counters.) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:

@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%

Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter (preferred) or Get-WmiObject:

Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"

Or,

Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"


To get the overall CPU load with formatted output exactly like the question:

Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"

Or,

 Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"

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

Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.

Your PicPath is a relative path that is converted into an absolute path at some time while loading the image. Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

Calculate percentage Javascript

_x000D_
_x000D_
function calculate() {_x000D_
    // amount_x000D_
        var salary = parseInt($('#salary').val());_x000D_
    // percent    _x000D_
        var incentive_rate = parseInt($('#incentive_rate').val());_x000D_
        var perc = "";_x000D_
        if (isNaN(salary) || isNaN(incentive_rate)) {_x000D_
            perc = " ";_x000D_
        } else {_x000D_
            perc =  (incentive_rate/100) * salary;_x000D_
          _x000D_
_x000D_
        } $('#total_income').val(perc);_x000D_
    }
_x000D_
_x000D_
_x000D_

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

delete_all vs destroy_all?

To avoid the fact that destroy_all instantiates all the records and destroys them one at a time, you can use it directly from the model class.

So instead of :

u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all

You can do :

u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"

The result is one query to destroy all the associated records

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

How do I prompt for Yes/No/Cancel input in a Linux shell script?

You can use the default REPLY on a read, convert to lowercase and compare to a set of variables with an expression.
The script also supports ja/si/oui

read -rp "Do you want a demo? [y/n/c] "

[[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo "Selected Cancel"; exit 1; }

if [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then
   echo "Positive"
fi

SQL Server : fetching records between two dates?

The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <)

select * 
from xxx 
where dates >= '20121026'
  and dates <  '20121028'

If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.

select * 
from xxx 
where CAST(dates as DATE) between '20121026' and '20121027'

This explicitly tells SQL Server that you are only interested in the DATE portion of the dates column for comparison against the BETWEEN range.

Copying a rsa public key to clipboard

cat .ssh/id_rsa.pub | bcopy

This works for me.

How to reload current page without losing any form data?

As some answers mention, localStorage is a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.

How can I connect to a Tor hidden service using cURL in PHP?

I use Privoxy and cURL to scrape Tor pages:

<?php
    $ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_exec($ch);
    curl_close($ch);
?>

After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config). Note the space and '.' a the end of line.

forward-socks4a / localhost:9050 .

Then restart Privoxy.

/etc/init.d/privoxy restart

Python Selenium accessing HTML source

You need to access the page_source property:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://example.com")

html_source = browser.page_source
if "whatever" in html_source:
    # do something
else:
    # do something else

How to see the actual Oracle SQL statement that is being executed

-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome

WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID

) rollback_remaining,

(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;

UNION with WHERE clause

NOTE: While my advice was true many years ago, Oracle's optimizer has improved so that the location of the where definitely no longer matters here. However preferring UNION ALL vs UNION will always be true, and portable SQL should avoid depending on optimizations that may not be in all databases.

Short answer, you want the WHERE before the UNION and you want to use UNION ALL if at all possible. If you are using UNION ALL then check the EXPLAIN output, Oracle might be smart enough to optimize the WHERE condition if it is left after.

The reason is the following. The definition of a UNION says that if there are duplicates in the two data sets, they have to be removed. Therefore there is an implicit GROUP BY in that operation, which tends to be slow. Worse yet, Oracle's optimizer (at least as of 3 years ago, and I don't think it has changed) doesn't try to push conditions through a GROUP BY (implicit or explicit). Therefore Oracle has to construct larger data sets than necessary, group them, and only then gets to filter. Thus prefiltering wherever possible is officially a Good Idea. (This is, incidentally, why it is important to put conditions in the WHERE whenever possible instead of leaving them in a HAVING clause.)

Furthermore if you happen to know that there won't be duplicates between the two data sets, then use UNION ALL. That is like UNION in that it concatenates datasets, but it doesn't try to deduplicate data. This saves an expensive grouping operation. In my experience it is quite common to be able to take advantage of this operation.

Since UNION ALL does not have an implicit GROUP BY in it, it is possible that Oracle's optimizer knows how to push conditions through it. I don't have Oracle sitting around to test, so you will need to test that yourself.

Angular 2: Passing Data to Routes?

You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.

The old router allows to pass data but the new (RC.1) router doesn't yet.

Update

data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

Visual Studio "Could not copy" .... during build

Exception

In some cases in Visual Studio when you (Build || Rebuild) on top of running IISExpress you faced with this Exception:

Unable to copy file "obj\Debug\YourProjectName.dll" to bin\YourProjectName.dll". the process cannot access the file 'bin\YourProjectName.dll' because it is being used by another process

Solution

  1. Right click on web project that needs to build.
  2. Click on properties.
  3. Select Build Events Tab on the left side.
  4. In Pre-build events command line paste these 2 line:
tasklist /fi "imagename eq iisexpress.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "iisexpress.exe"

You are good 2 GO!

IE8 support for CSS Media Query

The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:

<!--[if lt IE 9]>
<script src="respond.min.js"></script>
<![endif]-->

It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9

Java ArrayList clear() function

Your assumptions don't seem to be right. After a clear(), the newly added data start from index 0.

SQL - How do I get only the numbers after the decimal?

You can use RIGHT :

 select RIGHT(123.45,2) return => 45

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

You have more static resources that the cache has room for. You can do one of the following:

  • Increase the size of the cache
  • Decrease the TTL for the cache
  • Disable caching

For more details see the documentation for these configuration options.

535-5.7.8 Username and Password not accepted

UPDATE:

Notice: This setting is not available for accounts with 2-Step Verification enabled, which mean you have to disable 2 factor authentication.

enter image description here

If you disable the 2-Step Verification:

enter image description here

Decimal separator comma (',') with numberDecimal inputType in EditText

to get localize your input use:

char sep = DecimalFormatSymbols.getInstance().getDecimalSeparator();

and then add:

textEdit.setKeyListener(DigitsKeyListener.getInstance("0123456789" + sep));

than don't forget to replace "," with "." so Float or Double can parse it without errors.

How to round an average to 2 decimal places in PostgreSQL?

you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How do I change the database name using MySQL?

I agree with above answers and tips but there is a way to change database name with phpmyadmin

Renaming the Database From cPanel, click on phpMyAdmin. (It should open in a new tab.) Click on the database you wish to rename in the left hand column. Click on the Operations tab. Where it says "Rename database to:" enter the new database name. Click the Go button. When it asks you to want to create the new database and drop the old database, click OK to proceed. (This is a good time to make sure you spelled the new name correctly.) Once the operation is complete, click OK when asked if you want to reload the database.

here's the video tutorial:

http://support.hostgator.com/articles/specialized-help/technical/phpmyadmin/how-to-rename-a-database-in-phpmyadmin

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Syntax: error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
Default:    
error_log logs/error.log error;
Context:    main, http, stream, server, location

http://nginx.org/en/docs/ngx_core_module.html#error_log

Don't use: /dev/stderr This will break your setup if you're going to use systemd-nspawn.

Preferred method to store PHP arrays (json_encode vs serialize)

If to summ up what people say here, json_decode/encode seems faster than serialize/unserialize BUT If you do var_dump the type of the serialized object is changed. If for some reason you want to keep the type, go with serialize!

(try for example stdClass vs array)

serialize/unserialize:

Array cache:
array (size=2)
  'a' => string '1' (length=1)
  'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(Controller\Test)[8]
  protected 'view' => 

json encode/decode

Array cache:
object(stdClass)[7]
  public 'a' => string '1' (length=1)
  public 'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(stdClass)[8]

As you can see the json_encode/decode converts all to stdClass, which is not that good, object info lost... So decide based on needs, especially if it is not only arrays...

Ways to eliminate switch in code

Everybody loves HUGE if else blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a better solution is debatable.

Language is an important factor here also, I think.

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

How to count number of unique values of a field in a tab-delimited text file?

Assuming the data file is actually Tab separated, not space aligned:

<test.tsv awk '{print $4}' | sort | uniq

Where $4 will be:

  • $1 - Red
  • $2 - Ball
  • $3 - 1
  • $4 - Sold

Run chrome in fullscreen mode on Windows

Update 03-Oct-19

new script that displays 10second countdown then launches chrome/chromiumn in fullscreen kiosk mode.

more updates to chrome required script update to allow autoplaying video with audio. Note --overscroll-history-navigation=0 isn't working currently will need to disable this flag by going to chrome://flags/#overscroll-history-navigation in your browser and setting to disabled.

@echo off
echo Countdown to application launch...
timeout /t 10
"C:\Program Files (x86)\chrome-win32\chrome.exe" --chrome --kiosk http://localhost/xxxx --incognito --disable-pinch --no-user-gesture-required --overscroll-history-navigation=0
exit

might need to set chrome://flags/#autoplay-policy if running an older version of chrome (60 below)

Update 11-May-16

There have been many updates to chrome since I posted this and have had to alter the script alot to keep it working as I needed.

Couple of issues with newer versions of chrome:

  • built in pinch to zoom
  • Chrome restore error always showing after forced shutdown
  • auto update popup

Because of the restore error switched out to incognito mode as this launches a clear version all the time and does not save what the user was viewing and so if it crashes there is nothing to restore. Also the auto up in newer versions of chrome being a pain to try and disable I switched out to use chromium as it does not auto update and still gives all the modern features of chrome. Note make sure you download the top version of chromium this comes with all audio and video codecs as the basic version of chromium does not support all codecs.

Chromium download link

@echo off

echo Step 1 of 2: Waiting a few seconds before starting the Kiosk...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Step 2 of 5: Waiting a few more seconds before starting the browser...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Final 'invisible' step: Starting the browser, Finally...

"C:\Program Files (x86)\Google\Chromium\chrome.exe" --chrome --kiosk http://127.0.0.1/xxxx --incognito --disable-pinch --overscroll-history-navigation=0

exit

Outdated

I use this for exhibitions to lock down screens. I think its what your looking for.

  • Start chrome and go to www.google.com drag and drop the url out onto the desktop
  • rename it to something handy for this example google_homepage
  • drop this now into your c directory, click on my computer c: and drop this file in there
  • start chrome again go to settings and under on start up select open a specific page and set your home page here.

Next part is the script that I use to start close and restart chrome again in kiosk mode. The locations is where I have chrome installed so it might be abit different for you depending on your install.

Open your text editor of choice or just notepad and past the below code in, make sure its in the same format/order as below. Save it to your desktop as what ever you like so for this example chrome_startup_script.txt next right click it and rename, remove the txt from the end and put in bat instead. double click this to launch the script to see if its working correctly.

A command line box should appear and run through the script, chrome will start and then close down the reason to do this is to remove any error reports such as if the pc crashed, when chrome starts again without this it would show the yellow error bar at the top saying chrome did not shut down properly would you like to restore it. After a few seconds chrome should start again and in kiosk mode and will point to what ever homepage you have set.

@echo off
echo Step 1 of 5: Waiting a few seconds before starting the Kiosk...
"C:\windows\system32\ping" -n 31 -w 1000 127.0.0.1 >NUL
echo Step 2 of 5: Starting browser as a pre-start to delete error messages...
"C:\google_homepage.url"
echo Step 3 of 5: Waiting a few seconds before killing the browser task...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Step 4 of 5: Killing the browser task gracefully to avoid session restore...
Taskkill /IM chrome.exe
echo Step 5 of 5: Waiting a few seconds before restarting the browser...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Final 'invisible' step: Starting the browser, Finally...
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk --overscroll-history-navigation=0"
exit

Note: The number after the -n of the ping is the amount of seconds (minus one second) to wait before starting the link (or application in the next line)

Finally if this is all working then you can drag and drop the .bat file into the startup folder in windows and this script will launch each time windows starts.


Update:

With recent versions of chrome they have really got into enabling touch gestures, this means that swiping left or right on a touchscreen will cause the browser to go forward or backward in history. To prevent this we need to disable the history navigation on the back and forward buttons to do that add the following --overscroll-history-navigation=0 to the end of the script.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

how to change default python version?

I am using OS X 10.7.5 and Python 3.4.2. If you type python3 and what you want to run it will run it using python 3. For example pyhton3 test001.py. That ran a test program I made called test001. I hope this helps.

Is there a limit on number of tcp/ip connections between machines on linux?

Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

HTML <input type='file'> File Selection Event

Listen to the change event.

input.onchange = function(e) { 
  ..
};

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

versionCode vs versionName in Android Manifest

Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.

Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.

For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).

Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".

Hope that helps.

You can read more about it here

In Visual Basic how do you create a block comment

In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.

Can Android do peer-to-peer ad-hoc networking?

my friend and I are currently developing a java library implementing the AODV protocol (multihop routing suitable for mobile networks), in our bachelor thesis. The final 'product' includes a easy way to create/join an adhoc network on several android devices and an interface through the library, to send and receive messages. Unfortunately each type of phone such as hero, nexsus one... have a phonedepended way for createing a adhoc network so currently we are only supporting a few phones).

this means that once this project is finished, people with rooted phones can implement their distributed applications (file sharing, games, ...) by simply including the library .jar file in their android projects.

it's all open source by the way

http://code.google.com/p/adhoc-on-android/

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

How can I use onItemSelected in Android?

If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

How to extract URL parameters from a URL with Ruby or Rails?

For a pure Ruby solution combine URI.parse with CGI.parse (this can be used even if Rails/Rack etc. are not required):

CGI.parse(URI.parse(url).query) 
# =>  {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }

How to remove single character from a String

I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

This is the output:

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG

What is the difference between SAX and DOM?

In practical: book.xml

<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
</bookstore>
  • DOM presents the xml document as a the following tree-structure in memory.
  • DOM is W3C standard.
  • DOM parser works on Document Object Model.
  • DOM occupies more memory, preferred for small XML documents
  • DOM is Easy to navigate either forward or backward.

enter image description here


  • SAX presents the xml document as event based like start element:abc, end element:abc.
  • SAX is not W3C standard, it was developed by group of developers.
  • SAX does not use memory, preferred for large XML documents.
  • Backward navigation is not possible as it sequentially process the documents.
  • Event happens to a node/element and it gives all sub nodes(Latin nodus, ‘knot’).

This XML document, when passed through a SAX parser, will generate a sequence of events like the following:

start element: bookstore
start element: book with an attribute category equal to cooking
start element: title with an attribute lang equal to en
Text node, with data equal to Everyday Italian
....
end element: title
.....
end element: book
end element: bookstore

Installing J2EE into existing eclipse IDE

http://download.eclipse.org/webtools/updates/ - This is an old URL and doesn't work any more. If you want to install WTP (i.e. J2EE plugins) use the following URLs depending upon the version of the eclipse you are using:

More information can be found here.

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

Why does viewWillAppear not get called when an app comes back from the background?

Use Notification Center in the viewDidLoad: method of your ViewController to call a method and from there do what you were supposed to do in your viewWillAppear: method. Calling viewWillAppear: directly is not a good option.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationIsActive:) 
        name:UIApplicationDidBecomeActiveNotification 
        object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationEnteredForeground:) 
        name:UIApplicationWillEnterForegroundNotification
        object:nil];
}

- (void)applicationIsActive:(NSNotification *)notification {
    NSLog(@"Application Did Become Active");
}

- (void)applicationEnteredForeground:(NSNotification *)notification {
    NSLog(@"Application Entered Foreground");
}

builtins.TypeError: must be str, not bytes

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

Tomcat: LifecycleException when deploying


Tomcat has different WAR deployment ways. Some work, some don't. Please try the following deployment methods :

  • Automatic: Copy-paste your WAR file into ${CATALINA_HOME}/webapps. A folder with the same name will appear if everything goes right.
  • Manager Application: Upload the WAR file
  • Manager Application: Locate the WAR file

In my case, using the Manager Application (local URL: http://localhost:8080/manager) worked. Whereas deploying using a copy-paste resulted in your error.

Jquery selector input[type=text]')

$('.sys').children('input[type=text], select').each(function () { ... });

EDIT: Actually this code above is equivalent to the children selector .sys > input[type=text] if you want the descendant select (.sys input[type=text]) you need to use the options given by @NiftyDude.

More information:

How to fix Invalid AES key length?

I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.

How to git-cherry-pick only changes to certain files?

Cherry pick is to pick changes from a specific "commit". The simplest solution is to pick all changes of certain files is to use

 git checkout source_branch <paths>...

In example:

$ git branch
* master
  twitter_integration
$ git checkout twitter_integration app/models/avatar.rb db/migrate/20090223104419_create_avatars.rb test/unit/models/avatar_test.rb test/functional/models/avatar_test.rb
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   app/models/avatar.rb
#   new file:   db/migrate/20090223104419_create_avatars.rb
#   new file:   test/functional/models/avatar_test.rb
#   new file:   test/unit/models/avatar_test.rb
#
$ git commit -m "'Merge' avatar code from 'twitter_integration' branch"
[master]: created 4d3e37b: "'Merge' avatar code from 'twitter_integration' branch"
4 files changed, 72 insertions(+), 0 deletions(-)
create mode 100644 app/models/avatar.rb
create mode 100644 db/migrate/20090223104419_create_avatars.rb
create mode 100644 test/functional/models/avatar_test.rb
create mode 100644 test/unit/models/avatar_test.rb

Sources and full explanation http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/

UPDATE:

With this method, git will not MERGE the file, it will just override any other change done on the destination branch. You will need to merge the changes manually:

$ git diff HEAD filename

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

How to scroll to specific item using jQuery?

Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.

I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes

$container.scrollTo( targetPosition );

But that's not all. We need to fix the target position, too. The calculation you see in other answers,

$target.offset().top - $container.offset().top + $container.scrollTop()

mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.

Hence, a better way to calculate the target position is

var target = $target[0], 
    container = $container[0];

targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;

Again, have a look at the demo to see it in action.

For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.

In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

Converting PKCS#12 certificate into PEM using OpenSSL

Try:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes

After that you have:

  • certificate in newfile.crt.pem
  • private key in newfile.key.pem

To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:

openssl pkcs12 -in path.p12 -out newfile.pem -nodes

Or, if you want to provide a password for the private key, omit -nodes and input a password:

openssl pkcs12 -in path.p12 -out newfile.pem

If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'

npm global path prefix

Simple solution is ...

Just put below command :

  1. sudo npm config get prefix

    if it's not something like these /usr/local, than you need to fix it using below command.

  2. sudo npm config set prefix /usr/local...

Now it's 100% working fine

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": "https://awww.api.com"

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

Make install, but not to default directories?

make DESTDIR=./new/customized/path install

This quick command worked for me for opencv release 3.2.0 installation on Ubuntu 16. DESTDIR path can be relative as well as absolute.

Such redirection can also be useful in case user does not have admin privileges as long as DESTDIR location has right access for the user. e.g /home//

You have not accepted the license agreements of the following SDK components

In linux

 1. Open a terminal
 2. Write: "cd $ANDROID_HOME/tools/bin (this path can be /home/your-user/Android/Sdk/tools/bin)"
 3. Write: "./sdkmanager --licenses"
 4. To accept All licenses listed, write: "y"
 5. Ready!

If your are building an app with Ionic Framework, just write again the command to build it.

How to create text file and insert data to that file on Android

First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }

How can I check if a program exists from a Bash script?

hash foo 2>/dev/null: works with Z shell (Zsh), Bash, Dash and ash.

type -p foo: it appears to work with Z shell, Bash and ash (BusyBox), but not Dash (it interprets -p as an argument).

command -v foo: works with Z shell, Bash, Dash, but not ash (BusyBox) (-ash: command: not found).

Also note that builtin is not available with ash and Dash.

Responsively change div size keeping aspect ratio

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

Working example: http://jsfiddle.net/QtftX/1/

RESTful Authentication via Spring

We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:

Set up the security context like so:

<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

CustomAuthenticationEntryPoint:

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:

public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start. Happy coding. :)

Sql Server string to date conversion

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

Make the console wait for a user input to close

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

What is the largest Safe UDP Packet Size on the Internet

IPv4 minimum reassembly buffer size is 576, IPv6 has it at 1500. Subtract header sizes from here. See UNIX Network Programming by W. Richard Stevens :)

Connection refused on docker container

You need to publish the exposed ports by using the following options:

-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.

-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.

The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo and check which random ports are being used from your host at the Ports section.

Just run the following command:

docker run -it -p 8080:8080 demo

After that your url will work.

How to save the output of a console.log(object) to a file?

You can use library l2i (https://github.com/seriyvolk83/logs2indexeddb) to save all you put into console.log and then invoke

l2i.download();

to download a file with logs.

NVIDIA NVML Driver/library version mismatch

This also happened to me on Ubuntu 16.04 using the nvidia-348 package (latest nvidia version on Ubuntu 16.04).

However I could resolve the problem by installing nvidia-390 through the Proprietary GPU Drivers PPA.

So a solution to the described problem on Ubuntu 16.04 is doing this:

  • sudo add-apt-repository ppa:graphics-drivers/ppa
  • sudo apt-get update
  • sudo apt-get install nvidia-390

Note: This guide assumes a clean Ubuntu install. If you have previous drivers installed a reboot migh be needed to reload all the kernel modules.

How to add 10 days to current time in Rails

Some other options, just for reference

-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)

Just list out all options I know:

[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10

So now, what is the difference between them if we care about the timezone:

  • [1, 4] With system timezone
  • [2, 3] With config timezone of your Rails app
  • [5] Date only no time included in result

Notification bar icon turns white in Android 5 Lollipop

Completely agree with user Daniel Saidi. In Order to have Color for NotificationIcon I'm writing this answer.

For that you've to make icon like Silhouette and make some section Transparent wherever you wants to add your Colors. i.e,

enter image description here

You can add your color using

.setColor(your_color_resource_here)

NOTE : setColor is only available in Lollipop so, you've to check OSVersion

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    Notification notification = new Notification.Builder(context)
    ...
} else {
    // Lollipop specific setColor method goes here.
    Notification notification = new Notification.Builder(context)
    ...
    notification.setColor(your_color)
    ...            
}

You can also achieve this using Lollipop as the target SDK.

All instruction regarding NotificationIcon given at Google Developer Console Notification Guide Lines.

Preferred Notification Icon Size 24x24dp

mdpi    @ 24.00dp   = 24.00px
hdpi    @ 24.00dp   = 36.00px
xhdpi   @ 24.00dp   = 48.00px

And also refer this link for Notification Icon Sizes for more info.

Using if elif fi in shell scripts

This is working for me,

 # cat checking.sh
 #!/bin/bash
 echo "You have provided the following arguments $arg1 $arg2 $arg3"
 if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
 then
     echo "Two of the provided args are equal."
     exit 3
 elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ]
 then
     echo "All of the specified args are equal"
     exit 0
 else
     echo "All of the specified args are different"
     exit 4
 fi

 # ./checking.sh
 You have provided the following arguments
 All of the specified args are equal

You can add set -x in script to troubleshoot the errors.

How do I install the babel-polyfill library?

Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.

So this worked for me:

npm install --save [email protected]
npm install regenerator-runtime

then add to the very top of your initial js file:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

Java Array, Finding Duplicates

How about using this method?

HashSet<Integer> zipcodeSet = new HashSet<Integer>(Arrays.asList(zipcodeList));
duplicates = zipcodeSet.size()!=zipcodeList.length;

Maintaining Session through Angular.js

Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side

As mentioned in the above post. The session is created using the factory recipe.

Client side session can be maintained using the value provider recipe as well.

Please refer to my post for the complete details. session-tracking-in-angularjs

Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.

In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.

Here we create the custom injectable service having a cart inside using the "value provider recipe".

'use strict';
function Cart() {
    return {
        'cartId': '',
        'cartItem': []
    };
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart 

app.value('sessionService', {
    cart: new Cart(),
    clear: function () {
        this.cart = new Cart();
        // mechanism to create the cart id 
        this.cart.cartId = 1;
    },
    save: function (session) {
        this.cart = session.cart;
    },
    updateCart: function (productId, productQty) {
        this.cart.cartItem.push({
            'productId': productId,
            'productQty': productQty
        });
    },
    //deleteItem and other cart operations function goes here...
});

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

How do I import a .dmp file into Oracle?

Presuming you have a .dmp file created by oracle exp then

imp help=y

will be your friend. It will lead you to

imp file=<file>.dmp show=y

to see the contents of the dump and then something like

imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>

to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly

Check if the number is integer

Once can also use dplyr::near:

library(dplyr)

near(a, as.integer(a))

It applies to any vector a, and has an optional tolerance parameter.

In Jenkins, how to checkout a project into a specific directory (using GIT)

It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.

node{
    def exists = fileExists 'foo'
    if (!exists){
        new File('foo').mkdir()
    }
    dir ('foo') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'bar'
    if (!exists){
        new File('bar').mkdir()
    }
    dir ('bar') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'baz'
    if (!exists){
        new File('baz').mkdir()
    }
    dir ('baz') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.

IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.

To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.

So, be aware.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

illegal use of break statement; javascript

You need to make sure requestAnimFrame stops being called once game == 1. A break statement only exits a traditional loop (e.g. while()).

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        if (game != 1) {
            requestAnimFrame(loop);
        }
    }
}

Or alternatively you could simply skip the second if condition and change the first condition to if (isPlaying && game !== 1). You would have to make a variable called game and give it a value of 0. Add 1 to it every game.

How do I reverse an int array in Java?

This will help you

int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
    int temp = a[k];
    a[k] = a[a.length-(1+k)];
    a[a.length-(1+k)] = temp;
}

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Add querystring parameters to link_to

The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

From Oracle 11gR2, the LISTAGG clause should do the trick:

SELECT question_id,
       LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;

Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.

How and where are Annotations used in Java?

Java EE 5 favors the use of annotations over XML configuration. For example, in EJB3 the transaction attributes on an EJB method are specified using annotations. They even use annotations to mark POJOs as EJBs and to specify particular methods as lifecycle methods instead of requiring that implementation of an interface.

AngularJS format JSON string output

Angular has a built-in filter for showing JSON

<pre>{{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo:

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .controller('Ctrl', ['$scope',_x000D_
    function($scope) {_x000D_
_x000D_
      $scope.data = {_x000D_
        a: 1,_x000D_
        b: 2,_x000D_
        c: {_x000D_
          d: "3"_x000D_
        },_x000D_
      };_x000D_
_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-controller="Ctrl">_x000D_
    <pre>{{data | json}}</pre>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

There's also an angular.toJson method, but I haven't played around with that (Docs)

window.open with target "_blank" in Chrome

You can't do it because you can't have control on the manner Chrome opens its windows

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

rotating axis labels in R

First, create the data for the chart

H <- c(1.964138757, 1.729143013,    1.713273714,    1.706771799,    1.67977205)
M <- c("SP105", "SP30", "SP244", "SP31",    "SP147")

Second, give the name for a chart file

png(file = "Bargraph.jpeg", width = 500, height = 300)

Third, Plot the bar chart

barplot(H,names.arg=M,ylab="Degree ", col= rainbow(5), las=2, border = 0, cex.lab=1, cex.axis=1, font=1,col.axis="black")
title(xlab="Service Providers", line=4, cex.lab=1)

Finally, save the file

dev.off()

Output:

enter image description here

Validate phone number using javascript

In JavaScript, the below regular expression can be used for a phone number :

^((\+1)?[\s-]?)?\(?[1-9]\d\d\)?[\s-]?[1-9]\d\d[\s-]?\d\d\d\d

e.g; 9999875099 , 8750999912 etc.

Reference : https://techsolutions.filebizz.com/2020/08/regular-expression-for-phone-number-in.html

How to make CSS width to fill parent?

Use the styles

left: 0px;

or/and

right: 0px;

or/and

top: 0px;

or/and

bottom: 0px;

I think for most cases that will do the job

Change a Rails application to production

This would now be

rails server -e production

Or, more compact

rails s -e production

It works for rails 3+ projects.

Uncaught TypeError: Cannot read property 'value' of null

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)

how to avoid a new line with p tag?

something like:

p
{
    display:inline;
}

in your stylesheet would do it for all p tags.

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Go to C:\xamppp\php. Set these values in php.ini:

upload_max_filesize = 1000M
post_max_size = 0M

Android Color Picker

try this open source projects that might help you

https://github.com/QuadFlask/colorpicker

Where does flask look for image files?

It took me a while to figure this out too. url_for in Flask looks for endpoints that you specified in the routes.py script.

So if you have a decorator in your routes.py file like @blah.route('/folder.subfolder') then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }} . The 'folder.subfolder' argument sends it to a Flask endpoint it recognizes.

However let us say that you stored your image file, some_image.jpg, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py, your route decorator looks like @blah.routes('/folder'). You then have to ask for your image file this way: {{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}

I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.

HTTP test server accepting GET/POST requests

Have a look at PutsReq, it's similar to the others, but it also allows you to write the responses you want using JavaScript.

How to apply CSS to iframe?

Edit: This does not work cross domain unless the appropriate CORS header is set.

There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

<iframe name="iframe1" id="iframe1" src="empty.htm" 
        frameborder="0" border="0" cellspacing="0"
        style="border-style: none;width: 100%; height: 120px;"></iframe>

The style of the page embedded in the iframe must be either set by including it in the child page:

<link type="text/css" rel="Stylesheet" href="Style/simple.css" />

Or it can be loaded from the parent page with Javascript:

var cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);

How do you get assembler output from C/C++ source in gcc?

If what you want to see depends on the linking of the output, then objdump on the output object file/executable may also be useful in addition to the aforementioned gcc -S. Here's a very useful script by Loren Merritt that converts the default objdump syntax into the more readable nasm syntax:

#!/usr/bin/perl -w
$ptr='(BYTE|WORD|DWORD|QWORD|XMMWORD) PTR ';
$reg='(?:[er]?(?:[abcd]x|[sd]i|[sb]p)|[abcd][hl]|r1?[0-589][dwb]?|mm[0-7]|xmm1?[0-9])';
open FH, '-|', '/usr/bin/objdump', '-w', '-M', 'intel', @ARGV or die;
$prev = "";
while(<FH>){
    if(/$ptr/o) {
        s/$ptr(\[[^\[\]]+\],$reg)/$2/o or
        s/($reg,)$ptr(\[[^\[\]]+\])/$1$3/o or
        s/$ptr/lc $1/oe;
    }
    if($prev =~ /\t(repz )?ret / and
       $_ =~ /\tnop |\txchg *ax,ax$/) {
       # drop this line
    } else {
       print $prev;
       $prev = $_;
    }
}
print $prev;
close FH;

I suspect this can also be used on the output of gcc -S.

How to describe "object" arguments in jsdoc?

There's a new @config tag for these cases. They link to the preceding @param.

/** My function does X and Y.
    @params {object} parameters An object containing the parameters
    @config {integer} setting1 A required setting.
    @config {string} [setting2] An optional setting.
    @params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
    // ...
};

/**
 * This callback is displayed as part of the MyClass class.
 * @callback MyClass~FuncCallback
 * @param {number} responseCode
 * @param {string} responseMessage
 */

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

building on these answers - i also had to modify an X86 reference under Librarian -> Command Line -> Additional Options (for the x64 Platform)

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Remove "track by index" from the ng-repeat and it would refresh the DOM

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

How to create a directory and give permission in single command

IMO, it's better to use the install command in such situations. I was trying to make systemd-journald persistent across reboots.

install -d  -g systemd-journal -m 2755 -v /var/log/journal

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

How do I show a console output/window in a forms application?

Perhaps this is over-simplistic...

Create a Windows Form project...

Then: Project Properties -> Application -> Output Type -> Console Application

Then can have Console and Forms running together, works for me

How can you sort an array without mutating the original array?

Just copy the array. There are many ways to do that:

function sort(arr) {
  return arr.concat().sort();
}

// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects

Execute a batch file on a remote PC using a batch file on local PC

You can use WMIC or SCHTASKS (which means no third party software is needed):

1) SCHTASKS:

SCHTASKS /s remote_machine /U username /P password /create /tn "On demand demo" /tr "C:\some.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /s remote_machine /U username /P password /run /TN "On demand demo" 

2) WMIC (wmic will return the pid of the started process)

WMIC /NODE:"remote_machine" /user user /password password process call create "c:\some.bat","c:\exec_dir"

Python: most idiomatic way to convert None to empty string?

If you actually want your function to behave like the str() built-in, but return an empty string when the argument is None, do this:

def xstr(s):
    if s is None:
        return ''
    return str(s)

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

You need to place google-services.json into app/ dir. And for each build type, there should be accordant director in app/src folder.

For example, if you have release and debug:

app/google-services.json
app/src/debug/google-services.json

In all google-services.json files you should specify correct package_name according to build type.

For example, inside debug dir it should be like {com.myapp}.debug

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

In angular 7 got this fixed by adding these lines to .module.ts file:

import { CommonModule } from '@angular/common'; imports: [CommonModule]

Invariant Violation: Objects are not valid as a React child

In my case it was because of a dynamic array which had to be injected at runtime.

I just added the null checks for object and it worked fine.

Before:

...
render(
...
    <div> {props.data.roles[0]} </div>
...
);

After:

...
let items = (props && props.data && props.data.roles)? props.data.roles: [];
render(
...
    <div> {items[i]} </div>
...
);

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

Regex match everything after question mark?

\?(.*)

You want the content of the first capture group.

How can I measure the actual memory usage of an application or process?

If the process is not using up too much memory (either because you expect this to be the case, or some other command has given this initial indication), and the process can withstand being stopped for a short period of time, you can try to use the gcore command.

gcore <pid>

Check the size of the generated core file to get a good idea how much memory a particular process is using.

This won't work too well if process is using hundreds of megabytes, or gigabytes, as the core generation could take several seconds or minutes to be created depending on I/O performance. During the core creation the process is stopped (or "frozen") to prevent memory changes. So be careful.

Also make sure the mount point where the core is generated has plenty of disk space and that the system will not react negatively to the core file being created in that particular directory.

How to re-sign the ipa file?

Fastlane's sigh provides a fairly robust solution for resigning IPAs.

From their README:

Resign

If you generated your ipa file but want to apply a different code signing onto the ipa file, you can use sigh resign:

fastlane sigh resign

sigh will find the ipa file and the provisioning profile for you if they are located in the current folder.

You can pass more information using the command line:

fastlane sigh resign ./path/app.ipa --signing_identity "iPhone Distribution: Felix Krause" -p "my.mobileprovision"

It will even handle provisioning profiles for nested applications (eg. if you have watchkit apps)

php var_dump() vs print_r()

var_dump($var) shows in-depth details, by providing additional details of

  • data type of the value (including the descendant elements)
  • number of elements in a variable
  • length of the value

Jquery select this + class

Use find()

$(this).find(".subclass").css("visibility","visible");

How to set up Android emulator proxy settings

In console start the next command:

emulator -avd emulator_name -http-proxy you_proxy_ip_address:8080

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

The solution I ended up choosing was MahApps.Metro (github), which (after using it on two pieces of software now) I consider an excellent UI kit (credit to Oliver Vogel for the suggestion).

Window style

It skins the application with very little effort required, and has adaptations of the standard Windows 8 controls. It's very robust.

Text box watermark

A version is available on Nuget:

You can install MahApps.Metro via Nuget using the GUI (right click on your project, Manage Nuget References, search for ‘MahApps.Metro’) or via the console:

PM> Install-Package MahApps.Metro

It's also free -- even for commercial use.

Update 10-29-2013:

I discovered that the Github version of MahApps.Metro is packed with controls and styles that aren't available in the current nuget version, including:

Datagrids:

enter image description here

Clean Window:

enter image description here

Flyouts:

enter image description here

Tiles:

enter image description here

The github repository is very active with quite a bit of user contributions. I recommend checking it out.

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

How to get all child inputs of a div element (jQuery)

If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById and this solution still works if you have multiple inputs with the same type.

var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
        .each(function() {
            $(this).val('');
        });
$(div).find('input:radio, input:checkbox').each(function() {
    $(this).removeAttr('checked');
    $(this).removeAttr('selected');
});

This examples shows how to clear the inputs, for you example you'll need to change it.

No 'Access-Control-Allow-Origin' header in Angular 2 app

I also had the same issue while using http://www.mocky.io/ what i did is to add in mock.io response header: Access-Control-Allow-Origin *

To add it there just need to click on advanced options

Mock.io Header Example Once this is done, my application was able to retrieve the data from external domain.

Associating enums with strings in C#

My first question - Do you have access to the Database itself? This should be normalized in the database, ideally, otherwise, any solution is going to be prone to error. In my experience, data fields full of "OEM" and "CMB" tend to wind up having things like "oem " and other 'crap data' mixed in over time.... If you can normalize it, you could use the key in the table containing the elements as your Enum, and you're done, with a much cleaner structure.

If that's not available, I'd make your Enum, and make a class to parse your string into the Enum for you. This would at least give you some flexibility in handling non-standard entries and much more flexibility for trapping or handling errors than doing any of the workarounds using Enum.Parse/Reflection/etc. A dictionary would work, but could break down if you ever have case issues, etc.

I'd recommend writing a class so you can do:

// I renamed this to GroupType, since it sounds like each element has a single type...
GroupType theType = GroupTypeParser.GetGroupType(theDBString);

This preserves most of your readability without having to change the DB.

Static array vs. dynamic array in C++

Local arrays are created on the stack, and have automatic storage duration -- you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size:

int foo[10];

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame:

int* foo = new int[10];
delete[] foo;

How do you simulate Mouse Click in C#?

I use the InvokeOnClick() method. It takes two arguments: Control and EventArgs. If you need the EventArgs, then create an instance of it and pass it in, else use InvokeOnClick(controlToClick, null);. You can use a variety of Mouse event related arguments that derive from EventArgs such as MouseEventArgs.

Is there any option to limit mongodb memory usage?

Adding to the top voted answer, in case you are on a low memory machine and want to configure the wiredTigerCache in MBs instead of whole number GBs, use this -

storage:
 wiredTiger:
  engineConfig:
    configString : cache_size=345M

Source - https://jira.mongodb.org/browse/SERVER-22274

Split function in oracle to comma separated values with automatic sequence

Here is how you could create such a table:

 SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
   FROM dual
CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;

With a little bit of tweaking (i.e., replacing the , in [^,] with a variable) you could write such a function to return a table.

How to convert FileInputStream to InputStream?

You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.

If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.

To answer some of your comments...

To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.

The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.

how to open popup window using jsp or jquery?

Can be done with in jquery-

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
    $( "#dialog" ).dialog();
    });
    </script>

    <div id="dialog" title="Basic dialog">
    //your form layout
    </div>

twitter bootstrap text-center when in xs mode

Css Part is:

CSS:

@media (max-width: 767px) {

  // Align text to center.
  .text-xs-center {
    text-align: center;
  } 
}

And the HTML part will be ( this text center work only below 767px width )

HTML:

 <div class="col-xs-12 col-sm-6 text-right text-xs-center">
        <p>
            <a href="#"><i class="fa fa-facebook"></i></a> 
            <a href="#"><i class="fa fa-twitter"></i></a> 
            <a href="#"><i class="fa fa-google-plus"></i></a>
        </p>
 </div>