Programs & Examples On #File transfer

Is a generic term for the act of transmitting files over a computer network or the Internet.

scp from Linux to Windows

Try this:

scp /home/ubuntu/myfile C:\users\Anshul\Desktop

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

SFTP file transfer using Java JSch

Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation

Transfer files to/from session I'm logged in with PuTTY

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (the pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY button.

See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.

See Opening PuTTY in the Same Directory.

(I'm the author of WinSCP)

rsync error: failed to set times on "/foo/bar": Operation not permitted

As @racl101 has commented on an answer, this problem might be related to the folder owner. The rsync command should be done by the same user as the folder owner's one. If it's not the same, you can change it.

chown -R userCorrect /remote/path/to/foo/bar

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

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

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

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

package filesendtest;

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

class TCPServer {

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

    public static void main(String args[]) {

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

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

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

                FileInputStream fis = null;

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

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

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

package filesendtest;

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

class TCPClient {

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

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

        Socket clientSocket = null;
        InputStream is = null;

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

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

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

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

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

Related

Byte array of unknown length in java

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

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

Comparing HTTP and FTP for transferring files

Many firewalls drop outbound connections which are not to ports 80 or 443 (http & https); some even drop connections to those ports that are not HTTP(S). FTP may or may not be allowed, not to speak of the active/PASV modes.

Also, HTTP/1.1 allows for much better partial requests ("only send from byte 123456 to the end of file"), conditional requests and caching ("only send if content changed/if last-modified-date changed") and content compression (gzip).

HTTP is much easier to use through a proxy.

From my anecdotal evidence, HTTP is easier to make work with dropped/slow/flaky connections; e.g. it is not needed to (re)establish a login session before (re)initiating transfer.

OTOH, HTTP is stateless, so you'd have to do authentication and building a trail of "who did what when" yourself.

The only difference in speed I've noticed is transferring lots of small files: HTTP with pipelining is faster (reduces round-trips, esp. noticeable on high-latency networks).

Note that HTTP/2 offers even more optimizations, whereas the FTP protocol has not seen any updates for decades (and even extensions to FTP have insignificant uptake by users). So, unless you are transferring files through a time machine, HTTP seems to have won.

(Tangentially: there are protocols that are better suited for file transfer, such as rsync or BitTorrent, but those don't have as much mindshare, whereas HTTP is Everywhere™)

What is the difference between exit and return?

  • return returns from the current function; it's a language keyword like for or break.
  • exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);. The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

Example with return:

#include <stdio.h>

void f(){
    printf("Executing f\n");
    return;
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f
Back from f

Another example for exit():

#include <stdio.h>
#include <stdlib.h>

void f(){
    printf("Executing f\n");
    exit(0);
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f

You never get "Back from f". Also notice the #include <stdlib.h> necessary to call the library function exit().

Also notice that the parameter of exit() is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).

The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.

Last point, exit() come in two flavors _exit() and exit(). The difference between the forms is that exit() (and return from main) calls functions registered using atexit() or on_exit() before really terminating the process while _exit() (from #include <unistd.h>, or its synonymous _Exit from #include <stdlib.h>) terminates the process immediately.

Now there are also issues that are specific to C++.

C++ performs much more work than C when it is exiting from functions (return-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

This won't happen if you are using the good old C FILE* streams. These will be flushed on exit(). Actually, the rule is the same that for registered exit functions, FILE* will be flushed on all normal terminations, which includes exit(), but not calls to _exit() or abort().

You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.

Destructors of static C++ objects (globals) will be called if you call either return from main() or exit() anywhere in your program. They wont be called if the program is terminated using _exit() or abort(). abort() is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert() macro only active in debug mode.

When is exit() useful ?

exit() means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).

Direct calls to exit() are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit() from a library is bad, it leads for instance people to ask this question.

There is an undisputed legitimate use of exit() as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.

CSS: Fix row height

HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.

Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp

.

SQL RANK() versus ROW_NUMBER()

ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.

Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.

How can I create a text box for a note in markdown?

The simplest solution I've found to the exact same problem is to use a multiple line table with one row and no header (there is an image in the first column and the text in the second):

----------------------- ------------------------------------
![Tip](images/tip.png)\ Table multiline text bla bla bla bla
                        bla bla bla bla bla bla bla ... the
                        blank line below is important 

----------------------------------------------------------------

Another approach that might work (for PDF) is to use Latex default fbox directive :

 \fbox{My text!}

Or FancyBox module for more advanced features (and better looking boxes) : http://www.ctan.org/tex-archive/macros/latex/contrib/fancybox.

Laravel - Form Input - Multiple select for a one to many relationship

My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating @foreach but now work with a double @foreach and double @if:

  <div class="form-group">
    <label for="tagLabel">Tags: </label>
    <select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
      @foreach($tags as $id => $name)
        @if (is_array(Request::old('tag_id')))
                <option value="{{ $id }}" 
                @foreach (Request::old('tag_id') as $idold)
                  @if($idold==$id)
                    selected
                  @endif 
                @endforeach
                style="padding:5px;">{{ $name }}</option>
        @else
          <option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
        @endif
      @endforeach
    </select>
  </div>

this is the code por jquery chosen (the blade.php code doesn´t need this code to work)

    $(".chosen-tag").chosen({
  placeholder_text_multiple: "Selecciona alguna etiqueta",
  no_results_text: "No hay resultados para la busqueda",
  search_contains: true,
  width: '500px'
});

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

Set attribute without value

The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )

Remove the last chars of the Java String variable

path = path.substring(0, path.length() - 5);

moment.js get current time in milliseconds?

From the docs: http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

So use either of these:


moment(...).valueOf()

to parse a preexisting date and convert the representation to a unix timestamp


moment().valueOf()

for the current unix timestamp

Read entire file in Scala?

print every line, like use Java BufferedReader read ervery line, and print it:

scala.io.Source.fromFile("test.txt" ).foreach{  print  }

equivalent:

scala.io.Source.fromFile("test.txt" ).foreach( x => print(x))

How to set gradle home while importing existing project in Android studio

This is my solution on AndroidStudio/Idea for Mac

$ env | grep GRADLE
GRADLE_HOME=/usr/local/Cellar/gradle/2.6
GRADLE_USER_HOME=/Users/leon/.gradle

Escape a string for a sed replace pattern

Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter)

Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn in to a backreference.

As Ben Blank said, there are only three characters that need to be escaped in the replacement string (escapes themselves, forward slash for end of statement and & for replace all):

ESCAPED_REPLACE=$(printf '%s\n' "$REPLACE" | sed -e 's/[\/&]/\\&/g')
# Now you can use ESCAPED_REPLACE in the original sed statement
sed "s/KEYWORD/$ESCAPED_REPLACE/g"

If you ever need to escape the KEYWORD string, the following is the one you need:

sed -e 's/[]\/$*.^[]/\\&/g'

And can be used by:

KEYWORD="The Keyword You Need";
ESCAPED_KEYWORD=$(printf '%s\n' "$KEYWORD" | sed -e 's/[]\/$*.^[]/\\&/g');

# Now you can use it inside the original sed statement to replace text
sed "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/g"

Remember, if you use a character other than / as delimiter, you need replace the slash in the expressions above wih the character you are using. See PeterJCLaw's comment for explanation.

Edited: Due to some corner cases previously not accounted for, the commands above have changed several times. Check the edit history for details.

Removing input background colour for Chrome autocomplete?

try this for hide autofill style

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:active,
input:-webkit-autofill:focus {
    background-color: #FFFFFF !important;
    color: #555 !important;
    -webkit-box-shadow: 0 0 0 1000px white inset !important;
    -webkit-text-fill-color: #555555 !important;
    }

How to Convert a Text File into a List in Python

Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)

How to print out all the elements of a List in Java?

For a list of array of String

list.forEach(s -> System.out.println(Arrays.toString((String[]) s )));

VBA test if cell is in a range

I don't work with contiguous ranges all the time. My solution for non-contiguous ranges is as follows (includes some code from other answers here):

Sub test_inters()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim inters As Range

    Set rng2 = Worksheets("Gen2").Range("K7")
    Set rng1 = ExcludeCell(Worksheets("Gen2").Range("K6:K8"), rng2)

    If (rng2.Parent.name = rng1.Parent.name) Then
        Dim ints As Range
        MsgBox rng1.Address & vbCrLf _
        & rng2.Address & vbCrLf _

        For Each cell In rng1
            MsgBox cell.Address
            Set ints = Application.Intersect(cell, rng2)
            If (Not (ints Is Nothing)) Then
                MsgBox "Yes intersection"
            Else
                MsgBox "No intersection"
            End If
        Next cell
    End If
End Sub

Hide HTML element by id

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

UIView bottom border?

You don't have to add a layer for each border, just use a bezier path to draw them once.

CGRect rect = self.bounds;

CGPoint destPoint[4] = {CGPointZero,
    (CGPoint){0, rect.size.height},
    (CGPoint){rect.size.width, rect.size.height},
    (CGPoint){rect.size.width, 0}};

BOOL position[4] = {_top, _left, _bottom, _right};

UIBezierPath *path = [UIBezierPath new];
[path moveToPoint:destPoint[3]];

for (int i = 0; i < 4; ++i) {
    if (position[i]) {
        [path addLineToPoint:destPoint[i]];
    } else {
        [path moveToPoint:destPoint[i]];
    }
}

CAShapeLayer *borderLayer = [CAShapeLayer new];
borderLayer.frame = self.bounds;
borderLayer.path  = path.CGPath;
borderLayer.lineWidth   = _borderWidth ?: 1 / [UIScreen mainScreen].scale;
borderLayer.strokeColor = _borderColor.CGColor;
borderLayer.fillColor   = [UIColor clearColor].CGColor;

[self.layer addSublayer:borderLayer];

Automatic confirmation of deletion in powershell

You just need to add a /A behind the line.

Example:

get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

converting date time to 24 hour format

This is a method that uses JODA.

Input example is 07/20/2015 01:46:34.436 AM

public static String get24HourFormat(String dateString){
        Date date = new Date();
        DateTime date1=new DateTime();

        //  String date="";
        int hour=0;
        //int year=0;
        if(dateString!=null){

            try {
                DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ss.SSS aa");
                DateTimeFormatter output = DateTimeFormat.forPattern("kk");

                date1=formatter.parseDateTime(dateString);
                hour=date1.getHourOfDay();
                System.out.println(output.print(date1));
                //  System.out.println(date);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return hour+"";
    }

Making a mocked method return an argument that was passed to it

I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:

public class RoomService {
    public Room findByName(String roomName) {...}
    public void persist(Room room) {...}
}

The service mock uses a map to store the Room instances.

RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();

// mock for method persist
doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            Room room = (Room) arguments[0];
            roomMap.put(room.getName(), room);
        }
        return null;
    }
}).when(roomService).persist(any(Room.class));

// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
    @Override
    public Room answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            String key = (String) arguments[0];
            if (roomMap.containsKey(key)) {
                return roomMap.get(key);
            }
        }
        return null;
    }
});

We can now run our tests on this mock. For example:

String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));

How to create a popup window (PopupWindow) in Android

I construct my own class, and then call it from my activity, overriding small methods like showAtLocation. I've found its easier when I have 4 to 5 popups in my activity to do this.

public class ToggleValues implements OnClickListener{

    private View pView;
    private LayoutInflater inflater;
    private PopupWindow pop;
    private Button one, two, three, four, five, six, seven, eight, nine, blank;
    private ImageButton eraser;
    private int selected = 1;
    private Animation appear;

    public ToggleValues(int id, Context c, int screenHeight){
        inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        pop = new PopupWindow(inflater.inflate(id, null, false), 265, (int)(screenHeight * 0.45), true);
        pop.setBackgroundDrawable(c.getResources().getDrawable(R.drawable.alpha_0));
        pView = pop.getContentView();

        appear = AnimationUtils.loadAnimation(c, R.anim.appear);

        one = (Button) pView.findViewById(R.id.one);
        one.setOnClickListener(this);
        two = (Button) pView.findViewById(R.id.two);
        two.setOnClickListener(this);
        three = (Button) pView.findViewById(R.id.three);
        three.setOnClickListener(this);
        four = (Button) pView.findViewById(R.id.four);
        four.setOnClickListener(this);
        five = (Button) pView.findViewById(R.id.five);
        five.setOnClickListener(this);
        six = (Button) pView.findViewById(R.id.six);
        six.setOnClickListener(this);
        seven = (Button) pView.findViewById(R.id.seven);
        seven.setOnClickListener(this);
        eight = (Button) pView.findViewById(R.id.eight);
        eight.setOnClickListener(this);
        nine = (Button) pView.findViewById(R.id.nine);
        nine.setOnClickListener(this);
        blank = (Button) pView.findViewById(R.id.blank_Selection);
        blank.setOnClickListener(this);
        eraser = (ImageButton) pView.findViewById(R.id.eraser);
        eraser.setOnClickListener(this);
    }

    public void showAtLocation(View v) {
        pop.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, 40, 40);
        pView.startAnimation(appear);
    }

    public void dismiss(){ 
        pop.dismiss();
    }

    public boolean isShowing() {
        if(pop.isShowing()){
            return true;
        }else{
            return false;
        }
    }

    public int getSelected(){
        return selected;
    }

    public void onClick(View arg0) {
        if(arg0 == one){
            Sudo.setToggleNum(1);
        }else if(arg0 == two){
            Sudo.setToggleNum(2);
        }else if(arg0 == three){
            Sudo.setToggleNum(3);
        }else if(arg0 == four){
            Sudo.setToggleNum(4);
        }else if(arg0 == five){
            Sudo.setToggleNum(5);
        }else if(arg0 == six){
            Sudo.setToggleNum(6);
        }else if(arg0 == seven){
            Sudo.setToggleNum(7);
        }else if(arg0 == eight){
            Sudo.setToggleNum(8);
        }else if(arg0 == nine){
            Sudo.setToggleNum(9);
        }else if(arg0 == blank){
            Sudo.setToggleNum(0);
        }else if(arg0 == eraser){
            Sudo.setToggleNum(-1);
        }
        this.dismiss();
    }

}

Animate change of view background color on Android

You can use ArgbEvaluatorCompat class above API 11.

implementation 'com.google.android.material:material:1.0.0' 


ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mTargetColor = (int) animation.getAnimatedValue();
        }
    });
colorAnim.start();

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

How to select an option from drop down using Selenium WebDriver C#?

Other way could be this one:

driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();

and you can change the index in option[x] changing x by the number of element that you want to select.

I don't know if it is the best way but I hope that help you.

Import CSV file into SQL Server

May be SSMS: How to import (Copy/Paste) data from excel can help (If you don't want to use BULK INSERT or don't have permissions for it).

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

As others have suggested, the best way to do this is to use a join instead of variable assignment. Re-writing your query to use a join (and using the explicit join syntax instead of the implicit join, which was also suggested--and is the best practice), you would get something like this:

select  
  OrderDetails.Sku,
  OrderDetails.mf_item_number,
  OrderDetails.Qty,
  OrderDetails.Price,
  Supplier.SupplierId, 
  Supplier.SupplierName,
  Supplier.DropShipFees, 
  Supplier_Item.Price as cost
from 
  OrderDetails
join Supplier on OrderDetails.Mfr_ID = Supplier.SupplierId
join Group_Master on Group_Master.Sku = OrderDetails.Sku 
join Supplier_Item on 
  Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID 
where 
  invoiceid='339740' 

Abstract methods in Python

You have to implement an abstract base class (ABC).

Check python docs

How to tell if a connection is dead in python

If I'm not mistaken this is usually handled via a timeout.

How do I auto-submit an upload form when a file is selected?

HTML

<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>

JAVASCRIPT PURE

<script type="text/javascript">
window.onload = function() {
    document.getElementById("xfilename").onchange = function() {
        document.getElementById("xtarget").submit();
    }
};
</script>

Android: How to create a Dialog without a title?

olivierg's answer worked for me and is the best solution if creating a custom Dialog class is the route you want to go. However, it bothered me that I couldn't use the AlertDialog class. I wanted to be able to use the default system AlertDialog style. Creating a custom dialog class would not have this style.

So I found a solution (hack) that will work without having to create a custom class, you can use the existing builders.

The AlertDialog puts a View above your content view as a placeholder for the title. If you find the view and set the height to 0, the space goes away.

I have tested this on 2.3 and 3.0 so far, it is possible it doesn't work on every version yet.

Here are two helper methods for doing it:

/**
 * Show a Dialog with the extra title/top padding collapsed.
 * 
 * @param customView The custom view that you added to the dialog
 * @param dialog The dialog to display without top spacing
     * @param show Whether or not to call dialog.show() at the end.
 */
public static void showDialogWithNoTopSpace(final View customView, final Dialog dialog, boolean show) {
    // Now we setup a listener to detect as soon as the dialog has shown.
    customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Check if your view has been laid out yet
            if (customView.getHeight() > 0) {
                // If it has been, we will search the view hierarchy for the view that is responsible for the extra space. 
                LinearLayout dialogLayout = findDialogLinearLayout(customView);
                if (dialogLayout == null) {
                    // Could find it. Unexpected.

                } else {
                    // Found it, now remove the height of the title area
                    View child = dialogLayout.getChildAt(0);
                    if (child != customView) {
                        // remove height
                        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
                        lp.height = 0;
                        child.setLayoutParams(lp);

                    } else {
                        // Could find it. Unexpected.
                    }
                }

                // Done with the listener
                customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
         }

    });

    // Show the dialog
    if (show)
             dialog.show();
}

/**
 * Searches parents for a LinearLayout
 * 
 * @param view to search the search from
 * @return the first parent view that is a LinearLayout or null if none was found
 */
public static LinearLayout findDialogLinearLayout(View view) {
    ViewParent parent = (ViewParent) view.getParent();
    if (parent != null) {
        if (parent instanceof LinearLayout) {
            // Found it
            return (LinearLayout) parent;

        } else if (parent instanceof View) {
            // Keep looking
            return findDialogLinearLayout((View) parent);

        }
    }

    // Couldn't find it
    return null;
}

Here is an example of how it is used:

    Dialog dialog = new AlertDialog.Builder(this)
        .setView(yourCustomView)
        .create();

    showDialogWithNoTopSpace(yourCustomView, dialog, true);

If you are using this with a DialogFragment, override the DialogFragment's onCreateDialog method. Then create and return your dialog like the first example above. The only change is that you should pass false as the 3rd parameter (show) so that it doesn't call show() on the dialog. The DialogFragment will handle that later.

Example:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new AlertDialog.Builder(getContext())
        .setView(yourCustomView)
        .create();

    showDialogWithNoTopSpace(yourCustomView, dialog, false);
    return dialog;
}

As I test this further I'll be sure to update with any additional tweaks needed.

linux: kill background task

This should kill all background processes:

jobs -p | xargs kill -9

How to calculate DATE Difference in PostgreSQL?

a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.

if you want real difference

select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);

if you want absolute difference

select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));

Vlookup referring to table data in a different sheet

I have faced similar problem and it was returning #N/A. That means matching data is present but you might having extra space in the M3 column record, that may prevent it from getting exact value. Because you have set last parameter as FALSE, it is looking for "exact match". This formula is correct: =VLOOKUP(M3,Sheet1!$A$2:$Q$47,13,FALSE)

Which exception should I raise on bad/illegal argument combinations in Python?

I've mostly just seen the builtin ValueError used in this situation.

How to create PDF files in Python

It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.

Add space between cells (td) using css

Suppose cellspcing / cellpadding / border-spacing property did not worked, you can use the code as follow.

<div class="form-group">
  <table width="100%" cellspacing="2px" style="border-spacing: 10px;">
    <tr>                        
      <td width="47%">
        <input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
      </td>
      <td width="5%"></td>
      <td width="47%">
        <input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
      </td>
    </tr>
  </table>
</div>

I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.

PYTHONPATH vs. sys.path

In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.

Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

Since the question was first asked, there has been a change to that answer from a flat out "no" to a "kind of"

http://github.com/facebook/hiphop-php/wiki

Hip Hop for PHP was a compiler that took PHP code and turned it into highly optimized C++ Apparently, some functions are not supported (for example 'explode')

I found this question while looking for more information on how to implement HipHop and thought I'd speak up :)

Since 2013 Facebook no longer use it, however, and it has been discontinued in favour of HHVM, which is not a compiler: https://en.wikipedia.org/wiki/HipHop_for_PHP

Struct inheritance in C++

In C++, a structure's inheritance is the same as a class except the following differences:

When deriving a struct from a class/struct, the default access-specifier for a base class/struct is public. And when deriving a class, the default access specifier is private.

For example, program 1 fails with a compilation error and program 2 works fine.

// Program 1
#include <stdio.h>

class Base {
    public:
        int x;
};

class Derived : Base { }; // Is equivalent to class Derived : private Base {}

int main()
{
    Derived d;
    d.x = 20; // Compiler error because inheritance is private
    getchar();
    return 0;
}

// Program 2
#include <stdio.h>

struct Base {
    public:
        int x;
};

struct Derived : Base { }; // Is equivalent to struct Derived : public Base {}

int main()
{
    Derived d;
    d.x = 20; // Works fine because inheritance is public
    getchar();
    return 0;
}

How can I replace non-printable Unicode characters in Java?

I have used this simple function for this:

private static Pattern pattern = Pattern.compile("[^ -~]");
private static String cleanTheText(String text) {
    Matcher matcher = pattern.matcher(text);
    if ( matcher.find() ) {
        text = text.replace(matcher.group(0), "");
    }
    return text;
}

Hope this is useful.

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

change the date format in laravel view page

Try this:

date('d-m-Y', strtotime($user->from_date));

It will convert date into d-m-Y or whatever format you have given.

Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.

Using the "start" command with parameters passed to the started program

Instead of a batch file, you can create a shortcut on the desktop.

Set the target to:

"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch

and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box.

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Why are LEFT/RIGHT and LEFT OUTER/RIGHT OUTER the same? Let's explain why this vocabulary. Understand that LEFT and RIGHT joins are specific cases of the OUTER join, and therefore couldn't be anything else than OUTER LEFT/OUTER RIGHT. The OUTER join is also called FULL OUTER as opposed to LEFT and RIGHT joins that are PARTIAL results of the OUTER join. Indeed:

Table A | Table B     Table A | Table B      Table A | Table B      Table A | Table B
   1    |   5            1    |   1             1    |   1             1    |   1
   2    |   1            2    |   2             2    |   2             2    |   2
   3    |   6            3    |  null           3    |  null           -    |   -
   4    |   2            4    |  null           4    |  null           -    |   -
                        null  |   5             -    |   -            null  |   5
                        null  |   6             -    |   -            null  |   6

                      OUTER JOIN (FULL)     LEFT OUTER (partial)   RIGHT OUTER (partial)

It is now clear why those operations have aliases, as well as it is clear only 3 cases exist: INNER, OUTER, CROSS. With two sub-cases for the OUTER. The vocabulary, the way teachers explain this, as well as some answers above, often make it looks like there are lots of different types of join. But it's actually very simple.

How can I select all options of multi-select select box on click?

try

$('#select_all').click( function() {
    $('#countries option').each(function(){
        $(this).attr('selected', 'selected');
    });
});

this will give you more scope in the future to write things like

$('#select_all').click( function() {
    $('#countries option').each(function(){
        if($(this).attr('something') != 'omit parameter')
        {
            $(this).attr('selected', 'selected');
        }
    });
});

Basically allows for you to do a select all EU members or something if required later down the line

Is there a way to disable initial sorting for jquery DataTables?

In datatable options put this:

$(document).ready( function() {
  $('#example').dataTable({
    "aaSorting": [[ 2, 'asc' ]], 
    //More options ...

   });
})

Here is the solution: "aaSorting": [[ 2, 'asc' ]],

2 means table will be sorted by third column,
asc in ascending order.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

Most pythonic way to delete a file which may not exist

A more pythonic way would be:

try:
    os.remove(filename)
except OSError:
    pass

Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions.

It may be worthwhile to write a function to do this for you:

import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occurred

Error Code: 1406. Data too long for column - MySQL

This happened to me recently. I was fully migrate to MySQL 5.7, and everything is in default configuration.

All previously answers are already clear and I just want to add something.

This 1406 error could happen in your function / procedure too and not only to your table's column length.

In my case, I've trigger which call procedure with IN parameter varchar(16) but received 32 length value.

I hope this help someone with similar problem.

CSS: how do I create a gap between rows in a table?

This is the way (I was thinking it's impossible):

First give the table only vertical border-spacing (for example 5px) and set it's horizontal border-spacing to 0. Then you should give proper borders to each row cell. For example the right-most cell in each row should have border on top, bottom and right. The left-most cells should have border on top, bottom and left. And the other cells between these 2 should only have border on top and bottom. Like this example:

<table style="border-spacing:0 5px; color:black">
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
</table>

How to make modal dialog in WPF?

A lot of these answers are simplistic, and if someone is beginning WPF, they may not know all of the "ins-and-outs", as it is more complicated than just telling someone "Use .ShowDialog()!". But that is the method (not .Show()) that you want to use in order to block use of the underlying window and to keep the code from continuing until the modal window is closed.

First, you need 2 WPF windows. (One will be calling the other.)

From the first window, let's say that was called MainWindow.xaml, in its code-behind will be:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Then add your button to your XAML:

<Button Name="btnOpenModal" Click="btnOpenModal_Click" Content="Open Modal" />

And right-click the Click routine, select "Go to definition". It will create it for you in MainWindow.xaml.cs:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
}

Within that function, you have to specify the other page using its page class. Say you named that other page "ModalWindow", so that becomes its page class and is how you would instantiate (call) it:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
    ModalWindow modalWindow = new ModalWindow();
    modalWindow.ShowDialog();
}

Say you have a value you need set on your modal dialog. Create a textbox and a button in the ModalWindow XAML:

<StackPanel Orientation="Horizontal">
    <TextBox Name="txtSomeBox" />
    <Button Name="btnSaveData" Click="btnSaveData_Click" Content="Save" /> 
</StackPanel>

Then create an event handler (another Click event) again and use it to save the textbox value to a public static variable on ModalWindow and call this.Close().

public partial class ModalWindow : Window
{
    public static string myValue = String.Empty;        
    public ModalWindow()
    {
        InitializeComponent();
    }

    private void btnSaveData_Click(object sender, RoutedEventArgs e)
    {
        myValue = txtSomeBox.Text;
        this.Close();
    }
}

Then, after your .ShowDialog() statement, you can grab that value and use it:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
    ModalWindow modalWindow = new ModalWindow();
    modalWindow.ShowDialog();

    string valueFromModalTextBox = ModalWindow.myValue;
}

Concatenate String in String Objective-c

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:

@"first" @"second"

And it will result in:

@"firstsecond"

You can not use it with NSString objects, only with literals, but it can be useful in some cases.

Intent from Fragment to Activity

For Kotlin you can use

val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)

Android SDK manager won't open

I recently faced this problem after I installed android emulator using the sdk manager of android studio - which also upgraded my android sdk tools to 26.0.1 (as it was a prerequisite - according to the sdk manager of android studio).

In my case, I simply replaced the tools folder of android sdk with tools folder from an older android sdk. This downgraded the android sdk tools, but now I can open the sdk manager using SDK Manager.exe.

How to Delete Session Cookie?

This needs to be done on the server-side, where the cookie was issued.

Publish to IIS, setting Environment Variable

I have modified the answer which @Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.

  1. First, create appsettings.json file in root directory. with the content

      {
         // Possible string values reported below. When empty it use ENV 
            variable value or Visual Studio setting.
         // - Production
         // - Staging
         // - Test
        // - Development
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
    
  2. Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.

  3. Add necessary code to set up the environment to Program.cs file.

    public class Program
    {
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    
      ***var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
    
        try
        {
            ***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of setup related exception");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }
    
    public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog()
            ***.UseEnvironment(enviromentValue);***
    

    }

  4. Add the envsettings.json to your .csproj file for copy to published directory.

       <ItemGroup>
            <None Include="envsettings.json" CopyToPublishDirectory="Always" />
        </ItemGroup>
    
  5. Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

Altering user-defined table types in SQL Server

you cant ALTER/MODIFY your TYPE. You have to drop the existing and re-create it with correct name/datatype or add a new column/s

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Missing XML comment for publicly visible type or member

Jon Skeet's answer works great for when you're building with VisualStudio. However, if you're building the sln via the command line (in my case it was via Ant) then you may find that msbuild ignores the sln supression requests.

Adding this to the msbuild command line solved the problem for me:

/p:NoWarn=1591

Confirmation dialog on ng-click - AngularJS

I created a module for this very thing that relies on the Angular-UI $modal service.

https://github.com/Schlogen/angular-confirm

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How to stop default link click behavior with jQuery

e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable, without stopping further propagation of the event.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

How can I get Eclipse to show .* files?

If you're using Eclipse PDT, this is done by opening up the PHP explorer view, then clicking the upside-down triangle in the top-right of that window. A context window appears, and the filters option is available there. Clicking the Filters menu option opens a new window, where .* files can be unchecked, thus allowing the editing of .htaccess files.

I searched forever for this, so I'm sorta answering my own question here. I'm sure someone else will have the same problem too, so I hope this helps someone else as well.

Fast Linux file count for a large number of files

I realized that not using in memory processing, when you have a huge amount of data, is faster than "piping" the commands. So I saved the result to a file and analyzed it afterwards:

ls -1 /path/to/dir > count.txt && cat count.txt | wc -l

How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

  1. Have your media files stored in one single git repository, which is used by many projects
  2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

  1. create a repository for the media files and one for each project
  2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

  1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

  2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

  1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

  2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media

If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master

You are free to remove these commits later (with git reset) because you haven't shared them with other users.

How to debug stored procedures with print statements?

Here is an example of print statement use. They should appear under the messages tab as a previous person indicated.

    Declare @TestVar int = 5;

    print 'this is a test message';
    print @TestVar;
    print 'test-' + Convert(varchar(50), @TestVar);

Print Messages

How do I check if a list is empty?

if not a:
  print("List is empty")

Using the implicit booleanness of the empty list is quite pythonic.

Compare two Lists for differences

This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.

http://msdn.microsoft.com/en-us/library/bb397894.aspx

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

Can't push to the heroku

You could also select webpack build manually from the UI enter image description here

How to get distinct results in hibernate with joins and row-based limiting (paging)?

You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.

Simply add this to your criteria:

criteria.setProjection(Projections.distinct(Projections.property("id")));

Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check as part of the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness after the sql query has been performed.

Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.

How to test valid UUID/GUID?

If you are using Node.js for development, it is recommended to use a package called Validator. It includes all the regexes required to validate different versions of UUID's plus you get various other functions for validation.

Here is the npm link: Validator

var a = 'd3aa88e2-c754-41e0-8ba6-4198a34aa0a2'
v.isUUID(a)
true
v.isUUID('abc')
false
v.isNull(a)
false

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

sh: react-scripts: command not found after running npm start

You shoundt use neither SPACES neither some Special Caracters in you path, like for example using "&". I my case I was using this path: "D:\P&D\mern" and because of this "&" I lost 50 minutes trying to solve the problem! :/

Living and Learning!

PowerShell: Create Local User Account

Try using Carbon's Install-User and Add-GroupMember functions:

Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'

Disclaimer: I am the creator/maintainer of the Carbon project.

C# - Multiple generic types in one list

I have also used a non-generic version, using the new keyword:

public interface IMetadata
{
    Type DataType { get; }

    object Data { get; }
}

public interface IMetadata<TData> : IMetadata
{
    new TData Data { get; }
}

Explicit interface implementation is used to allow both Data members:

public class Metadata<TData> : IMetadata<TData>
{
    public Metadata(TData data)
    {
       Data = data;
    }

    public Type DataType
    {
        get { return typeof(TData); }
    }

    object IMetadata.Data
    {
        get { return Data; }
    }

    public TData Data { get; private set; }
}

You could derive a version targeting value types:

public interface IValueTypeMetadata : IMetadata
{

}

public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{

}

public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
    public ValueTypeMetadata(TData data) : base(data)
    {}
}

This can be extended to any kind of generic constraints.

How to create a zip archive of a directory in Python?

Well, after reading the suggestions I came up with a very similar way that works with 2.7.x without creating "funny" directory names (absolute-like names), and will only create the specified folder inside the zip.

Or just in case you needed your zip to contain a folder inside with the contents of the selected directory.

def zipDir( path, ziph ) :
 """
 Inserts directory (path) into zipfile instance (ziph)
 """
 for root, dirs, files in os.walk( path ) :
  for file in files :
   ziph.write( os.path.join( root, file ) , os.path.basename( os.path.normpath( path ) ) + "\\" + file )

def makeZip( pathToFolder ) :
 """
 Creates a zip file with the specified folder
 """
 zipf = zipfile.ZipFile( pathToFolder + 'file.zip', 'w', zipfile.ZIP_DEFLATED )
 zipDir( pathToFolder, zipf )
 zipf.close()
 print( "Zip file saved to: " + pathToFolder)

makeZip( "c:\\path\\to\\folder\\to\\insert\\into\\zipfile" )

div inside php echo

Just wrap it around then.

<?php        
    if ( ($cart->count_product) > 0) 
    { 
        echo "<div class='my_class'>";
        print $cart->count_product; 
        echo "</div>";
    }

?>

Passing arguments to AsyncTask, and returning results

I sort of agree with leander on this one.

call:

new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));

task:

public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
        @Override
        protected ArrayList<String> doInBackground(String... args) {
           ...
        }

        @Override
        protected void onPostExecute(ArrayList<String> result) {
           ... //do something with the result list here
        }
}

Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);

public class calc_stanica extends AsyncTask<String, Void, Boolean> {
        private List<String> resultList;

        @Override
        protected boolean doInBackground(String... args) {
           ...
        }

        @Override
        protected void onPostExecute(boolean success) {
           ... //if successfull, do something with the result list here
        }
}

Moment.js with Vuejs

I'd simply import the moment module, then use a computed function to handle my moment() logic and return a value that's referenced in the template.

While I have not used this and thus can not speak on it's effectiveness, I did find https://github.com/brockpetrie/vue-moment for an alternate consideration

Getting data-* attribute for onclick event for an html element

Check if the data attribute is present, then do the stuff...

$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
                        if(e.target.getAttribute('data-title')) {
                            var careerTitle = $(this).attr('data-title');
                            if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
                        }
                });

Open a Web Page in a Windows Batch FIle

hh.exe (help pages renderer) is capable of opening some simple webpages:

hh http://www.nissan.com

This will work even if browsing is blocked through:

HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer

W3WP.EXE using 100% CPU - where to start?

  1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
  2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
  3. Load testing, using tools such as Visual Studio Team Test or WCAT
  4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
  5. Use logparser to see which requests arrived at the time of the CPU spike
  6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
  7. CPU and memory profiling (can be difficult on a production system)
  8. Process Explorer
  9. Windows Resource Monitor
  10. Detailed error logging
  11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
  12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Passing array in GET for a REST call

Another way of doing that, which can make sense depending on your server architecture/framework of choice, is to repeat the same argument over and over again. Something like this:

/appointments?users=id1&users=id2

In this case I recommend using the parameter name in singular:

/appointments?user=id1&user=id2

This is supported natively by frameworks such as Jersey (for Java). Take a look on this question for more details.

Default value to a parameter while passing by reference in C++

This little template will help you:

template<typename T> class ByRef {
public:
    ByRef() {
    }

    ByRef(const T value) : mValue(value) {
    }

    operator T&() const {
        return((T&)mValue);
    }

private:
    T mValue;
};

Then you'll be able to:

virtual const ULONG Write(ULONG &State = ByRef<ULONG>(0), bool sequence = true);

How to increase Maximum Upload size in cPanel?

The solution is to create the php.ini file under your root directory. If the site is the wordpress installation then create the php.ini under your/path/to/wordpress/wp-admin/php.ini and add the following line of codes

[PHP]
post_max_size=120M
upload_max_filesize=132M

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

This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example

class Dojo implements Sensei {
     console.log('Hi'); // ERROR Identifier expected.
     constructor(){}
}

Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

Modify a Column's Type in sqlite3

It is possible by recreating table.Its work for me please follow following step:

  1. create temporary table using as select * from your table
  2. drop your table, create your table using modify column type
  3. now insert records from temp table to your newly created table
  4. drop temporary table

do all above steps in worker thread to reduce load on uithread

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

Get encoding of a file in Windows

Install git ( on Windows you have to use git bash console). Type:

file *   

for all files in the current directory , or

file */*   

for the files in all subdirectories

Create two-dimensional arrays and access sub-arrays in Ruby

Here's a 3D array case

class Array3D
   def initialize(d1,d2,d3)
    @data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
   end

  def [](x, y, z)
    @data[x][y][z]
  end

  def []=(x, y, z, value)
    @data[x][y][z] = value
  end
end

You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc

How to comment out a block of code in Python

Hide the triple quotes in a context that won't be mistaken for a docstring, eg:

'''
...statements...
''' and None

or:

if False: '''
...statements...
'''

Reset the Value of a Select Box

This works for me:

$('select').prop('selectedIndex', 0);

FIDDLE

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Convert a string representation of a hex dump to a byte array using Java?

Actually, I think the BigInteger is solution is very nice:

new BigInteger("00A0BF", 16).toByteArray();

Edit: Not safe for leading zeros, as noted by the poster.

How to update primary key

You shouldn't really do this but insert in a new record instead and update it that way.
But, if you really need to, you can do the following:

  • Disable enforcing FK constraints temporarily (e.g. ALTER TABLE foo WITH NOCHECK CONSTRAINT ALL)
  • Then update your PK
  • Then update your FKs to match the PK change
  • Finally enable back enforcing FK constraints

How to get just the parent directory name of a specific file

Use below,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();

Dump a mysql database to a plaintext (CSV) backup from the command line

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command. With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

How do I configure Maven for offline development?

Before going offline you have to make sure that everything is in your local repo, which is required while working offline. Running "mvn dependency:go-offline" for the project(s)/pom(s), you intend to work on, will reduce the efforts to achieve this.

But it´s usually not the whole story, because dependency:go-offline will only download the "bare build" plugins (go-offline / resolve-plugins does not resolve all plugin dependencies). So you have to find a way to download deploy / test / site plugins (and maybe others) and their dependencies into your repo.

Furthermore dependency:go-offline does not download the pom´s artifact itself, so you have to dependency:copy it if required.

Sometimes - as MaDa wrote - you do not know, what you will need, while being offline, which makes it pretty impossible to have a "sufficient" repo.

Anyway having a properly filled repo you only have to add "<offline>true</offline>" to Maven´s settings.xml to go offline.

Do not change the Maven profile (id) you used to fill your repo, while being offline. Maven recognizes the downloaded artifacts in its metadata with an "identity", which is bound to the profile id.

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

PHP checkbox set to check based on database value

You can read database value in to a variable and then set the variable as follows

$app_container->assign('checked_flag', $db_data=='0'  ? '' : 'checked');

And in html you can just use the checked_flag variable as follows

<input type="checkbox" id="chk_test" name="chk_test" value="1" {checked_flag}>

Search in all files in a project in Sublime Text 3

Here's the easiest way : File -> Find in files

enter image description here

How do I use an image as a submit button?

<form id='formName' name='formName' onsubmit='redirect();return false;'>
        <div class="style7">
    <input type='text' id='userInput' name='userInput' value=''>
    <img src="BUTTON1.JPG" onclick="document.forms['formName'].submit();">
</div>
</form>

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

Table variable error: Must declare the scalar variable "@temp"

A table alias cannot start with a @. So, give @Temp another alias (or leave out the two-part naming altogether):

SELECT *
FROM @TEMP t
WHERE t.ID = 1;

Also, a single equals sign is traditionally used in SQL for a comparison.

How to copy file from HDFS to the local file system

In order to copy files from HDFS to the local file system the following command could be run:

hadoop dfs -copyToLocal <input> <output>

  • <input>: the HDFS directory path (e.g /mydata) that you want to copy
  • <output>: the destination directory path (e.g. ~/Documents)

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

Sending E-mail using C#

I can strongly recommend the aspNetEmail library: http://www.aspnetemail.com/

The System.Net.Mail will get you somewhere if your needs are only basic, but if you run into trouble, please check out aspNetEmail. It has saved me a bunch of time, and I know of other develoeprs who also swear by it!

How can I do factory reset using adb in android?

I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)

Here is steps:

# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache 
# reboot device
fastboot reboot

Using Spring 3 autowire in a standalone Java application

Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:

@Component
public class Main {

    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");

        Main p = context.getBean(Main.class);
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire the dependencies (which causes the NullPointerException).

In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring.

Send HTML in email via PHP

Simplest way is probably to just use Zend Framework or any of the other frameworks like CakePHP or Symphony.

You can do it with the standard mail function too, but you'll need a bit more knowledge on how to attach pictures.

Alternatively, just host the images on a server instead of attaching them. Sending HTML mail is documented in the mail function documentation.

How Many Seconds Between Two Dates?

In bash:

bc <<< "$(date --date='1 week ago' +%s) - \
    $(date --date='Sun,  29 Feb 2004 16:21:42 -0800' +%s)"

It does require having bc and gnu date installed.

How do I replace text in a selection?

I know this has been answered many times, and all are correct, but I though I would add another:

Similar to the Ctrl - D method to select individual occurrences of the current selection, you can select all occurrences in the file with Alt+F3 when using Windows or Linux (CMD+CTRL+G in Mac world).

This is helpful for mass-changes.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Finally, I got a solution!

My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.

so I use android.os.Process.killProcess(android.os.Process.myPid()); its kill my activity and i used android:excludeFromRecents="true" for remove from recent activity .

How does collections.defaultdict work?

The behavior of defaultdict can be easily mimicked using dict.setdefault instead of d[key] in every call.

In other words, the code:

from collections import defaultdict

d = defaultdict(list)

print(d['key'])                        # empty list []
d['key'].append(1)                     # adding constant 1 to the list
print(d['key'])                        # list containing the constant [1]

is equivalent to:

d = dict()

print(d.setdefault('key', list()))     # empty list []
d.setdefault('key', list()).append(1)  # adding constant 1 to the list
print(d.setdefault('key', list()))     # list containing the constant [1]

The only difference is that, using defaultdict, the list constructor is called only once, and using dict.setdefault the list constructor is called more often (but the code may be rewriten to avoid this, if really needed).

Some may argue there is a performance consideration, but this topic is a minefield. This post shows there isn't a big performance gain in using defaultdict, for example.

IMO, defaultdict is a collection that adds more confusion than benefits to the code. Useless for me, but others may think different.

How to remove text from a string?

This doesn't have anything to do with jQuery. You can use the JavaScript replace function for this:

var str = "data-123";
str = str.replace("data-", "");

You can also pass a regex to this function. In the following example, it would replace everything except numerics:

str = str.replace(/[^0-9\.]+/g, "");

How to apply filters to *ngFor?

Ideally you should create angualr 2 pipe for that. But you can do this trick.

<ng-container *ngFor="item in itemsList">
    <div*ngIf="conditon(item)">{{item}}</div>
</ng-container>

How can I read a text file from the SD card in Android?

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

How can I search for a multiline pattern in a file?

perl -ne 'print if (/begin pattern/../end pattern/)' filename

PHP Call to undefined function

Many times the problem comes because php does not support short open tags in php.ini file, i.e:

<?
   phpinfo();
?>

You must use:

<?php
   phpinfo();
?>

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

I can't install python-ldap

To install python-ldap successfully with pip, following development libraries are needed (package names taken from ubuntu environment):

sudo apt-get install -y python-dev libldap2-dev libsasl2-dev libssl-dev

Click toggle with jQuery

try changing this:

$(this).find(':checkbox').attr('checked', true ); 

to this:

$(this).find(':checkbox').attr('checked', 'checked'); 

Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck!

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I tried everything suggested on here and many other sites, I eventually figured out that the problem was with Bitdefender blocking aapt....

If you have Bitdefender installed then you need to turn aapt & aapt2 "Application Access" on individually.

Hope this is of use.

Expand a div to fill the remaining width

Here, this might help...

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    div.box {_x000D_
      background: #EEE;_x000D_
      height: 100px;_x000D_
      width: 500px;_x000D_
    }_x000D_
    div.left {_x000D_
      background: #999;_x000D_
      float: left;_x000D_
      height: 100%;_x000D_
      width: auto;_x000D_
    }_x000D_
    div.right {_x000D_
      background: #666;_x000D_
      height: 100%;_x000D_
    }_x000D_
    div.clear {_x000D_
      clear: both;_x000D_
      height: 1px;_x000D_
      overflow: hidden;_x000D_
      font-size: 0pt;_x000D_
      margin-top: -1px;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="box">_x000D_
    <div class="left">Tree</div>_x000D_
    <div class="right">View</div>_x000D_
    <div class="clear" />_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Splitting a continuous variable into equal sized groups

try this:

split(das, cut(das$anim, 3))

if you want to split based on the value of wt, then

library(Hmisc) # cut2
split(das, cut2(das$wt, g=3))

anyway, you can do that by combining cut, cut2 and split.

UPDATED

if you want a group index as an additional column, then

das$group <- cut(das$anim, 3)

if the column should be index like 1, 2, ..., then

das$group <- as.numeric(cut(das$anim, 3))

UPDATED AGAIN

try this:

> das$wt2 <- as.numeric(cut2(das$wt, g=3))
> das
   anim    wt wt2
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   3
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

As Raghuveer points out in his/her answer, ni is the PowerShell alias for New-Item, so you can create files from a PowerShell prompt using ni instead of touch.

If you prefer to type touch instead of ni, you can set a touch alias to the PowerShell New-Item cmdlet.

Creating a touch command in Windows PowerShell:

From a PowerShell prompt, define the new alias.

Set-Alias -Name touch -Value New-Item

Now the touch command works almost the same as you are expecting. The only difference is that you'll need to separate your list of files with commas.

touch index.html, app.js, style.css

Note that this only sets the alias for PowerShell. If PowerShell isn't your thing, you can set up WSL or use bash for Windows.

Unfortunately the alias will be forgotten as soon as you end your PowerShell session. To make the alias permanent, you have to add it to your PowerShell user profile.

From a PowerShell prompt:

notepad $profile

Add your alias definition to your profile and save.

Multiple argument IF statement - T-SQL

You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)

DECLARE @StartDate AS DATETIME

DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        print 'yoyoyo'
    END

IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2) 
    BEGIN
        print 'Oh hey there'
    END

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

h3 is absolutly a better solution than h2, h1 or h6 !

  1. You have to use specific level : if you're in a h1, use h2, if you're in a h5, use h6 (if you're in a h6... hum, use strong or em for exemple). It not a obligation but a question of accessibility (Here, green part).

  2. You don't have to give title to list... because this element it doesn't exist. So screen reader will not use something special.

Therefore, using Hn is probably one of the best solution, but surely not a specific level.

What is a regex to match ONLY an empty string?

Based on the most-approved answer, here is yet another way:

var result = !/[\d\D]/.test(string);  //[\d\D] will match any character

How to get user name using Windows authentication in asp.net?

It depends on the configuration of the application as well as on IIS as this gentleman in the below link has rightfully explained. Please see his article below

http://richhewlett.com/2011/02/15/getting-a-users-username-in-asp-net/

Git's famous "ERROR: Permission to .git denied to user"

If problem is coming on windows then remove the Credentials from the Windows history.

  • Go to Credential Manager
  • Go to Windows Credentials
  • Delete the entries under Generic Credentials
  • Try connecting again.This time , it should prompt you for the correct username and password.

enter image description here enter image description here

remove credentials from git

how to place last div into right top corner of parent div? (css)

_x000D_
_x000D_
.block1 {_x000D_
    color: red;_x000D_
    width: 100px;_x000D_
    border: 1px solid green;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
    color: blue;_x000D_
    width: 70px;_x000D_
    border: 2px solid black;_x000D_
    position: absolute;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
  <p>text</p>_x000D_
  <p>text2</p>_x000D_
  <div class='block2'>block2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should do it. Assuming you don't need it to flow.

How do I use a custom Serializer with Jackson?

You have to override method handledType and everything will work

@Override
public Class<Item> handledType()
{
  return Item.class;
}

Android Stop Emulator from Command Line

I can close it with:

adb shell reboot -p

Gradle store on local file system

For my case, I was using an Ivy repository, and my Gradle dependencies were stored in ~/.ivy2/.

Select Specific Columns from Spark DataFrame

i liked dehasis approach, because it allowed me to select, rename and convert columns in one step. However I had to adjust it to make it work for me in PySpark:

from pyspark.sql.functions import col

spark.read.csv(path).select(
      col('_c0').alias("stn").cast('String'),
      col('_c1').alias("wban").cast('String'),
      col('_c2').alias("lat").cast('Double'),
      col('_c3').alias("lon").cast('Double')
    )
      .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

How to check if the request is an AJAX request with PHP

Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];

<?php
function create_nonce($optional_salt='')
{
    return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>

<form>
  <input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
  <label class="form-group">
    Login<br />
    <input name="userName" id="userName" type="text" />
  </label>
  <label class="form-group">
    Password<br />
    <input name="userPassword" id="userPassword" type="password" />
  </label>
  <button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
    $("form.login button").on("click", function() {
        authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
    });

    function authorize (authUser, authPassword, authNonce) {
        $.ajax({
          type: "POST",
          url: "/inc/rpc.php",
          dataType: "json",
          data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
        })
        .success(function( msg ) {
            //some successful stuff
        });
    }
</script>

Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:

<?php
function check_nonce($nonce, $optional_salt='')
{
    $lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
    if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce || 
        hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
    {
        return true;
    } else {
        return false;
    }
}

$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
    $ret['nonce_check'] = 'passed';
} else {
    $ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>

edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.

PHP: Count a stdClass object

Just use this

$i=0;
foreach ($object as $key =>$value)
{
$i++;
}

the variable $i is number of keys.

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

Comparing floating point number to zero

No.

Equality is equality.

The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

If you really want to test two doubles for equality, use this one:

inline bool isEqual(double x, double y)
{
   return x == y;
}

Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

10.000000000000001 is not equal to 10.0, no matter what they tell you.

An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

const double NO_DATA = -1.0;

double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);

if (myData != NO_DATA)
{
    ...
}

How to use greater than operator with date?

Try this.

SELECT * FROM la_schedule WHERE `start_date` > '2012-11-18';

How do you get the length of a string?

In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

MDN says: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

Android Overriding onBackPressed()

Yes. Only override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

How do I make a simple makefile for gcc on Linux?

all: program
program.o: program.h headers.h

is enough. the rest is implicit

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

How to commit and rollback transaction in sql server?

Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ...... 

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

How can I set the 'backend' in matplotlib in Python?

The errors you posted are unrelated. The first one is due to you selecting a backend that is not meant for interactive use, i.e. agg. You can still use (and should use) those for the generation of plots in scripts that don't require user interaction.

If you want an interactive lab-environment, as in Matlab/Pylab, you'd obviously import a backend supporting gui usage, such as Qt4Agg (needs Qt and AGG), GTKAgg (GTK an AGG) or WXAgg (wxWidgets and Agg).

I'd start by trying to use WXAgg, apart from that it really depends on how you installed Python and matplotlib (source, package etc.)

How to clear the interpreter console?

Magic strings are mentioned above - I believe they come from the terminfo database:

http://www.google.com/?q=x#q=terminfo

http://www.google.com/?q=x#q=tput+command+in+unix

$ tput clear| od -t x1z 0000000 1b 5b 48 1b 5b 32 4a >.[H.[2J< 0000007

Recursively list files in Java

base on @Michael answer, add check whether listFiles return null

static Stream<File> files(File file) {
    return file.isDirectory()
            ? Optional.ofNullable(file.listFiles()).map(Stream::of).orElseGet(Stream::empty).flatMap(MainActivity::files)
            : Stream.of(file);
}

or use Lightweight-Stream-API, which support Android5 & Android6

static Stream<File> files(File f) {
    return f.isDirectory() ? Stream.ofNullable(f.listFiles()).flatMap(MainActivity::files) : Stream.of(f);
}

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

How do I set a cookie on HttpClient's HttpRequestMessage

After spending hours on this issue, none of the answers above helped me so I found a really useful tool.

Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details

Secondly, I came across this useful plugin for Fiddler:

https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode

It will just generate the C# code for you. An example was:

        var uriBuilder = new UriBuilder("test.php", "test");
        var httpClient = new HttpClient();


        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());



        httpRequestMessage.Headers.Add("Host", "test.com");
        httpRequestMessage.Headers.Add("Connection", "keep-alive");
     //   httpRequestMessage.Headers.Add("Content-Length", "138");
        httpRequestMessage.Headers.Add("Pragma", "no-cache");
        httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
        httpRequestMessage.Headers.Add("Origin", "test.com");
        httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
    //    httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
        httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
        httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
        httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");


        var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

        var httpContent = httpResponseMessage.Content;
        string result = httpResponseMessage.Content.ReadAsStringAsync().Result;

Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.

DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.

Error importing SQL dump into MySQL: Unknown database / Can't create database

It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.

How to create and download a csv file from php script?

That is the function that I used for my project, and it works as expected.

function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '";' );

    // clean output buffer
    ob_end_clean();

    $handle = fopen( 'php://output', 'w' );

    // use keys as column titles
    fputcsv( $handle, array_keys( $array['0'] ) );

    foreach ( $array as $value ) {
        fputcsv( $handle, $value , $delimiter );
    }

    fclose( $handle );

    // flush buffer
    ob_flush();

    // use exit to get rid of unexpected output afterward
    exit();
}

Python add item to the tuple

You need to make the second element a 1-tuple, eg:

a = ('2',)
b = 'z'
new = a + (b,)

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

For any case set overflow-x to hidden and I prefer to set max-height in order to limit the expansion of the height of the div. Your code should looks like this:

overflow-y: scroll;
overflow-x: hidden;
max-height: 450px;

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

How to get datas from List<Object> (Java)?

You should try something like this

List xx= (List) list.get(0)
String id = (String) xx.get(0)

or if you have a House value object the result of the query is of the same type, then

House myhouse = (House) list.get(0);

Is there a short cut for going back to the beginning of a file by vi editor?

I've always used Ctrl + Home (start of file) and Ctrl + End (end of file).

Works in both insert and nav modes.

asp.net: Invalid postback or callback argument

Add on top page

protected void Page_Load(object sender, EventArgs e)
{    
    if (!Page.IsPostBack)
    {
        //Code display data
    }
}

http://localhost/ not working on Windows 7. What's the problem?

It sounds like you have no web server running at all anywhere.

Have you tried enabling IIS and using it to display a basic html file first?

Programs & Features -> Turn Windows Features On/Off -> Internet Information Servcies

Then, place your html file in C:\inetpub\wwwroot\index.html and browse to http://localhost.

Once this works, try to get WAMP/php working. Be careful of port conflicts.

Understanding dict.copy() - shallow or deep?

"new" and "original" are different dicts, that's why you can update just one of them.. The items are shallow-copied, not the dict itself.

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

How do I set bold and italic on UILabel of iPhone/iPad?

This is very simple. Here is the code.

[yourLabel setFont:[UIFont boldSystemFontOfSize:15.0];

This will help you.

How to get address of a pointer in c/c++?

int a = 10;

To get the address of a, you do: &a (address of a) which returns an int* (pointer to int)

int *p = &a;

Then you store the address of a in p which is of type int*.

Finally, if you do &p you get the address of p which is of type int**, i.e. pointer to pointer to int:

int** p_ptr = &p;

just seen your edit:

to print out the pointer's address, you either need to convert it:

printf("address of pointer is: 0x%0X\n", (unsigned)&p);
printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr);

or if your printf supports it, use the %p:

printf("address of pointer is: %p\n", p);
printf("address of pointer to pointer is: %p\n", p_ptr);

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.

Merge, update, and pull Git branches without using checkouts

Enter git-forward-merge:

Without needing to checkout destination, git-forward-merge <source> <destination> merges source into destination branch.

https://github.com/schuyler1d/git-forward-merge

Only works for automatic merges, if there are conflicts you need to use the regular merge.

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

How to check whether the user uploaded a file in PHP?

You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained

function isUploadOkay($form_name, &$error_message) {
    if (!isset($_FILES[$form_name])) {
        $error_message = "No file upload with name '$form_name' in form.";
        return false;
    }
    $error = $_FILES[$form_name]['error'];

    // List at: http://php.net/manual/en/features.file-upload.errors.php
    if ($error != UPLOAD_ERR_OK) {
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                $error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;

            case UPLOAD_ERR_FORM_SIZE:
                $error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $error_message = 'The uploaded file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $error_message = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $error_message = 'Missing a temporary folder.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $error_message = 'Failed to write file to disk.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $error_message = 'A PHP extension interrupted the upload.';
                break;

            default:
                $error_message = 'Unknown error';
            break;
        }
        return false;
    }

    $error_message = null;
    return true;
}

Why doesn't "System.out.println" work in Android?

Correction:

On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.

Original:

There is no console to send the messages to so the System.out.println messages get lost. In the same way this happens when you run a "traditional" Java application with javaw.

Instead, you can use the Android Log class:

Log.d("MyApp","I am here");

You can then view the log either in the Logcat view in Eclipse, or by running the following command:

adb logcat

It's good to get in to the habit of looking at logcat output as that is also where the Stack Traces of any uncaught Exceptions are displayed.

The first Entry to every logging call is the log tag which identifies the source of the log message. This is helpful as you can filter the output of the log to show just your messages. To make sure that you're consistent with your log tag it's probably best to define it once as a static final String somewhere.

Log.d(MyActivity.LOG_TAG,"Application started");

There are five one-letter methods in Log corresponding to the following levels:

  • e() - Error
  • w() - Warning
  • i() - Information
  • d() - Debug
  • v() - Verbose
  • wtf() - What a Terrible Failure

The documentation says the following about the levels:

Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Convert month int to month name

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

How to make matrices in Python?

you can do it short like this:

matrix = [["A, B, C, D, E"]*5]
print(matrix)


[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]

Can’t delete docker image with dependent child images

I also got this issue, I could resolve issue with below commands. this may be cause, the image's container is running or exit so before remove image you need to remove container

docker ps -a -f status=exited : this command shows all the exited containers so then copy container Id and then run below commands to remove container

docker rm #containerId : this command remove container this may be issue that mention "image has dependent child images"

Then try to remove image with below command

docker rmi #ImageId

How to center the content inside a linear layout?

android:gravity can be used on a Layout to align its children.

android:layout_gravity can be used on any view to align itself in its parent.

NOTE: If self or children is not centering as expected, check if width/height is match_parent and change to something else

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

As "there are tens of thousands of cells in the page" binding the click-event to every single cell will cause a terrible performance problem. There's a better way to do this, that is binding a click event to the body & then finding out if the cell element was the target of the click. Like this:

$('body').click(function(e){
       var Elem = e.target;
       if (Elem.nodeName=='td'){
           //.... your business goes here....
           // remember to replace $(this) with $(Elem)
       }
})

This method will not only do your task with native "td" tag but also with later appended "td". I think you'll be interested in this article about event binding & delegate


Or you can simply use the ".on()" method of jQuery with the same effect:

$('body').on('click', 'td', function(){
        ...
});

How to Logout of an Application Where I Used OAuth2 To Login With Google?

Ouath just makes the Google instance null, hence it you out of Google. Now that's how the architecture is made. Logging out of Google, if you Logout of your app is a dirty work, but can't help if the requirement stipulates the same. Hence add the following to your signOut() function. My project was an Angular 6 app:

document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:4200";

Here localhost:4200 is the URL of my app. If your login page is xyz.com then input that.

Automatic login script for a website on windows machine?

The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.

Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""

Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.

    <!doctype html>
    <!-- saved from url=(0014)about:internet -->

    <html>
    <title>Ikariam Autologin</title>
    </head>
    <body>
    <form id="loginForm" name="loginForm" method="post"    action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
    <select name="uni_url" id="logServer" class="validate[required]">
    <option  class=""  value="s666.en.ikariam.com" fbUrl=""  cookieName=""  >
            Test_en
    </option>
    </select>
    <input id="loginName" name="name" type="text" value="PlayersName" class="" />
    <input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
    <input type="hidden" id="loginKid" name="kid" value=""/>
                        </form>
  <script>document.loginForm.submit();</script>       
  </body></html>

Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.

Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:

http://happy-snail.webs.com/autologinintogames.htm

Show/hide 'div' using JavaScript

<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>

Counting unique / distinct values by group in a data frame

Few years old .. although had similar requirement and ended up writing my own solution. Applying here:

 x<-data.frame(
 
 "Name"=c("Amy","Jack","Jack","Dave","Amy","Jack","Tom","Larry","Tom","Dave","Jack","Tom","Amy","Jack"),
 "OrderNo"=c(12,14,16,11,12,16,19,22,19,11,17,20,23,16)
)

table(sub("~.*","",unique(paste(x$Name,x$OrderNo,sep="~",collapse=NULL))))

  Amy  Dave  Jack Larry   Tom
    2     1     3     1     2

Why do people hate SQL cursors so much?

The "overhead" with cursors is merely part of the API. Cursors are how parts of the RDBMS work under the hood. Often CREATE TABLE and INSERT have SELECT statements, and the implementation is the obvious internal cursor implementation.

Using higher-level "set-based operators" bundles the cursor results into a single result set, meaning less API back-and-forth.

Cursors predate modern languages that provide first-class collections. Old C, COBOL, Fortran, etc., had to process rows one at a time because there was no notion of "collection" that could be used widely. Java, C#, Python, etc., have first-class list structures to contain result sets.

The Slow Issue

In some circles, the relational joins are a mystery, and folks will write nested cursors rather than a simple join. I've seen truly epic nested loop operations written out as lots and lots of cursors. Defeating an RDBMS optimization. And running really slowly.

Simple SQL rewrites to replace nested cursor loops with joins and a single, flat cursor loop can make programs run in 100th the time. [They thought I was the god of optimization. All I did was replace nested loops with joins. Still used cursors.]

This confusion often leads to an indictment of cursors. However, it isn't the cursor, it's the misuse of the cursor that's the problem.

The Size Issue

For really epic result sets (i.e., dumping a table to a file), cursors are essential. The set-based operations can't materialize really large result sets as a single collection in memory.

Alternatives

I try to use an ORM layer as much as possible. But that has two purposes. First, the cursors are managed by the ORM component. Second, the SQL is separated from the application into a configuration file. It's not that the cursors are bad. It's that coding all those opens, closes and fetches is not value-add programming.