Programs & Examples On #Javap

javap - The Java Class File Disassembler

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Cordova - Error code 1 for command | Command failed for

Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

For New version of Java JavaPath folder is located

64 bit OS

"C:\Program Files \Common Files\Oracle\Java\javapath\"

X86

"C:\Program Files(x86) \Common Files\Oracle\Java\javapath\"

TransactionRequiredException Executing an update/delete query

If the previous answers fail, make sure you use @Service stereotype for the class where you call the update method on your repository. I originally used @Component instead and it was not working, the simple change to @Service made it work.

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

reading text file with utf-8 encoding using java

You need to specify the encoding of the InputStreamReader using the Charset parameter.

Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));

This is work for me. i hope to help you.

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

How to draw in JPanel? (Swing/graphics Java)

Note the extra comments.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class JavaPaintUI extends JFrame {

    private int tool = 1;
    int currentX, currentY, oldX, oldY;

    public JavaPaintUI() {
        initComponents();
    }

    private void initComponents() {
        // we want a custom Panel2, not a generic JPanel!
        jPanel2 = new Panel2();

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jPanel2.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                jPanel2MousePressed(evt);
            }
            public void mouseReleased(MouseEvent evt) {
                jPanel2MouseReleased(evt);
            }
        });
        jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent evt) {
                jPanel2MouseDragged(evt);
            }
        });

        // add the component to the frame to see it!
        this.setContentPane(jPanel2);
        // be nice to testers..
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }// </editor-fold>

    private void jPanel2MouseDragged(MouseEvent evt) {
        if (tool == 1) {
            currentX = evt.getX();
            currentY = evt.getY();
            oldX = currentX;
            oldY = currentY;
            System.out.println(currentX + " " + currentY);
            System.out.println("PEN!!!!");
        }
    }

    private void jPanel2MousePressed(MouseEvent evt) {
        oldX = evt.getX();
        oldY = evt.getY();
        System.out.println(oldX + " " + oldY);
    }


    //mouse released//
    private void jPanel2MouseReleased(MouseEvent evt) {
        if (tool == 2) {
            currentX = evt.getX();
            currentY = evt.getY();
            System.out.println("line!!!! from" + oldX + "to" + currentX);
        }
    }

    //set ui visible//
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaPaintUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JPanel jPanel2;
    // End of variables declaration

    // This class name is very confusing, since it is also used as the
    // name of an attribute!
    //class jPanel2 extends JPanel {
    class Panel2 extends JPanel {

        Panel2() {
            // set a preferred size for the custom panel.
            setPreferredSize(new Dimension(420,420));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawString("BLAH", 20, 20);
            g.drawRect(200, 200, 200, 200);
        }
    }
}

Screen Shot

enter image description here

Other examples - more tailored to multiple lines & multiple line segments

HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage in the Custom Painting Approaches article.

See also this approach using painting in a BufferedImage.

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound is just an unfortunate exception used to indicate that the web server returned a 404.

Calling Java from Python

Through my own experience trying to run some java code from within python i a manner similar to how python code runs within java code in python, I was unable to a find a straight forward methodology.

My solution to my problem was by running this java code as beanshell scripts by calling the beanshell interpreter as a shell commnad from within my python code after editing the java code in a temporary file with the appropriate packages and variables.

If what I am talking about is helpful in any manner, I am glad to help you sharing more details of my solutions.

FileNotFoundException..Classpath resource not found in spring?

Two things worth pointing out:

  1. The scope of your spring-context dependency shouldn't be "runtime", but "compile", which is the default, so you can just remove the scope line.
  2. You should configure the compiler plugin to compile to at least java 1.5 to handle the annotations when building with Maven. (Can also affect IDE settings, though Eclipse doesn't tend to care.)

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    

After that, reconfiguring your project from Maven should fix it. I don't recall exactly how to do that in Eclipse, but you should find it if you right click the project node and poke around the menus.

Java NIO FileChannel versus FileOutputstream performance / usefulness

Based on my tests (Win7 64bit, 6GB RAM, Java6), NIO transferFrom is fast only with small files and becomes very slow on larger files. NIO databuffer flip always outperforms standard IO.

  • Copying 1000x2MB

    1. NIO (transferFrom) ~2300ms
    2. NIO (direct datababuffer 5000b flip) ~3500ms
    3. Standard IO (buffer 5000b) ~6000ms
  • Copying 100x20mb

    1. NIO (direct datababuffer 5000b flip) ~4000ms
    2. NIO (transferFrom) ~5000ms
    3. Standard IO (buffer 5000b) ~6500ms
  • Copying 1x1000mb

    1. NIO (direct datababuffer 5000b flip) ~4500s
    2. Standard IO (buffer 5000b) ~7000ms
    3. NIO (transferFrom) ~8000ms

The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method: How to copy a large file in Windows XP?

What's causing my java.net.SocketException: Connection reset?

The javadoc for SocketException states that it is

Thrown to indicate that there is an error in the underlying protocol such as a TCP error

In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.

To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.

As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.

Causes of getting a java.lang.VerifyError

It could also happen when you have a lot of module imports with maven. There will be two or more classes having exactly the same name ( same qualified name). This error is resulting from difference of interpretation between compile time and runtime.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How to check whether Kafka Server is running?

The good option is to use AdminClient as below before starting to produce or consume the messages

private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;           
 try (AdminClient client = AdminClient.create(properties)) {
            client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
        } catch (ExecutionException ex) {
            LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
            return;
        }

Writing data into CSV file in C#

You might just have to add a line feed "\n\r".

How to center a label text in WPF?

Sample:

Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;

How to print formatted BigDecimal values?

I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:

val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)

Result displaying $formattedBigD:

1,000,000,000,000,000,000,000,000,000,000

Insert node at a certain position in a linked list C++

 void addToSpecific()
 {
 int n;   
 int f=0;   //flag
 Node *temp=H;    //H-Head, T-Tail
 if(NULL!=H)  
 {
    cout<<"Enter the Number"<<endl;
    cin>>n;
    while(NULL!=(temp->getNext()))
    {
       if(n==(temp->getInfo()))
       {
      f=1;
      break;
       }
       temp=temp->getNext();
    }
 }
 if(NULL==H)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T=H=nn;
 }
 else if(0==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T->setNext(nn);
    T=nn;
 }
 else if(1==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    nn->setNext((temp->getNext()));
    temp->setNext(nn);
 }
 }

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

Redis strings vs Redis hashes to represent JSON: efficiency?

Some additions to a given set of answers:

First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.

It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )

 # you need me-redis and awesome-print gems to run exact code
 redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new 
  => #<Redis client v4.0.1 for redis://127.0.0.1:6379/0> 
 > redis.flushdb
  => "OK" 
 > ap redis.info(:memory)
    {
                "used_memory" => "529512",
          **"used_memory_human" => "517.10K"**,
            ....
    }
  => nil 
 # me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )    
 # txt is some english fictionary book around 56K length, 
 # so we just take some random 63-symbols string from it 
 > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
 => :done 
 > ap redis.info(:memory)
  {
               "used_memory" => "1251944",
         **"used_memory_human" => "1.19M"**, # ~ 72b per key/value
            .....
  }
  > redis.flushdb
  => "OK" 
  # setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte 
  > redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done 
  > ap redis.info(:memory)
   {
               "used_memory" => "1876064",
         "used_memory_human" => "1.79M",   # ~ 134 bytes per pair  
          ....
   }
    redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
    ap redis.info(:memory)
    {
             "used_memory" => "2262312",
          "used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes    
           ....
    }

For TheHippo answer, comments on Option one are misleading:

hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.

For BMiner answer.

Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!

But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much

But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.

Second option will most likely go to the fourth solution under a hood because as question states:

Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.

And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.

My suggestion how to optimize such dataset:

You've got two options:

  1. If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.

  2. If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.

How to convert a string Date to long millseconds

  • First convert string to java.util.Date using date formatter
  • Use getTime() to obtain count of millisecs from date

Make Frequency Histogram for Factor Variables

You could also use lattice::histogram()

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I have added in Application Class

@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

application.properties I have added

app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30

More details Configure a Custom DataSource

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.

I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.

LINK: maxConnection setting may not work even autoConfig = false in ASP.NET

Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.

LINK: <remove> Element for connectionManagement (Network Settings)

Hope it helps someone.

How to change JDK version for an Eclipse project

The JDK (JAVA_HOME) used to launch Eclipse is not necessarily the one used to compiled your project.

To see what JRE you can select for your project, check the preferences:

General ? Java Installed JRE

By default, if you have not added any JRE, the only one declared will be the one used to launched Eclipse (which can be defined in your eclipse.ini).

You can add any other JRE you want, including one compatible with your project.

After that, you will need to check in your project properties (or in the general preferences) what JRE is used, with what compliance level:

Alt text
(source: standartux.fr)

How to revert a merge commit that's already pushed to remote branch?

A very simple answer if you are looking to revert the change that you pushed just now :

commit 446sjb1uznnmaownlaybiosqwbs278q87
Merge: 123jshc 90asaf


git revert -m 2 446sjb1uznnmaownlaybiosqwbs278q87 //does the work

How do I get multiple subplots in matplotlib?

  • You can also unpack the axes in the subplots call

  • And set whether you want to share the x and y axes between the subplots

Like this:

import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()

enter image description here

The property 'Id' is part of the object's key information and cannot be modified

I had this happening when I was editing related objects from two separate contexts at the same time. Example:

DataContext ctxA = new DataContext();
DataContext ctxB = new DataContext();

Author orwell = new Author {Name = "George Orwell" };
ctxA.Add(orwell);
ctxB.Add(new Book {Name = "1984", Author = orwell});

ctxA.SaveChanges();
ctxB.SaveChanges();

My case was a little bit more convoluted (as this is obviously quite stupid) but in essence this was causing the error in my case.

How does the vim "write with sudo" trick work?

I'd like to suggest another approach to the "Oups I forgot to write sudo while opening my file" issue:

Instead of receiving a permission denied, and having to type :w!!, I find it more elegant to have a conditional vim command that does sudo vim if file owner is root.

This is as easy to implement (there might even be more elegant implementations, I'm clearly not a bash-guru):

function vim(){
  OWNER=$(stat -c '%U' $1)
  if [[ "$OWNER" == "root" ]]; then
    sudo /usr/bin/vim $*;
  else
    /usr/bin/vim $*;
  fi
}

And it works really well.

This is a more bash-centered approach than a vim-one so not everybody might like it.

Of course:

  • there are use cases where it will fail (when file owner is not root but requires sudo, but the function can be edited anyway)
  • it doesn't make sense when using vim for reading-only a file (as far as I'm concerned, I use tail or cat for small files)

But I find this brings a much better dev user experience, which is something that IMHO tends to be forgotten when using bash. :-)

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

Conveniently map between enum and int / String

Really great question :-) I used solution similar to Mr.Ferguson`s sometime ago. Our decompiled enum looks like this:

final class BonusType extends Enum
{

    private BonusType(String s, int i, int id)
    {
        super(s, i);
        this.id = id;
    }

    public static BonusType[] values()
    {
        BonusType abonustype[];
        int i;
        BonusType abonustype1[];
        System.arraycopy(abonustype = ENUM$VALUES, 0, abonustype1 = new BonusType[i = abonustype.length], 0, i);
        return abonustype1;
    }

    public static BonusType valueOf(String s)
    {
        return (BonusType)Enum.valueOf(BonusType, s);
    }

    public static final BonusType MONTHLY;
    public static final BonusType YEARLY;
    public static final BonusType ONE_OFF;
    public final int id;
    private static final BonusType ENUM$VALUES[];

    static 
    {
        MONTHLY = new BonusType("MONTHLY", 0, 1);
        YEARLY = new BonusType("YEARLY", 1, 2);
        ONE_OFF = new BonusType("ONE_OFF", 2, 3);
        ENUM$VALUES = (new BonusType[] {
            MONTHLY, YEARLY, ONE_OFF
        });
    }
}

Seeing this is apparent why ordinal() is unstable. It is the i in super(s, i);. I'm also pessimistic that you can think of a more elegant solution than these you already enumerated. After all enums are classes as any final classes.

Find closing HTML tag in Sublime Text

Try Emmet plug-in command Go To Matching Pair:

http://docs.emmet.io/actions/go-to-pair/

Shortcut (Mac): Shift + Control + T

Shortcut (PC): Control + Alt + J

https://github.com/sergeche/emmet-sublime#available-actions

Turning Sonar off for certain code

I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078").

For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})

There is also the //NOSONAR comment that tells SonarQube to ignore all errors for a specific line.

Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.

The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR and risk a Sonar issue creeping in your code by accident.

You can read more about this in the FAQ

Edit: 6/30/16 SonarQube is now called SonarLint

In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.) and the Sonar issue will expand.

On the bottom left it will have the squid number (ex. squid:S1185 Maintainability > Understandability)

So then you can suppress it by @SuppressWarnings("squid:S1185")

onclick go full screen

If you want to switch the whole tab to fullscreen (just like F11 keypress) document.documentElement is the element you are looking for:

function go_full_screen(){
    var elem = document.documentElement;
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    }
}

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

pdftk compression option

pdf2ps large.pdf small.pdf is enough, instead of two steps

pdf2ps large.pdf very_large.ps 
ps2pdf very_large.ps small.pdf

However, ps2pdf large.pdf small.pdf is a better choice.

  • ps2pdf is much faster
  • without additional parameters specified, pdf2ps sometimes produces larger file.

PHP script to loop through all of the files in a directory?

you can do this as well

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

#!/usr/bin/env node --max-old-space-size=4096 in the ionic-app-scripts.js dint work

But after Modifying: the following file it worked

node_modules/.bin/ionic-app-scripts.cmd

By adding:

@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node --max_old_space_size=4096 "%~dp0..@ionic\app-scripts\bin\ionic-app-scripts.js" %* )

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Strange "java.lang.NoClassDefFoundError" in Eclipse

For me the issue was I had configured another folder under "Run configurations" which had a class without the latest changes. Once I got it removed referred to the correct bin folder, it started working. Hope it helps someone.

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Check if a string is a valid date using DateTime.TryParse

So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.

string dateString = "198101";

if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
     //do stuff
}

The output is stored in Temp and not needed afterwards, datestring is the input string to be tested.

Can't access Tomcat using IP address

New versions of application servers removed the ability of binding to your entire network interface and limited it just to the local interface (localhost). The reason being was for security. From what I know, Tomcat and JBoss implement the same security measures.

If you want to bind it to another IP you can explicitly set it in your connector string:

  • Tomcat: address="192.168.1.100"
  • JBoss: you pass in a -b 192.168.1.100 as a command line.

Just remember that binding 0.0.0.0 allows anyone access to your box to access that server. It will bind to all addresses. If that is what you want, then use 0.0.0.0, if it isn't then specify the address you would like to explicitly bind instead.

Just make sure you understand the consequences binding to all addresses (0.0.0.0)

How to run multiple Python versions on Windows

Using a batch file to switch, easy and efficient on windows 7. I use this:

In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),

In the section user variables

  1. added %pathpython% to the path environment variable

  2. removed any references to python pathes

In the section system variables

  1. removed any references to python pathes

I created batch files for every python installation (exmple for 3.4 x64

Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.

Content of the file =

     Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin

     setx PathPython %PathPython%

To switch between versions, I execute the batch file in admin mode.

!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!

So I have exact control on it.

Gradle: How to Display Test Results in the Console in Real Time?

My favourite minimalistic version based on Shubham Chaudhary answer. enter image description here

Put this in build.gradle file:

test {
    afterSuite { desc, result ->
    if (!desc.parent)
        println("${result.resultType} " +
            "(${result.testCount} tests, " +
            "${result.successfulTestCount} successes, " +
            "${result.failedTestCount} failures, " +
            "${result.skippedTestCount} skipped)")
    }
}

window.location.href and window.open () methods in JavaScript

window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.

How to print matched regex pattern using awk?

It sounds like you are trying to emulate GNU's grep -o behaviour. This will do that providing you only want the first match on each line:

awk 'match($0, /regex/) {
    print substr($0, RSTART, RLENGTH)
}
' file

Here's an example, using GNU's awk implementation ():

awk 'match($0, /a.t/) {
    print substr($0, RSTART, RLENGTH)
}
' /usr/share/dict/words | head
act
act
act
act
aft
ant
apt
art
art
art

Read about match, substr, RSTART and RLENGTH in the awk manual.

After that you may wish to extend this to deal with multiple matches on the same line.

Remove item from list based on condition

You could use Linq.

var prod = from p in prods
           where p.ID != 1
           select p;

Android textview outline text

MagicTextView is very useful to make stroke font, but in my case, it cause error like this this error caused by duplication background attributes which set by MagicTextView

so you need to edit attrs.xml and MagicTextView.java

attrs.xml

<attr name="background" format="reference|color" />
 ?
<attr name="mBackground" format="reference|color" />

MagicTextView.java 88:95

if (a.hasValue(R.styleable.MagicTextView_mBackground)) {
Drawable background = a.getDrawable(R.styleable.MagicTextView_mBackground);
if (background != null) {
    this.setBackgroundDrawable(background);
} else {
    this.setBackgroundColor(a.getColor(R.styleable.MagicTextView_mBackground, 0xff000000));
}
}

Can I display the value of an enum with printf()?

enum MyEnum
{  A_ENUM_VALUE=0,
   B_ENUM_VALUE,
   C_ENUM_VALUE
};


int main()
{
 printf("My enum Value : %d\n", (int)C_ENUM_VALUE);
 return 0;
}

You have just to cast enum to int !
Output : My enum Value : 2

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How to compare two tags with git?

$ git diff tag1 tag2

or show log between them:

$ git log tag1..tag2

sometimes it may be convenient to see only the list of files that were changed:

$ git diff tag1 tag2 --stat

and then look at the differences for some particular file:

$ git diff tag1 tag2 -- some/file/name

A tag is only a reference to the latest commit 'on that tag', so that you are doing a diff on the commits between them.

(Make sure to do git pull --tags first)

Also, a good reference: http://learn.github.com/p/diff.html

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Loop through all the rows of a temp table and call a stored procedure for each row

You can do something like this

    Declare @min int=0, @max int =0 --Initialize variable here which will be use in loop 
    Declare @Recordid int,@TO nvarchar(30),@Subject nvarchar(250),@Body nvarchar(max)  --Initialize variable here which are useful for your

    select ROW_NUMBER() OVER(ORDER BY [Recordid] )  AS Rownumber, Recordid, [To], [Subject], [Body], [Flag]
            into #temp_Mail_Mstr FROM Mail_Mstr where Flag='1'  --select your condition with row number & get into a temp table

    set @min = (select MIN(Rownumber) from #temp_Mail_Mstr); --Get minimum row number from temp table
    set @max = (select Max(Rownumber) from #temp_Mail_Mstr);  --Get maximum row number from temp table

   while(@min <= @max)
   BEGIN
        select @Recordid=Recordid, @To=[To], @Subject=[Subject], @Body=Body from #temp_Mail_Mstr where Rownumber=@min

        -- You can use your variables (like @Recordid,@To,@Subject,@Body) here  
        -- Do your work here 

        set @min=@min+1 --Increment of current row number
    END

What are the differences between a program and an application?

When I studied IT in college my prof. made it simple for me:

"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."

Got it right on the exam.

So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.

Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Disallow Twitter Bootstrap modal window from closing

If you want to conditionally disable the backdrop click closing feature. You can use the following line to set the backdrop option to static during runtime.

Bootstrap v3.xx

jQuery('#MyModal').data('bs.modal').options.backdrop = 'static';

Bootstrap v2.xx

jQuery('#MyModal').data('modal').options.backdrop = 'static';

This will prevent an already instantiated model with backdrop option set to false (the default behavior), from closing.

How to make a phone call in android and come back to my activity when the call is done?

Steps:

1)Add the required permissions in the Manifest.xml file.

<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2)Create a listener for the phone state changes.

public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        //when this state occurs, and your flag is set, restart your app
    Intent i = context.getPackageManager().getLaunchIntentForPackage(
                            context.getPackageName());
    //For resuming the application from the previous state
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Uncomment the following if you want to restart the application instead of bring to front.
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(i);
    }
}
}

3)Initialize the listener in your OnCreate

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP with FLAG_ACTIVITY_SINGLE_TOP

Reference this Answer

Simplest SOAP example

This is the simplest JavaScript SOAP Client I can create.

<html>
<head>
    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://somesoapurl.com/', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' + 
                    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                    'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
                    'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                    'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +
                '</soapenv:Envelope>';

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        alert(xmlhttp.responseText);
                        // alert('done. use firebug/console to see network response');
                    }
                }
            }
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            // send request
            // ...
        }
    </script>
</head>
<body>
    <form name="Demo" action="" method="post">
        <div>
            <input type="button" value="Soap" onclick="soap();" />
        </div>
    </form>
</body>
</html> <!-- typo -->

Read input from console in Ruby?

If you want to make interactive console:

#!/usr/bin/env ruby

require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
  addends << addend_string.to_i
  puts "#{addends.join(' + ')} = #{addends.sum}"
end

Usage (assuming you put above snippet into summator file in current directory):

chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3

Use Ctrl + D to exit

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

How to implement a queue using two stacks?

public class QueueUsingStacks<T>
{
    private LinkedListStack<T> stack1;
    private LinkedListStack<T> stack2;

    public QueueUsingStacks()
    {
        stack1=new LinkedListStack<T>();
        stack2 = new LinkedListStack<T>();

    }
    public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )
    {
        while(source.Head!=null)
        {
            dest.Push(source.Head.Data);
            source.Head = source.Head.Next;
        }
    }
    public void Enqueue(T entry)
    {

       stack1.Push(entry);
    }
    public T Dequeue()
    {
        T obj;
        if (stack2 != null)
        {
            Copy(stack1, stack2);
             obj = stack2.Pop();
            Copy(stack2, stack1);
        }
        else
        {
            throw new Exception("Stack is empty");
        }
        return obj;
    }

    public void Display()
    {
        stack1.Display();
    }


}

For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack

WindowsError: [Error 126] The specified module could not be found

problem solved for me. I changed version from pytorch=1.5.1 to pytorch=1.4 and typed the below command in anaconda prompt window

conda install pytorch==1.4.0 torchvision==0.5.0 -c pytorch

Decompile an APK, modify it and then recompile it

I know this question is answered still and I am not trying to be smart here. I'll just want to share another method on this topic.

Download applications with apk grail

APK Grail providing the free zip file of the application.

Is it possible to override / remove background: none!important with jQuery?

div { background: none !important }
div { background: red; }

Is transparent.

div { background: none !important }
div { background: red !important; }

Is red.

An !important can override another !important.

If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

Ship an application with a database

The SQLiteAssetHelper library makes this task really simple.

It's easy to add as a gradle dependency (but a Jar is also available for Ant/Eclipse), and together with the documentation it can be found at:
https://github.com/jgilfelt/android-sqlite-asset-helper

Note: This project is no longer maintained as stated on above Github link.

As explained in documentation:

  1. Add the dependency to your module's gradle build file:

    dependencies {
        compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    }
    
  2. Copy the database into the assets directory, in a subdirectory called assets/databases. For instance:
    assets/databases/my_database.db

    (Optionally, you may compress the database in a zip file such as assets/databases/my_database.zip. This isn't needed, since the APK is compressed as a whole already.)

  3. Create a class, for example:

    public class MyDatabase extends SQLiteAssetHelper {
    
        private static final String DATABASE_NAME = "my_database.db";
        private static final int DATABASE_VERSION = 1;
    
        public MyDatabase(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    }
    

Adding images to an HTML document with javascript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

_x000D_
_x000D_
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
_x000D_
_x000D_

... you'd get this:

enter image description here

How to make exe files from a node.js app?

I was using below technology:

  1. @vercel/ncc (this make sure we bundle all necessary dependency into single file)
  2. pkg (this to make exe file)

Let do below:

  1. npm i -g @vercel/ncc

  2. ncc build app.ts -o dist (my entry file is app.ts, output is in dist folder, make sure you run in folder where package.json and app.ts reside, after run above you may see the index.js file in the folder dist)

  3. npm install -g pkg (installing pkg)

  4. pkg index.js (make sure you are in the dist folder above)

Split list into smaller lists (split in half)

A little more generic solution (you can specify the number of parts you want, not just split 'in half'):

EDIT: updated post to handle odd list lengths

EDIT2: update post again based on Brians informative comments

def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] 
             for i in range(wanted_parts) ]

A = [0,1,2,3,4,5,6,7,8,9]

print split_list(A, wanted_parts=1)
print split_list(A, wanted_parts=2)
print split_list(A, wanted_parts=8)

Javascript array sort and unique

function sort_unique(arr) {
    return arr.sort().filter(function(el,i,a) {
        return (i==a.indexOf(el));
    });
}

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error in Chrome. The Chrome console told me that the error was in the 1st line of the HTML file.

It was actually in the .js file. So watch out for setValidNou(1060, $(this).val(), 0') error types.

draw diagonal lines in div background with CSS

Almost perfect solution, that automatically scales to dimensions of an element would be usage of CSS3 linear-gradient connected with calc() as shown below. Main drawback is of course compatibility. Code below works in Firefox 25 and Explorer 10 and 11, but in Chrome (I've tested v30 and v32 dev) there are some subtle problems with lines disappearing if they are too narrow. Moreover disappearing depends on the box dimensions – style below works for div { width: 100px; height: 100px}, but fails for div { width: 200px; height: 200px} for which in my tests 0.8px in calculations needs to be replaced with at least 1.1048507095px for diagonals to be shown and even then line rendering quality is quite poor. Let's hope this Chrome bug will be solved soon.

_x000D_
_x000D_
.crossed {_x000D_
     background: _x000D_
         linear-gradient(to top left,_x000D_
             rgba(0,0,0,0) 0%,_x000D_
             rgba(0,0,0,0) calc(50% - 0.8px),_x000D_
             rgba(0,0,0,1) 50%,_x000D_
             rgba(0,0,0,0) calc(50% + 0.8px),_x000D_
             rgba(0,0,0,0) 100%),_x000D_
         linear-gradient(to top right,_x000D_
             rgba(0,0,0,0) 0%,_x000D_
             rgba(0,0,0,0) calc(50% - 0.8px),_x000D_
             rgba(0,0,0,1) 50%,_x000D_
             rgba(0,0,0,0) calc(50% + 0.8px),_x000D_
             rgba(0,0,0,0) 100%);_x000D_
}
_x000D_
<textarea class="crossed"></textarea>
_x000D_
_x000D_
_x000D_

Should I use window.navigate or document.location in JavaScript?

Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

https://github.com/michaelpapworth/jQuery.navigate

"When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

If one examines the code what it does is this:

   var methods = {
            'goTo': function (url) {
                // instead of using window.location to navigate away
                // we use an ephimeral link to click on and thus ensure
                // the referer (current url) is always passed on to the request
                $('<a></a>').attr("href", url)[0].click();
            },
            ...
   };

Neato!

How to convert a String to Bytearray

I know the question is almost 4 years old, but this is what worked smoothly with me:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes;_x000D_
};_x000D_
_x000D_
Array.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.toString().split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

or, if you want to work with strings only, and no Array, you can use:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes.toString();_x000D_
};_x000D_
_x000D_
String.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

How to calculate Date difference in Hive

yes datediff is implemented; see: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

By the way I found this by Google-searching "hive datediff", it was the first result ;)

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

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

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

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

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Cannot create SSPI context

First thing you should do is go into the logs (Management\SQL Server Logs) and see if SQL Server successfully registered the Service Principal Name (SPN). If you see some sort of error (The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service) then you know where to start.

We saw this happen when we changed the account SQL Server was running under. Resetting it to Local System Account solved the problem. Microsoft also has a guide on manually configuring the SPN.

Chrome doesn't delete session cookies

I just had this problem of Chrome storing a Session ID but I do not like the idea of disabling the option to continue where I left off. I looked at the cookies for the website and found a Session ID cookie for the login page. Deleting that did not correct my problem. I search for the domain and found there was another Session ID cookie on the domain. Deleting both Session ID cookies manually fixed the problem and I did not close and reopen the browser which could have restored the cookies.

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

List of foreign keys and the tables they reference in Oracle DB

select d.table_name,

       d.constraint_name "Primary Constraint Name",

       b.constraint_name "Referenced Constraint Name"

from user_constraints d,

     (select c.constraint_name,

             c.r_constraint_name,

             c.table_name

      from user_constraints c 

      where table_name='EMPLOYEES' --your table name instead of EMPLOYEES

      and constraint_type='R') b

where d.constraint_name=b.r_constraint_name

How to get build time stamp from Jenkins build variables?

You can use the Jenkins object to fetch the start time directly

Jenkins.getInstance().getItemByFullName(<your_job_name>).getBuildByNumber(<your_build_number>).getTime()

also answered it here: https://stackoverflow.com/a/63074829/1968948

Replace new line/return with space using regex

This should take care of space, tab and newline:

data = data.replaceAll("[ \t\n\r]*", " ");

How to roundup a number to the closest ten?

You can use the function MROUND(<reference cell>, <round to multiple of digit needed>).

Example:

  1. For a value A1 = 21 round to multiple of 10 it would be written as =MROUND(A1,10) for which Result = 20

  2. For a value Z4 = 55.1 round to multiple of 10 it would be written as =MROUND(Z4,10) for which Result = 60

tsc throws `TS2307: Cannot find module` for a local file

In my case ,

   //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            //{
            //    HotModuleReplacement = true
            //});

i commented it in startup.cs

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

In the case of permission denied error, you just need to go with this command.

sudo pip install virtualenv

sudo before the command will throw away the current user permissions error.

Note: For security risks, You should read piotr comment.

Pass a PHP string to a JavaScript variable (and escape newlines)

Expanding on someone else's answer:

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

Generate random numbers with a given (numerical) distribution

scipy.stats.rv_discrete might be what you want. You can supply your probabilities via the values parameter. You can then use the rvs() method of the distribution object to generate random numbers.

As pointed out by Eugene Pakhomov in the comments, you can also pass a p keyword parameter to numpy.random.choice(), e.g.

numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])

If you are using Python 3.6 or above, you can use random.choices() from the standard library – see the answer by Mark Dickinson.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Using port number in Windows host file

You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.

How to execute shell command in Javascript

In IE, you can do this :

var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");

Java, how to compare Strings with String Arrays

Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.

Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?

...or do I misunderstand your question?

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

if some directory/folder does not exist but somehow you navigated to that directory in that case you can see this Error,

for example:

  • currently, you are in "mno" directory (path = abc/def/ghi/jkl/mno
  • run "sudo su" and delete mno
  • goto the "ghi" directory and delete "jkl" directory
  • now you are in "ghi" directory (path abc/def/ghi)
  • run "exit"
  • after running the "exit", you will get that Error
  • now you will be in "mno"(path = abc/def/ghi/jkl/mno) folder. that does not exist.

so, Generally this Error will show when Directory doesn't exist.

to fix this, simply run "cd;" or you can move to any other directory which exists.

What programming language does facebook use?

The language used by Facebook is PHP.

Also, do any other social networking sites use the same language?

The other one I know of is friendster.

How to update large table with millions of rows in SQL Server?

First of all, thank you all for your inputs. I tweak my Query - 1 and got my desired result. Gordon Linoff is right, PRINT was messing up my query so I modified it as following:

Modified Query - 1:

SET ROWCOUNT 5
WHILE (1 = 1)
  BEGIN
    BEGIN TRANSACTION

        UPDATE TableName 
        SET Value = 'abc1' 
        WHERE Parameter1 = 'abc' AND Parameter2 = 123

        IF @@ROWCOUNT = 0
          BEGIN
                COMMIT TRANSACTION
                BREAK
          END
    COMMIT TRANSACTION
  END
SET ROWCOUNT  0

Output:

(5 row(s) affected)

(5 row(s) affected)

(4 row(s) affected)

(0 row(s) affected)

Select datatype of the field in postgres

Pulling data type from information_schema is possible, but not convenient (requires joining several columns with a case statement). Alternatively one can use format_type built-in function to do that, but it works on internal type identifiers that are visible in pg_attribute but not in information_schema. Example

SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a JOIN pg_class b ON a.attrelid = b.relfilenode
WHERE a.attnum > 0 -- hide internal columns
AND NOT a.attisdropped -- hide deleted columns
AND b.oid = 'my_table'::regclass::oid; -- example way to find pg_class entry for a table

Based on https://gis.stackexchange.com/a/97834.

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

How to create a JavaScript callback for knowing when an image is loaded?

You could use the load()-event in jQuery but it won't always fire if the image is loaded from the browser cache. This plugin https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js can be used to remedy that problem.

Selecting only first-level elements in jquery

1

 $("ul.rootlist > target-element")
2   $("ul.rootlist").find(target-element).eq(0) (only one instance)
3   $("ul.rootlist").children(target-element)

there are probably many other ways

Sorting int array in descending order

    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    };

    // option 1
    Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
    Arrays.sort(array, comparator);

    // option 2
    int[] array2 = new int[] { 1, 24, 4, 4, 345 };
    List<Integer>list = Ints.asList(array2);
    Collections.sort(list, comparator);
    array2 = Ints.toArray(list);

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

Access to the path denied error in C#

I had this issue for longer than I would like to admit.

I simply just needed to run VS as an administrator, rookie mistake on my part...

Hope this helps someone <3

Is there a portable way to get the current username in Python?

You best bet would be to combine os.getuid() with pwd.getpwuid():

import os
import pwd

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]

Refer to the pwd docs for more details:

http://docs.python.org/library/pwd.html

Best way to convert an ArrayList to a string

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join("\t", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");

CSS hide scroll bar, but have element scrollable

work on all major browsers

html {
    overflow: scroll;
    overflow-x: hidden;
}
::-webkit-scrollbar {
    width: 0px;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

Difference between & and && in Java?

'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).

if( x != null && x.equals("*BINGO*") {
  then do something with x...
}

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

How to limit google autocomplete results to City and Country only

Also you will need to zoom and center the map due to your country restrictions!

Just use zoom and center parameters! ;)

function initialize() {
  var myOptions = {
    zoom: countries['us'].zoom,
    center: countries['us'].center,
    mapTypeControl: false,
    panControl: false,
    zoomControl: false,
    streetViewControl: false
  };

  ... all other code ...

}

How to get HTTP Response Code using Selenium WebDriver

You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.

An usage example:

>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

How to change the color of a SwitchCompat from AppCompat library

Ok, so I'm sorry but most of these answers are incomplete or have some minor bug in them. The very complete answer from @austyn-mahoney is correct and the source for this answer, but it's complicated and you probably just want to style a switch. 'Styling' controls across different versions of Android is an epic pain in the ass. After pulling my hair out for days on a project with very tight design constraints I finally broke down and wrote a test app and then really dug in and tested the various solutions out there for styling switches and check-boxes, since when a design has one it frequently has the other. Here's what I found...

First: You can't actually style either of them, but you can apply a theme to all of them, or just one of them.

Second: You can do it all from XML and you don't need a second values-v21/styles.xml.

Third: when it comes to switches you have two basic choices if you want to support older versions of Android (like I'm sure you do)...

  1. You can use a SwitchCompat and you will be able to make it look the same across platforms.
  2. You can use a Switch and you will be able to theme it with the rest of your theme, or just that particular switch and on older versions of Android you'll just see an unstyled older square switch.

Ok now for the simple reference code. Again if you create a simple Hello World! and drop this code in you can play to your hearts content. All of that is boiler plate here so I'm just going to include the XML for the activity and the style...

activity_main.xml...

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        app:switchTextAppearance="@style/BrandedSwitch.text"
        app:theme="@style/BrandedSwitch.control"
        app:showText="true" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed Switch" />

    <Switch
        android:id="@+id/switch_item3"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' Switch" />

    <Switch
        android:id="@+id/switch_item4"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        android:theme="@style/BrandedSwitch"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' CheckBox" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:theme="@style/BrandedCheckBox"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed CheckBox" />

    <CheckBox
        android:id="@+id/checkbox2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"/>

</RelativeLayout>

styles.xml...

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#3F51B5</item>
    <item name="colorPrimaryDark">#303F9F</item>
    <item name="colorAccent">#FF4081</item>
</style>

<style name="BrandedSwitch.control" parent="Theme.AppCompat.Light">
    <!-- active thumb & track color (30% transparency) -->
    <item name="colorControlActivated">#e6e600</item>
    <item name="colorSwitchThumbNormal">#cc0000</item>
</style>

<style name="BrandedSwitch.text" parent="Theme.AppCompat.Light">
    <item name="android:textColor">#ffa000</item>
    <item name="android:textSize">9dp</item>
</style>

<style name="BrandedCheckBox" parent="AppTheme">
    <item name="colorAccent">#aaf000</item>
    <item name="colorControlNormal">#ff0000</item>
</style>

<style name="BrandedSwitch" parent="AppTheme">
    <item name="colorAccent">#39ac39</item>
</style>

I know, I know, you are too lazy to build this, you just want to get your code written and check it in so you can close this pain in the ass Android compatibility nightmare bug so that the designer on your team will finally be happy. I get it. Here's what it looks like when you run it...

API_21:

API 21

API_18:

API18

How to set a string's color

Strings don't encapsulate color information. Are you thinking of setting the color in a console or in the GUI?

Nested iframes, AKA Iframe Inception

I think the best way to reach your div:

var your_element=$('iframe#uploads').children('iframe').children('div#element');

It should work well.

How to move screen without moving cursor in Vim?

I've used these shortcuts in the past (note: separate key strokes i.e. tap z, let go, tap the subsequent key):

z enter --> moves current line to top of screen

z . --> moves current line to center of screen

z - --> moves current line to bottom

If it's not obvious:

enter means the Return or Enter key.

. means the DOT or "full stop" key (.).

- means the HYPHEN key (-)

For what it's worth, z. avoids the danger of saving and closing Vi by accidentally typing ZZ if the caps-lock is on.

How to 'grep' a continuous stream?

This one command workes for me (Suse):

mail-srv:/var/log # tail -f /var/log/mail.info |grep --line-buffered LOGIN  >> logins_to_mail

collecting logins to mail service

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Use like blow

i use this command and solve

"Uncaught TypeError: Cannot read property 'msie' of undefined" Error

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    return;
}

AngularJS Multiple ng-app within a page

<html>
<head>
    <script src="angular.min.js"></script>
</head>
<body>
<div ng-app="shoppingCartParentModule" >
     <div ng-controller="ShoppingCartController">
        <h1>Your order</h1>
        <div ng-repeat="item in items">
            <span>{{item.product_name}}</span>
            <span>{{item.price | currency}}</span>
            <button ng-click="remove($index);">Remove</button>
        </div>
    </div>

    <div ng-controller="NamesController">
        <h1>List of Names</h1>
        <div ng-repeat="name in names">
            <p>{{name.username}}</p>
        </div>
    </div>
</div>
</body>
<script>
var shoppingCartModule = angular.module("shoppingCart", [])
            shoppingCartModule.controller("ShoppingCartController",
                function($scope) {
                    $scope.items = [
                        {product_name: "Product 1", price: 50},
                        {product_name: "Product 2", price: 20},
                        {product_name: "Product 3", price: 180}
                    ];
                    $scope.remove = function(index) {
                        $scope.items.splice(index, 1);
                    }
                }
            );
            var namesModule = angular.module("namesList", [])
            namesModule.controller("NamesController",
                function($scope) {
                    $scope.names = [
                        {username: "Nitin"},
                        {username: "Mukesh"}
                    ];
                }
            );
   angular.module("shoppingCartParentModule",["shoppingCart","namesList"])
</script>
</html>

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

Terminating a Java Program

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do - and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you'd need to return void. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.

return would cause the program to exit only if it's inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String... str) {
    System.out.println(1);
    return;
    System.out.println(2);
    System.exit(0);
}

will not compile with most compiler - producing unreachable code error pointing to the second System.out.println call.

Git Pull is Not Possible, Unmerged Files

Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

git fetch origin
git reset --hard origin/master

This basically just takes the current branch and points it to the HEAD of the remote branch.

WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

Or you can use the plumbing commands to do essentially the same:

git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard

EDIT: I'd like to briefly explain why this works.

The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

A branch is just a named pointer to a given hash. Here's an example set:

$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master

Each of these files contains a hash pointing to a commit:

$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b

These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

git reset --hard origin/master

git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

To see this at work go ahead and try out the following:

git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD

How to install pip with Python 3?

For python3 try this:

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python

The good thing is that It will also detect what version of python you have (even if it's an environment of python in your custom location). After this you can proceed normally with (for example)

pip install numpy

source: https://pypi.python.org/pypi/setuptools/1.1.6#upgrading-from-setuptools-0-6

Find a file in python

If you are working with Python 2 you have a problem with infinite recursion on windows caused by self-referring symlinks.

This script will avoid following those. Note that this is windows-specific!

import os
from scandir import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(unicode(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print "Could not resolve " + os.path.join(direc, entry.name)
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

It returns a list with all paths that point to files in the filenames list. Usage:

find("C:\\", ["file1.abc", "file2.abc", "file3.abc", "file4.abc", "file5.abc"])

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

java.io.IOException: Invalid Keystore format

I think the keystore file you want to use has a different or unsupported format in respect to your Java version. Could you post some more info of your task?

In general, to solve this issue you might need to recreate the whole keystore (using some other JDK version for example). In export-import the keys between the old and the new one - if you manage to open the old one somewhere else.

If it is simply an unsupported version, try the BouncyCastle crypto provider for example (although I'm not sure If it adds support to Java for more keystore types?).

Edit: I looked at the feature spec of BC.

Telnet is not recognized as internal or external command

  1. Open "Start" (Windows Button)
  2. Search for "Turn Windows features On or Off"
  3. Check "Telnet client" and check "Telnet server".

Already defined in .obj - no double inclusions

This is one of the method to overcome this issue.

  • Just put the prototype in the header files and include the header files in the .cpp files as shown below.

client.cpp

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is... {

// ...

    bool read(int, char*); // Or whatever the name is...

//  ... };

#endif

client.h

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

main.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.h

int main()

How to convert a date String to a Date or Calendar object?

The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes.

Joda's DateFormatter can parse a String to a Joda DateTime.

Skipping every other element after the first

Using the for-loop like you have, one way is this:

def altElement(a):
    b = []
    j = False
    for i in a:
        j = not j
        if j:
            b.append(i)

    print b

j just keeps switching between 0 and 1 to keep track of when to append an element to b.

Get the device width in javascript

Based on the method Bootstrap uses to set its Responsive breakpoints, the following function returns xs, sm, md, lg or xl based on the screen width:

_x000D_
_x000D_
console.log(breakpoint());

function breakpoint() {
    let breakpoints = {
        '(min-width: 1200px)': 'xl',
        '(min-width: 992px) and (max-width: 1199.98px)': 'lg',
        '(min-width: 768px) and (max-width: 991.98px)': 'md',
        '(min-width: 576px) and (max-width: 767.98px)': 'sm',
        '(max-width: 575.98px)': 'xs',
    }

    for (let media in breakpoints) {
        if (window.matchMedia(media).matches) {
            return breakpoints[media];
        }
    }

    return null;
}
_x000D_
_x000D_
_x000D_

How to find the cumulative sum of numbers in a list?

l = [1,-1,3]
cum_list = l

def sum_list(input_list):
    index = 1
    for i in input_list[1:]:
        cum_list[index] = i + input_list[index-1]
        index = index + 1 
    return cum_list

print(sum_list(l))

How to downgrade Node version

This may be due to version incompatibility between your code and the version you have installed.

In my case I was using v8.12.0 for development (locally) and installed latest version v13.7.0 on the server.

So using nvm I switched the node version to v8.12.0 with the below command:

> nvm install 8.12.0 // to install the version I wanted

> nvm use 8.12.0  // use the installed version

NOTE: You need to install nvm on your system to use nvm.

You should try this solution before trying solutions like installing build-essentials or uninstalling the current node version because you could switch between versions easily than reverting all the installations/uninstallations that you've done.

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Android get current Locale, not default

As per official documentation ConfigurationCompat is deprecated in support libraries

You can consider using

LocaleListCompat.getDefault()[0].toLanguageTag() 0th position will be user preferred locale

To get Default locale at 0th position would be LocaleListCompat.getAdjustedDefault()

How to get "GET" request parameters in JavaScript?

The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.

function getUrlParameter(name) {
    var urlOld          = window.location.href.split('?');
    urlOld[1]           = urlOld[1] || '';
    var urlBase         = urlOld[0];
    var urlQuery        = urlOld[1].split('#');
    urlQuery[1]         = urlQuery[1] || '';
    var parametersString = urlQuery[0].split('&');
    if (parametersString.length === 1 && parametersString[0] === '') {
        parametersString = [];
    }
    // console.log(parametersString);
    var anchor          = urlQuery[1] || '';

    var urlParameters = {};
    jQuery.each(parametersString, function (idx, parameterString) {
        paramName   = parameterString.split('=')[0];
        paramValue  = parameterString.split('=')[1];
        urlParameters[paramName] = paramValue;
    });
    return urlParameters[name];
}

How to install both Python 2.x and Python 3.x in Windows

I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same "Fatal error" when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.

How to correctly display .csv files within Excel 2013?

Taken from https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns

The behavior of Excel when opening CSV files heavily depends on your local settings and the selected list separator under Region and language » Formats » Advanced. By default Excel will assume every CSV was saved with that separator. Which is true as long as the CSV doesn't come from another country!

If your customers are in other countries, they may see other results then you think.

For example, here you see that a German Excel will use semicolon instead of comma like in the U.S.

Regional Settings

How to detect READ_COMMITTED_SNAPSHOT is enabled?

  1. As per https://msdn.microsoft.com/en-us/library/ms180065.aspx, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."

  2. Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

https://www.blackhat.com/docs/asia-16/materials/asia-16-Sivakorn-Im-Not-a-Human-Breaking-the-Google-reCAPTCHA-wp.pdf

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:

https://github.com/neuroradiology/InsideReCaptcha

UPDATE 2017

A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:

http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf

UPDATE 2018

Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

https://www.google.com/recaptcha/intro/v3beta.html

Define a fixed-size list in Java

A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.

The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array) to create the list wrapper. The wrapper will allow you to do operations like get and set, but the add and remove operations will throw exceptions.

And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.


On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add / addAll and remove / removeAll / retainAll operations. (And in the iterator remove methods if they are supported.)

So why doesn't the Java Collections framework implement these? Here's why I think so:

  1. Use-cases that need this are rare.
  2. The use-cases where this is needed, there are different requirements on what to do when an operation tries to break the limits; e.g. throw exception, ignore operation, discard some other element to make space.
  3. A list implementation with limits could be problematic for helper methods; e.g. Collections.sort.

Downloading Java JDK on Linux via wget is shown license page instead

This happens because when you click the "Accept" button on the download page in your browser, the webpage saves a cookie that it uses to check your agreement before letting you download the file. The problem occurs when trying to download from the command line using wget and it's because there's no cookie information sent with the wget request for downloading the file so from the file server's perspective, you're a completely new user who hasn't accepted the license agreement.

One solution is to send cookie information using the --header option of the wget utility (as shown above in other answers). Ideally if some content is protected, you'd use the various session management options available with wget. For this particular problem however, it's solved (currently) by sending the Cookie header with the download request.

AngularJS: factory $http.get JSON file

I wanted to note that the fourth part of Accepted Answer is wrong .

theApp.factory('mainInfo', function($http) { 

var obj = {content:null};

$http.get('content.json').success(function(data) {
    // you can do some processing here
    obj.content = data;
});    

return obj;    
});

The above code as @Karl Zilles wrote will fail because obj will always be returned before it receives data (thus the value will always be null) and this is because we are making an Asynchronous call.

The details of similar questions are discussed in this post


In Angular, use $promise to deal with the fetched data when you want to make an asynchronous call.

The simplest version is

theApp.factory('mainInfo', function($http) { 
    return {
        get:  function(){
            $http.get('content.json'); // this will return a promise to controller
        }
});


// and in controller

mainInfo.get().then(function(response) { 
    $scope.foo = response.data.contentItem;
});

The reason I don't use success and error is I just found out from the doc, these two methods are deprecated.

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

Best practice: PHP Magic Methods __set and __get

I am now returning to setters and getters but I am also putting the getters and setters in the magic methos __get and __set. This way I have a default behavior when I do this

$class->var;

This will just call the getter I have set in the __get. Normally I will just use the getter directly but there are still some instances where this is just simpler.

How do I convert a datetime to date?

Answer updated to Python 3.7 and more

Here is how you can turn a date-and-time object

(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)

into a date object (aka datetime.date object):

from datetime import datetime

#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)

# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)

# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()

And just to be clear, if you print those elements, here is the output :

print(datetime_element)

2020-07-10 12:56:54.324893


print(date_element)

2020-07-10

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Put this formula in cell d31 and copy down to d39

 =iferror(vlookup(b31,$f$3:$g$12,2,0),"")

Here's what is going on. VLOOKUP:

  • Takes a value (here the contents of b31),
  • Looks for it in the first column of a range (f3:f12 in the range f3:g12), and
  • Returns the value for the corresponding row in a column in that range (in this case, the 2nd column or g3:g12 of the range f3:g12).

As you know, the last argument of VLOOKUP sets the match type, with FALSE or 0 indicating an exact match.

Finally, IFERROR handles the #N/A when VLOOKUP does not find a match.

How can I edit a view using phpMyAdmin 3.2.4?

In your database table list it should show View in Type column. To edit View:

  1. Click on your View in table list
  2. Click on Structure tab
  3. Click on Edit View under Check All

enter image description here

Hope this help

update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:

  1. In Row column: It had zero Row
  2. In Action column: It had greyed empty button

Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

Get url without querystring

You can use System.Uri

Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);

Or you can use substring

string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));

EDIT: Modifying the first solution to reflect brillyfresh's suggestion in the comments.

SQL - Query to get server's IP address

The server might have multiple IP addresses that it is listening on. If your connection has the VIEW SERVER STATE server permission granted to it, you can run this query to get the address you have connected to SQL Server:

SELECT dec.local_net_address
FROM sys.dm_exec_connections AS dec
WHERE dec.session_id = @@SPID;

This solution does not require you to shell out to the OS via xp_cmdshell, which is a technique that should be disabled (or at least strictly secured) on a production server. It may require you to grant VIEW SERVER STATE to the appropriate login, but that is a far smaller security risk than running xp_cmdshell.

The technique mentioned by GilM for the server name is the preferred one:

SELECT SERVERPROPERTY(N'MachineName');

How to Calculate Execution Time of a Code Snippet in C++

(windows specific solution) The current (circa 2017) way to get accurate timings under windows is to use "QueryPerformanceCounter". This approach has the benefit of giving very accurate results and is recommended by MS. Just plop the code blob into a new console app to get a working sample. There is a lengthy discussion here: Acquiring High resolution time stamps

#include <iostream>
#include <tchar.h>
#include <windows.h>

int main()
{
constexpr int MAX_ITER{ 10000 };
constexpr __int64 us_per_hour{ 3600000000ull }; // 3.6e+09
constexpr __int64 us_per_min{ 60000000ull };
constexpr __int64 us_per_sec{ 1000000ull };
constexpr __int64 us_per_ms{ 1000ull };

// easy to work with
__int64 startTick, endTick, ticksPerSecond, totalTicks = 0ull;

QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);

for (int iter = 0; iter < MAX_ITER; ++iter) {// start looping
    QueryPerformanceCounter((LARGE_INTEGER *)&startTick); // Get start tick
    // code to be timed
    std::cout << "cur_tick = " << iter << "\n";
    QueryPerformanceCounter((LARGE_INTEGER *)&endTick); // Get end tick
    totalTicks += endTick - startTick; // accumulate time taken
}

// convert to elapsed microseconds
__int64 totalMicroSeconds =  (totalTicks * 1000000ull)/ ticksPerSecond;

__int64 hours = totalMicroSeconds / us_per_hour;
totalMicroSeconds %= us_per_hour;
__int64 minutes = totalMicroSeconds / us_per_min;
totalMicroSeconds %= us_per_min;
__int64 seconds = totalMicroSeconds / us_per_sec;
totalMicroSeconds %= us_per_sec;
__int64 milliseconds = totalMicroSeconds / us_per_ms;
totalMicroSeconds %= us_per_ms;


std::cout << "Total time: " << hours << "h ";
std::cout << minutes << "m " << seconds << "s " << milliseconds << "ms ";
std::cout << totalMicroSeconds << "us\n";

return 0;
}

Least common multiple for 3 or more numbers

We have working implementation of Least Common Multiple on Calculla which works for any number of inputs also displaying the steps.

What we do is:

0: Assume we got inputs[] array, filled with integers. So, for example:
   inputsArray = [6, 15, 25, ...]
   lcm = 1

1: Find minimal prime factor for each input.
   Minimal means for 6 it's 2, for 25 it's 5, for 34 it's 17
   minFactorsArray = []

2: Find lowest from minFactors:
   minFactor = MIN(minFactorsArray)

3: lcm *= minFactor

4: Iterate minFactorsArray and if the factor for given input equals minFactor, then divide the input by it:
  for (inIdx in minFactorsArray)
    if minFactorsArray[inIdx] == minFactor
      inputsArray[inIdx] \= minFactor

5: repeat steps 1-4 until there is nothing to factorize anymore. 
   So, until inputsArray contains only 1-s.

And that's it - you got your lcm.

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:

SET PORT=8000

For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

How to convert an xml string to a dictionary?

You can do this quite easily with lxml. First install it:

[sudo] pip install lxml

Here is a recursive function I wrote that does the heavy lifting for you:

from lxml import objectify as xml_objectify


def xml_to_dict(xml_str):
    """ Convert xml to dict, using lxml v3.4.2 xml processing library """
    def xml_to_dict_recursion(xml_object):
        dict_object = xml_object.__dict__
        if not dict_object:
            return xml_object
        for key, value in dict_object.items():
            dict_object[key] = xml_to_dict_recursion(value)
        return dict_object
    return xml_to_dict_recursion(xml_objectify.fromstring(xml_str))

xml_string = """<?xml version="1.0" encoding="UTF-8"?><Response><NewOrderResp>
<IndustryType>Test</IndustryType><SomeData><SomeNestedData1>1234</SomeNestedData1>
<SomeNestedData2>3455</SomeNestedData2></SomeData></NewOrderResp></Response>"""

print xml_to_dict(xml_string)

The below variant preserves the parent key / element:

def xml_to_dict(xml_str):
    """ Convert xml to dict, using lxml v3.4.2 xml processing library, see http://lxml.de/ """
    def xml_to_dict_recursion(xml_object):
        dict_object = xml_object.__dict__
        if not dict_object:  # if empty dict returned
            return xml_object
        for key, value in dict_object.items():
            dict_object[key] = xml_to_dict_recursion(value)
        return dict_object
    xml_obj = objectify.fromstring(xml_str)
    return {xml_obj.tag: xml_to_dict_recursion(xml_obj)}

If you want to only return a subtree and convert it to dict, you can use Element.find() to get the subtree and then convert it:

xml_obj.find('.//')  # lxml.objectify.ObjectifiedElement instance

See the lxml docs here. I hope this helps!

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

Since there is no programmatic way to mimic minimal-ui, we have come up with a different workaround, using calc() and known iOS address bar height to our advantage:

The following demo page (also available on gist, more technical details there) will prompt user to scroll, which then triggers a soft-fullscreen (hide address bar/menu), where header and content fills the new viewport.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }

        html {
            background-color: red;
        }

        body {
            background-color: blue;
            margin: 0;
        }

        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }

        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }

        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }

        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }

            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        window.addEventListener('scroll', function(ev) {

            if (timeout) {
                clearTimeout(timeout);
            }

            timeout = setTimeout(function() {

                if (window.scrollY > 0) {
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';
                }

            }, 200);

        });
    </script>
</head>
<body>

    <div class="header">
        <p>header</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>
</html>

How to convert List<Integer> to int[] in Java?

Here is Java 8 single line code for this

public int[] toIntArray(List<Integer> intList){
       return intList.stream().mapToInt(Integer::intValue).toArray();
}

How to get all groups that a user is a member of?

The below works well:

get-aduser $username -Properties memberof | select -expand memberof

If you have a list of users:

$list = 'administrator','testuser1','testuser2'
$list | `
    %{  
        $user = $_; 
        get-aduser $user -Properties memberof | `
        select -expand memberof | `
        %{new-object PSObject -property @{User=$user;Group=$_;}} `
    }

What's the difference between a word and byte?

It seems all the answers assume high level languages and mainly C/C++.

But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:

byte  = 8 bits 
word  = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")

How to suspend/resume a process in Windows?

You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).

Hard Way

First get all the threads of a given process then call the SuspendThread function to stop each one (and ResumeThread to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.

void suspend(DWORD processId)
{
    HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);

    THREADENTRY32 threadEntry; 
    threadEntry.dwSize = sizeof(THREADENTRY32);

    Thread32First(hThreadSnapshot, &threadEntry);

    do
    {
        if (threadEntry.th32OwnerProcessID == processId)
        {
            HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
                threadEntry.th32ThreadID);

            SuspendThread(hThread);
            CloseHandle(hThread);
        }
    } while (Thread32Next(hThreadSnapshot, &threadEntry));

    CloseHandle(hThreadSnapshot);
}

Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.

Undocumented way

Starting from Windows XP there is the NtSuspendProcess but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).

typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);

void suspend(DWORD processId)
{
    HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));

    NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
        GetModuleHandle("ntdll"), "NtSuspendProcess");

    pfnNtSuspendProcess(processHandle);
    CloseHandle(processHandle);
}

"Debugger" Way

To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop.

This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.

void suspend(DWORD processId)
{
    DebugActiveProcess(processId);
}

From Command Line

As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:

Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)

Of course if you need it often you can make an alias for that.

How to submit an HTML form without redirection

See jQuery's post function.

I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.

Also, see the preventDefault function, of jQuery!

nodejs npm global config missing on windows

Have you tried running npm config list? And, if you want to see the defaults, run npm config ls -l.

in iPhone App How to detect the screen resolution of the device

Use it in App Delegate: I am using storyboard

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {

    CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;

    //----------------HERE WE SETUP FOR IPHONE 4/4s/iPod----------------------

    if(iOSDeviceScreenSize.height == 480){          

        UIStoryboard *iPhone35Storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone35Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

        iphone=@"4";

        NSLog(@"iPhone 4: %f", iOSDeviceScreenSize.height);

    }

    //----------------HERE WE SETUP FOR IPHONE 5----------------------

    if(iOSDeviceScreenSize.height == 568){

        // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
        UIStoryboard *iPhone4Storyboard = [UIStoryboard storyboardWithName:@"iPhone5" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone4Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

         NSLog(@"iPhone 5: %f", iOSDeviceScreenSize.height);
        iphone=@"5";
    }

} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    // NSLog(@"wqweqe");
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];

}

 return YES;
 }

Iterating on a file doesn't work the second time

Of course. That is normal and sane behaviour. Instead of closing and re-opening, you could rewind the file.

How to delete a record in Django models?

MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query

DELETE FROM my_models where id=1

What is the most efficient way to store a list in the Django models?

Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends table? I understand that myFriends are just strings but I would think that a better design would be to create a Friend model and have MyClass contain a foreign key realtionship to the resulting table.

How to prevent "The play() request was interrupted by a call to pause()" error?

It looks like a lot of programmers encountered this problem. a solution should be quite simple. media element return Promise from actions so

n.pause().then(function(){
    n.currentTime = 0;
    n.play();
})

should do the trick

How do I make a file:// hyperlink that works in both IE and Firefox?

In case someone else finds this topic while using localhost in the file URIs - Internet Explorer acts completely different if the host name is localhost or 127.0.0.1 - if you use the actual hostname, it works fine (from trusted sites/intranet zone).

Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt but FF requires additional slashes file:////server/share/file.txt.

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

what is the use of $this->uri->segment(3) in codeigniter pagination

CodeIgniter User Guide says:

$this->uri->segment(n)

Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up

The segment numbers would be this:

1. news
2. local
3. metro
4. crime_is_up

So segment refers to your url structure segment. By the above example, $this->uri->segment(3) would be 'metro', while $this->uri->segment(4) would be 'crime_is_up'.

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

How to check whether a int is not null or empty?

int cannot be null. If you are not assigning any value to int default value will be 0. If you want to check for null then make int as Integer in declaration. Then Integer object can be null. So, you can check where it is null or not. Even in javax bean validation you won't be able to get error for @NotNull annotation until the variable is declared as Integer.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

There is a documentation in SLf4J site to resolve this. I followed that and added slf4j-simple-1.6.1.jar to my aplication along with slf4j-api-1.6.1.jar which i already had.This solved my problem

slf4j

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

To install an apk on one of your emulators:

First get the list of devices:

-> adb devices
List of devices attached
25sdfsfb3801745eg        device
emulator-0954   device

Then install the apk on your emulator with the -s flag:

-> adb -s "25sdfsfb3801745eg" install "C:\Users\joel.joel\Downloads\release.apk"
Performing Streamed Install
Success

Ps.: the order here matters, so -s <id> has to come before install command, otherwise it won't work.

Hope this helps someone!

Is there a quick change tabs function in Visual Studio Code?

By default, Ctrl+Tab in Visual Studio Code cycles through tabs in order of most recently used. This is confusing because it depends on hidden state.

Web browsers cycle through tabs in visible order. This is much more intuitive.

To achieve this in Visual Studio Code, you have to edit keybindings.json. Use the Command Palette with CTRL+SHIFT+P, enter "Preferences: Open Keyboard Shortcuts (JSON)", and hit Enter.

Then add to the end of the file:

[
    // ...
    {
        "key": "ctrl+tab",
        "command": "workbench.action.nextEditor"
    },
    {
        "key": "ctrl+shift+tab",
        "command": "workbench.action.previousEditor"
    }
]

Alternatively, to only cycle through tabs of the current window/split view, you can use:

[
    {
        "key": "ctrl+tab",
        "command": "workbench.action.nextEditorInGroup"
    },
    {
        "key": "ctrl+shift+tab",
        "command": "workbench.action.previousEditorInGroup"
    }
]

Alternatively, you can use Ctrl+PageDown (Windows) or Cmd+Option+Right (Mac).

PHP - Fatal error: Unsupported operand types

I guess you want to do this:

$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
   $avg = round($total_rating_points / $total_rating_count, 1);

Understanding slice notation

And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax:

>>> x = [1,2,3,4,5,6]
>>> x[::-1]
[6,5,4,3,2,1]

Easy way to reverse sequences!

And if you wanted, for some reason, every second item in the reversed sequence:

>>> x = [1,2,3,4,5,6]
>>> x[::-2]
[6,4,2]

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

<table align='center' style='text-align:center'>
  <tr>
    <td align='center' style='text-align:center'>
      <!-- AMAZING CONTENT! -->
    </td>
  </tr>
</table>

I only listed some of the key things that resolved my Microsoft email issues.

Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/

It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

ORA-00907: missing right parenthesis

ORA-00907: missing right parenthesis

This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.

Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis and leaves it to us to spot the actual bloomer.

The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.

Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.

In-line declaration doesn't have a comma and doesn't include the referencing column name.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8) 
          CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
    order_id           VARCHAR2 (10) NOT NULL,
          CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)

Table level constraints are a separate component, and so do have a comma and do mention the referencing column.

CREATE TABLE historys_T    (
    history_record    VARCHAR2 (8),
    customer_id       VARCHAR2 (8),    
    order_id           VARCHAR2 (10) NOT NULL,
    CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,   
   CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)

Here is a list of other syntax errors:

  1. The referenced table (and the referenced primary key or unique constraint) must already exist before we can create a foreign key against them. So you cannot create a foreign key for HISTORYS_T before you have created the referenced ORDERS table.
  2. You have misspelled the names of the referenced tables in some of the foreign key clauses (LIBRARY_T and FORMAT_T).
  3. You need to provide an expression in the DEFAULT clause. For DATE columns that is usually the current date, DATE DEFAULT sysdate.

Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).

As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.

  1. You have not named most of your constraints. Oracle will give them a default name but it will be a horrible one, and makes the data dictionary harder to understand. Explicitly naming every constraint helps us navigate the physical database. It also leads to more comprehensible error messages when our SQL trips a constraint violation.
  2. Name your constraints consistently. HISTORY_T has constraints called historys_T_FK and fk_order_id_orders, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk. So history_customer_fk and history_order_fk respectively.
  3. It can be useful to create the constraints with separate statements. Creating tables then primary keys then foreign keys will avoid the problems with dependency ordering identified above.
  4. You are trying to create cyclic foreign keys between LIBRARY_T and FORMATS. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.
  5. Avoid blank lines in your scripts. Some tools will handle them but some will not. We can configure SQL*Plus to handle them but it's better to avoid the need.
  6. The naming convention of LIBRARY_T is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.
  7. T_CUSTOMERS is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers is not a keyword.

Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS and LIBRARY_T my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_ or a _TAB.

Allowed memory size of X bytes exhausted

If by increasing the memory limit you have gotten rid of the error and your code now works, you'll need to take measures to decrease that memory usage. Here are a few things you could do to decrease it:

If you're reading files, read them line-by-line instead of reading in the complete file into memory. Look at fgets and SplFileObject::fgets. Upgrade to a new version of PHP if you're using PHP 5.3. PHP 5.4 and 5.5 use much less memory.

Avoid loading large datasets into in an array. Instead, go for processing smaller subsets of the larger dataset and, if necessary, persist your data into a database to relieve memory use.

Try the latest version or minor version of a third-party library (1.9.3 vs. your 1.8.2, for instance) and use whichever is more stable. Sometimes newer versions of libraries are written more efficiently.

If you have an uncommon or unstable PHP extension, try upgrading it. It might have a memory leak.

If you're dealing with large files and you simply can't read it line-by-line, try breaking the file into many smaller files and process those individually. Disable PHP extensions that you don't need.

In the problem area, unset variables which contain large amounts of data and aren't required later in the code.

FROM: https://www.airpair.com/php/fatal-error-allowed-memory-size

How to map atan2() to degrees 0-360

I have 2 solutions that seem to work for all combinations of positive and negative x and y.

1) Abuse atan2()

According to the docs atan2 takes parameters y and x in that order. However if you reverse them you can do the following:

double radians = std::atan2(x, y);
double degrees = radians * 180 / M_PI;
if (radians < 0)
{
    degrees += 360; 
}

2) Use atan2() correctly and convert afterwards

double degrees = std::atan2(y, x) * 180 / M_PI;
if (degrees > 90)
{
    degrees = 450 - degrees;
}
else
{
    degrees = 90 - degrees;
}

Importing lodash into angular2 + typescript application

Since Typescript 2.0, @types npm modules are used to import typings.

# Implementation package (required to run)
$ npm install --save lodash

# Typescript Description
$ npm install --save @types/lodash 

Now since this question has been answered I'll go into how to efficiently import lodash

The failsafe way to import the entire library (in main.ts)

import 'lodash';

This is the new bit here:

Implementing a lighter lodash with the functions you require

import chain from "lodash/chain";
import value from "lodash/value";
import map from "lodash/map";
import mixin from "lodash/mixin";
import _ from "lodash/wrapperLodash";

source: https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba#.kg6azugbd

PS: The above article is an interesting read on improving build time and reducing app size

Apache Spark: The number of cores vs. the number of executors

There is a small issue in the First two configurations i think. The concepts of threads and cores like follows. The concept of threading is if the cores are ideal then use that core to process the data. So the memory is not fully utilized in first two cases. If you want to bench mark this example choose the machines which has more than 10 cores on each machine. Then do the bench mark.

But dont give more than 5 cores per executor there will be bottle neck on i/o performance.

So the best machines to do this bench marking might be data nodes which have 10 cores.

Data node machine spec: CPU: Core i7-4790 (# of cores: 10, # of threads: 20) RAM: 32GB (8GB x 4) HDD: 8TB (2TB x 4)

What is the list of valid @SuppressWarnings warning names in Java?

It depends on your IDE or compiler.

Here is a list for Eclipse Galileo:

  • all to suppress all warnings
  • boxing to suppress warnings relative to boxing/unboxing operations
  • cast to suppress warnings relative to cast operations
  • dep-ann to suppress warnings relative to deprecated annotation
  • deprecation to suppress warnings relative to deprecation
  • fallthrough to suppress warnings relative to missing breaks in switch statements
  • finally to suppress warnings relative to finally block that don’t return
  • hiding to suppress warnings relative to locals that hide variable
  • incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
  • nls to suppress warnings relative to non-nls string literals
  • null to suppress warnings relative to null analysis
  • restriction to suppress warnings relative to usage of discouraged or forbidden references
  • serial to suppress warnings relative to missing serialVersionUID field for a serializable class
  • static-access to suppress warnings relative to incorrect static access
  • synthetic-access to suppress warnings relative to unoptimized access from inner classes
  • unchecked to suppress warnings relative to unchecked operations
  • unqualified-field-access to suppress warnings relative to field access unqualified
  • unused to suppress warnings relative to unused code

List for Indigo adds:

  • javadoc to suppress warnings relative to javadoc warnings
  • rawtypes to suppress warnings relative to usage of raw types
  • static-method to suppress warnings relative to methods that could be declared as static
  • super to suppress warnings relative to overriding a method without super invocations

List for Juno adds:

  • resource to suppress warnings relative to usage of resources of type Closeable
  • sync-override to suppress warnings because of missing synchronize when overriding a synchronized method

Kepler and Luna use the same token list as Juno (list).

Others will be similar but vary.

Hide vertical scrollbar in <select> element

No, you can't control the look of a select box in such detail.

A select box is usually displayed as a dropdown list, but there is nothing that says that it always has to be displayed that way. How it is displayed depends on the system, and on some mobile phones for example you don't get a dropdown at all, but a selector that covers most or all of the screen.

If you want to control how your form elements look in such detail, you have to make your own form controls out of regular HTML elements (or find someone else who has already done that).

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

When I get this kind of error I had to update the data type by a notch. For Example, if I have it as "tiny int" change it to "small int" ~ Nita

Deleting folders in python recursively

Here's my pure pathlib recursive directory unlinker:

from pathlib import Path

def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    directory.rmdir()

rmdir(Path("dir/"))

Modal width (increase)

Make sure your modal is not placed in a container, try to add the !important annotation if it's not changing the width from the original one.

Spring Boot REST API - request timeout?

The @Transactional annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController

@RequestMapping(value = "/method",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)

"’" showing on page instead of " ' "

The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:

htmlText = htmlText.Replace('–', '-');

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I had the same problem because I changed the user from myself to someone else:

su

For some reason, after did the normal compiling I was not able to execute it (the same error message). Directly ssh to the other user account works.

How do I get sed to read from standard input?

use the --expression option

grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

Execute ssh with password authentication via windows command prompt

PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Undefined symbols for architecture x86_64 on Xcode 6.1

Yes, I think the library you are using is not compatible with 64 bit version but you can solve the problem -

Just navigate to Build Settings>Architectures & replace $(ARCHS_STANDARD) to $(ARCHS_STANDARD_32_BIT)

So that your xcode build your project with 32 bit supported version.

How do you use "git --bare init" repository?

You can execute the following commands to initialize your local repository

mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master

You should work on your project from your local repository and use the server as the central repository.

You can also follow this article which explains each and every aspect of creating and maintaining a Git repository. Git for Beginners

How to find out what type of a Mat object is with Mat::type() in OpenCV

I've added some usability to the function from the answer by @Octopus, for debugging purposes.

void MatType( Mat inputMat )
{
    int inttype = inputMat.type();

    string r, a;
    uchar depth = inttype & CV_MAT_DEPTH_MASK;
    uchar chans = 1 + (inttype >> CV_CN_SHIFT);
    switch ( depth ) {
        case CV_8U:  r = "8U";   a = "Mat.at<uchar>(y,x)"; break;  
        case CV_8S:  r = "8S";   a = "Mat.at<schar>(y,x)"; break;  
        case CV_16U: r = "16U";  a = "Mat.at<ushort>(y,x)"; break; 
        case CV_16S: r = "16S";  a = "Mat.at<short>(y,x)"; break; 
        case CV_32S: r = "32S";  a = "Mat.at<int>(y,x)"; break; 
        case CV_32F: r = "32F";  a = "Mat.at<float>(y,x)"; break; 
        case CV_64F: r = "64F";  a = "Mat.at<double>(y,x)"; break; 
        default:     r = "User"; a = "Mat.at<UKNOWN>(y,x)"; break; 
    }   
    r += "C";
    r += (chans+'0');
    cout << "Mat is of type " << r << " and should be accessed with " << a << endl;

}

Make a VStack fill the width of the screen in SwiftUI

The simplest way I manage to solve the issue was is by using a ZStack + .edgesIgnoringSafeArea(.all)

struct TestView : View {

    var body: some View {
        ZStack() {
            Color.yellow.edgesIgnoringSafeArea(.all)
            VStack {
                Text("Hello World")
            }
        }
    }
}

Add an object to a python list

If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()

How to check if a column exists in a datatable

You can look at the Columns property of a given DataTable, it is a list of all columns in the table.

private void PrintValues(DataTable table)
{
    foreach(DataRow row in table.Rows)
    {
        foreach(DataColumn column in table.Columns)
        {
            Console.WriteLine(row[column]);
        }
    }
}

http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

/usr/local/ssl/openssl.cnf

A path like this means the program has been compiled with either Cygwin or MSYS. If you must use this openssl then you will need an interpreter that understands those paths, like Bash, which is provided by Cygwin or MSYS.

Another option would be to download or compile a Windows Native version of openssl. Using that the program would instead require a path like

C:\Users\Steven\ssl\openssl.cnf

which would be better suited for the Command Prompt.

How to find a whole word in a String in java

Looking back at the original question, we need to find some given keywords in a given sentence, count the number of occurrences and know something about where. I don't quite understand what "where" means (is it an index in the sentence?), so I'll pass that one... I'm still learning java, one step at a time, so I'll see to that one in due time :-)

It must be noticed that common sentences (as the one in the original question) can have repeated keywords, therefore the search cannot just ask if a given keyword "exists or not" and count it as 1 if it does exist. There can be more then one of the same. For example:

// Base sentence (added punctuation, to make it more interesting):
String sentence = "Say that 123 of us will come by and meet you, "
                + "say, at the woods of 123woods.";

// Split it (punctuation taken in consideration, as well):
java.util.List<String> strings = 
                       java.util.Arrays.asList(sentence.split(" |,|\\."));

// My keywords:
java.util.ArrayList<String> keywords = new java.util.ArrayList<>();
keywords.add("123woods");
keywords.add("come");
keywords.add("you");
keywords.add("say");

By looking at it, the expected result would be 5 for "Say" + "come" + "you" + "say" + "123woods", counting "say" twice if we go lowercase. If we don't, then the count should be 4, "Say" being excluded and "say" included. Fine. My suggestion is:

// Set... ready...?
int counter = 0;

// Go!
for(String s : strings)
{
    // Asking if the sentence exists in the keywords, not the other
    // around, to find repeated keywords in the sentence.
    Boolean found = keywords.contains(s.toLowerCase());
    if(found)
    {
        counter ++;
        System.out.println("Found: " + s);
    }
}

// Statistics:
if (counter > 0)
{
    System.out.println("In sentence: " + sentence + "\n"
                     + "Count: " + counter);
}

And the results are:

Found: Say
Found: come
Found: you
Found: say
Found: 123woods
In sentence: Say that 123 of us will come by and meet you, say, at the woods of 123woods.
Count: 5

MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}