Programs & Examples On #Forward

There are myriad kinds of forwarding. Use this if you must, but try to find a more specific [tag] first.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.

RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

No such keg: /usr/local/Cellar/git

Give another go at force removing the brewed version of git

brew uninstall --force git

Then cleanup any older versions and clear the brew cache

brew cleanup -s git

Remove any dead symlinks

brew cleanup --prune-prefix

Then try reinstalling git

brew install git

If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix directory (/usr/local by default), you can simply rm -rf $(brew --prefix). Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh

Calling JMX MBean method from a shell script

You might want also to have a look at jmx4perl. It provides java-less access to a remote Java EE Server's MBeans. However, a small agent servlet needs to be installed on the target platform, which provides a restful JMX Access via HTTP with a JSON payload. (Version 0.50 will add an agentless mode by implementing a JSR-160 proxy).

Advantages are quick startup times compared to launching a local java JVM and ease of use. jmx4perl comes with a full set of Perl modules which can be easily used in your own scripts:

use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias;   # Import certains aliases for MBeans

print "Memory Used: ",
      JMX::Jmx4Perl
          ->new(url => "http://localhost:8080/j4p")
          ->get_attribute(MEMORY_HEAP_USED);

You can also use alias for common MBean/Attribute/Operation combos (e.g. for most MXBeans). For additional features (Nagios-Plugin, XPath-like access to complex attribute types, ...), please refer to the documentation of jmx4perl.

Open text file and program shortcut in a Windows batch file

I was able to figure out the solution:

start notepad "myfile.txt"
"myshortcut.lnk"
exit

Is it possible to hide/encode/encrypt php source code and let others have the system?

Yes, you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.

But these 'others' can also decode/decrypt the source code using other tools and services found online. So you cannot 100% protect your code, what you can do is, make it tougher for someone to reverse engineer your code.

Most of these tools above support Encoding and Obfuscating.

  • Encoding will hide your code by encrypting it.
  • Obfuscating will make your code difficult to understand.

You can choose to use both (Encoding and Obfuscating) or either one, depending on your needs.

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Virtual box version 4.3.28 worked with Genymotion 2.5.2 for me. Nothing else seemed to work.

Execute Shell Script after post build in Jenkins

You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.

if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
  lastStableBuild = item.getLastStableBuild()
  lastStableDate = lastStableBuild.getTime()
  formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
  now = new Date()
  formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
  command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
  manager.listener.logger.println "FOB Command: ${command}"
  manager.listener.logger.println command.execute().text
}

(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

this happened to me when I imported an Android Studio App into eclipse.

I figured out the andoridmanifest.xml file needs to be slightly modified when importing from android studio project. I created a new test project, and copied over the headings to make it match. voila, issue solved.

Open a folder using Process.Start

Have you made sure that the folder "c:\teste" exists? If it doesn't, explorer will open showing some default folder (in my case "C:\Users\[user name]\Documents").

Update

I have tried the following variations:

// opens the folder in explorer
Process.Start(@"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", @"c:\temp");
// throws exception
Process.Start(@"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", @"c:\does_not_exist");

If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:

  • Open the Run dialog, enter "explorer.exe" and hit enter
  • Open a command prompt, type "explorer.exe" and hit enter

How to delete the first row of a dataframe in R?

While I agree with the most voted answer, here is another way to keep all rows except the first:

dat <- tail(dat, -1)

This can also be accomplished using Hadley Wickham's dplyr package.

dat <- dat %>% slice(-1)

What is the difference between a symbolic link and a hard link?

Also:

  1. Read performance of hard links is better than symbolic links (micro-performance)
  2. Symbolic links can be copied, version-controlled, ..etc. In another words, they are an actual file. On the other end, a hard link is something at a slightly lower level and you will find that compared to symbolic links, there are less tools that provide means for working with the hard links as hard links and not as normal files

How do implement a breadth first traversal?

public void breadthFirstSearch(Node root, Consumer<String> c) {
    List<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
        Node n = queue.remove(0);
        c.accept(n.value);

        if (n.left != null)
            queue.add(n.left);
        if (n.right != null)
            queue.add(n.right);
    }
}

And the Node:

public static class Node {
    String value;
    Node left;
    Node right;

    public Node(final String value, final Node left, final Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

How to use NSJSONSerialization

@rckoenes already showed you how to correctly get your data from the JSON string.

To the question you asked: EXC_BAD_ACCESS almost always comes when you try to access an object after it has been [auto-]released. This is not specific to JSON [de-]serialization but, rather, just has to do with you getting an object and then accessing it after it's been released. The fact that it came via JSON doesn't matter.

There are many-many pages describing how to debug this -- you want to Google (or SO) obj-c zombie objects and, in particular, NSZombieEnabled, which will prove invaluable to you in helping determine the source of your zombie objects. ("Zombie" is what it's called when you release an object but keep a pointer to it and try to reference it later.)

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

Importing CommonCrypto in a Swift framework

WARNING: iTunesConnect may reject apps that are using this method.


New member on my team accidentally broke the solution given by one of the top answers, so I decided to consolidate it in a small wrapper project called CommonCryptoModule. You can install it manually or via Cocoapods:

pod 'CommonCryptoModule', '~> 1.0.2'

Then, all you have to do is to import the module where you need CommonCrypto, like so:

import CommonCryptoModule

Hope someone else finds this useful.

The page cannot be displayed because an internal server error has occurred on server

I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:

  <configuration>
  <system.webServer>
    <applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
      <add initializationPage="/init1.aspx?call=2"/>
      <add initializationPage="/init1.aspx?call=2" />
    </applicationInitialization>
  </system.webServer>

Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Hope this Helps:

public String getSystemTimeInBelowFormat() {
    String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
    return timestamp;
}

Error: could not find function ... in R

If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.

You can solve this by adding the following statement to the NAMESPACE:

exportPattern("^[^\\\\.]")

This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:

.myHiddenFunction <- function(x) cat("my hidden function")

Why does Eclipse Java Package Explorer show question mark on some classes?

those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:

image describing Eclipse icons for Egit

  • dirty (folder) - At least one file below the folder is dirty; that means that it has changes in the working tree that are neither in the index nor in the repository.
  • tracked - The resource is known to the Git repository. untracked - The resource is not known to the Git repository.
  • ignored - The resource is ignored by the Git team provider. Here only the preference settings under Team -> Ignored Resources and the "derived" flag are relevant. The .gitignore file is not taken into account.
  • dirty - The resource has changes in the working tree that are neither in the index nor in the repository.
  • staged - The resource has changes which are added to the index. Not that adding to the index is possible at the moment only on the commit dialog on the context menu of a resource.
  • partially-staged - The resource has changes which are added to the index and additionally changes in the working tree that are neither in the index nor in the repository.
  • added - The resource is not yet tracked by but added to the Git repository.
  • removed - The resource is staged for removal from the Git repository.
  • conflict - A merge conflict exists for the file.
  • assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index--assume-unchanged).

Webfont Smoothing and Antialiasing in Firefox and Opera

Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda

Surprising solution -
adding following property to the applied selectors:

selector {
    text-shadow: 0 0 0;
}

Actually, result is the same just with text-shadow: 0 0;, but I like to explicitly set blur-radius.

It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.

open link of google play store in mobile version android

Below code may helps you for display application link of google play sore in mobile version.

For Application link :

Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

  try {
        startActivity(myAppLinkToMarket);

      } catch (ActivityNotFoundException e) {

        //the device hasn't installed Google Play
        Toast.makeText(Setting.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();
              }

For Developer link :

Uri uri = Uri.parse("market://search?q=pub:" + YourDeveloperName);
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

            try {

                startActivity(myAppLinkToMarket);

            } catch (ActivityNotFoundException e) {

                //the device hasn't installed Google Play
                Toast.makeText(Settings.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();

            } 

trying to align html button at the center of the my page

Make all parent element with 100% width and 100% height and use display: table; and display:table-cell;, check the working sample.

Working Git Version

<!DOCTYPE html>
<html>
<head>
<style>
html,body{height: 100%;}
body{width: 100%;}
</style>
</head>
<body style="display: table; background-color: #ff0000; ">

<div style="display: table-cell; vertical-align: middle; text-align: center;">
    <button type="button" style="text-align: center;" class="btn btn-info">
       Discover More
    </button>
</div>

</body>
</html>

How to run certain task every day at a particular time using ScheduledExecutorService?

If you don't have the luxury of being able to use Java 8, the following will do what you need:

public class DailyRunnerDaemon
{
   private final Runnable dailyTask;
   private final int hour;
   private final int minute;
   private final int second;
   private final String runThreadName;

   public DailyRunnerDaemon(Calendar timeOfDay, Runnable dailyTask, String runThreadName)
   {
      this.dailyTask = dailyTask;
      this.hour = timeOfDay.get(Calendar.HOUR_OF_DAY);
      this.minute = timeOfDay.get(Calendar.MINUTE);
      this.second = timeOfDay.get(Calendar.SECOND);
      this.runThreadName = runThreadName;
   }

   public void start()
   {
      startTimer();
   }

   private void startTimer();
   {
      new Timer(runThreadName, true).schedule(new TimerTask()
      {
         @Override
         public void run()
         {
            dailyTask.run();
            startTimer();
         }
      }, getNextRunTime());
   }


   private Date getNextRunTime()
   {
      Calendar startTime = Calendar.getInstance();
      Calendar now = Calendar.getInstance();
      startTime.set(Calendar.HOUR_OF_DAY, hour);
      startTime.set(Calendar.MINUTE, minute);
      startTime.set(Calendar.SECOND, second);
      startTime.set(Calendar.MILLISECOND, 0);

      if(startTime.before(now) || startTime.equals(now))
      {
         startTime.add(Calendar.DATE, 1);
      }

      return startTime.getTime();
   }
}

It doesn't require any external libs, and will account for daylight savings. Simply pass in the time of day you want to run the task as a Calendar object, and the task as a Runnable. For example:

Calendar timeOfDay = Calendar.getInstance();
timeOfDay.set(Calendar.HOUR_OF_DAY, 5);
timeOfDay.set(Calendar.MINUTE, 0);
timeOfDay.set(Calendar.SECOND, 0);

new DailyRunnerDaemon(timeOfDay, new Runnable()
{
   @Override
   public void run()
   {
      try
      {
        // call whatever your daily task is here
        doHousekeeping();
      }
      catch(Exception e)
      {
        logger.error("An error occurred performing daily housekeeping", e);
      }
   }
}, "daily-housekeeping");

N.B. the timer task runs in a Daemon thread which is not recommended for doing any IO. If you need to use a User thread, you will need to add another method which cancels the timer.

If you have to use a ScheduledExecutorService, simply change the startTimer method to the following:

private void startTimer()
{
   Executors.newSingleThreadExecutor().schedule(new Runnable()
   {
      Thread.currentThread().setName(runThreadName);
      dailyTask.run();
      startTimer();
   }, getNextRunTime().getTime() - System.currentTimeMillis(),
   TimeUnit.MILLISECONDS);
}

I am not sure of the behaviour but you may need a stop method which calls shutdownNow if you go down the ScheduledExecutorService route, otherwise your application may hang when you try to stop it.

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

CSS Layout - Dynamic width DIV

Or, if you know the width of the two "side" images and don't want to deal with floats:

<div class="container">
    <div class="left-panel"><img src="myleftimage" /></div>
    <div class="center-panel">Content goes here...</div>
    <div class="right-panel"><img src="myrightimage" /></div>
</div>

CSS:

.container {
    position:relative;
    padding-left:50px;
    padding-right:50px;
}

.container .left-panel {
    width: 50px;
    position:absolute;
    left:0px;
    top:0px;
}

.container .right-panel {
    width: 50px;
    position:absolute;
    right:0px;
    top:0px;
}

.container .center-panel {
    background: url('mymiddleimage');
}

Notes:

Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

Why can't I reference System.ComponentModel.DataAnnotations?

I had same problem, I solved this problem by following way.

Right click on page, select Property. in build action select Content.

Hope that this solution may help you.

Clearing state es6 React

class MyComponent extends Component {
 constructor(props){
  super(props)
   this.state = {
     inputVal: props.inputValue
  }
   // preserve the initial state in a new object
   this.baseState = this.state 
}
  resetForm = () => {
    this.setState(this.baseState)
  }

}

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

How to go to each directory and execute a command?

  #!/bin.bash
for folder_to_go in $(find . -mindepth 1 -maxdepth 1 -type d \( -name "*" \) ) ; 
                                    # you can add pattern insted of * , here it goes to any folder 
                                    #-mindepth / maxdepth 1 means one folder depth   
do
cd $folder_to_go
  echo $folder_to_go "########################################## "
  
  whatever you want to do is here

cd ../ # if maxdepth/mindepath = 2,  cd ../../
done

#you can try adding many internal for loops with many patterns, this will sneak anywhere you want

Check if array is empty or null

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

XAMPP Apache Webserver localhost not working on MAC OS

This is because in Mac OS X there is already Apache pre-installed. So what you can do is to change the listening port of one of the Apaches, either the Apache that you installed with XAMPP or the pre-installed one.

To change the listening port for XAMPP's Apache, go to /Applications/XAMPP/xamppfiles/etc and edit httpd.conf. Change the line "Listen 80" (80 is the listening port) to other port, eg. "Listen 1234".

Or,

To change the one for pre-installed Apache, go to /etc/apache2. You can do the same thing with file httpd.conf there.

After changing you might need to restart your Mac, just to make sure.

How to turn off INFO logging in Spark?

The way I do it is:

in the location I run the spark-submit script do

$ cp /etc/spark/conf/log4j.properties .
$ nano log4j.properties

change INFO to what ever level of logging you want and then run your spark-submit

How can I check if character in a string is a letter? (Python)

You can use str.isalpha().

For example:

s = 'a123b'

for char in s:
    print(char, char.isalpha())

Output:

a True
1 False
2 False
3 False
b True

Is there a way to create key-value pairs in Bash script?

in older bash (or in sh) that does not support declare -A, following style can be used to emulate key/value

# key
env=staging


# values
image_dev=gcr.io/abc/dev
image_staging=gcr.io/abc/stage
image_production=gcr.io/abc/stable

img_var_name=image_$env

# active_image=${!var_name}
active_image=$(eval "echo \$$img_var_name")

echo $active_image

Upgrading React version and it's dependencies by reading package.json

you can update all of the dependencies to their latest version by npm update

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

How to handle windows file upload using Selenium WebDriver?

Below code works for me :

public void test() {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.freepdfconvert.com/pdf-word");
    driver.findElement(By.id("clientUpload")).click();
    driver.switchTo()
            .activeElement()
            .sendKeys(
                    "/home/likewise-open/GLOBAL/123/Documents/filename.txt");
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    driver.findElement(By.id("convertButton"));

How can I use "." as the delimiter with String.split() in java

String.split takes a regex, and '.' has a special meaning for regexes.

You (probably) want something like:

String[] words = line.split("\\.");

Some folks seem to be having trouble getting this to work, so here is some runnable code you can use to verify correct behaviour.

import java.util.Arrays;

public class TestSplit {
  public static void main(String[] args) {
    String line = "aa.bb.cc.dd";
    String[] words = line.split("\\.");
    System.out.println(Arrays.toString(words));
    // Output is "[aa, bb, cc, dd]"
  }
}

how to get last insert id after insert query in codeigniter active record

**Inside Model**
function add_info($data){
   $this->db->insert('tbl_user_info',$data);
   $last_id = $this->db->insert_id();
   return  $last_id;
}

**Inside Controller**
public function save_user_record() {
  $insertId =  $this->welcome_model->save_user_info($data);
  echo $insertId->id;
}

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

How to add dll in c# project

Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.

edit

I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.

VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.

How to install "ifconfig" command in my ubuntu docker image?

I came here because I was trying to use ifconfig on the container to find its IPAaddress and there was no ifconfig. If you really need ifconfig on the container go with @vishnu-narayanan answer above, however you may be able to get the information you need by using docker inspect on the host:

docker inspect <containerid>

There is lots of good stuff in the output including IPAddress of container:

"Networks": {
    "bridge": {
        "IPAMConfig": null,
        "Links": null,
        "Aliases": null,
        "NetworkID": "12345FAKEID",
        "EndpointID": "12345FAKEENDPOINTID",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.3",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "MacAddress": "01:02:03:04:05:06",
        "DriverOpts": null
    }
}

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

Can you target an elements parent element using event.target?

var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ;  i<_RemoveBtn.length ; i++){
    _RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
    console.log(event.currentTarget.parentNode);    
}

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

.htaccess rewrite subdomain to directory

Try to putting this .htaccess file on subdomain folder:

RewriteEngine On

RewriteRule ^(.*)?$ ./subdomains/sub/$1

It redirects to http://domain.com/subdomains/sub/, when you only want it to show http://sub.domain.com/

Android XML Percent Symbol

To allow the app using formatted strings from resources you should correct your xml. So, for example

<string name="app_name">Your App name, ver.%d</string>

should be replaced with

<string name="app_name">Your App name, ver.%1$d</string>

You can see this for details.

How do I handle newlines in JSON?

I guess this is what you want:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

(You need to escape the "\" in your string (turning it into a double-"\"), otherwise it will become a newline in the JSON source, not the JSON data.)

Include CSS,javascript file in Yii Framework

In Yii framework, You can include js and css using below method.

Including CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template.

Getting HTTP code in PHP using curl

Here is my solution need get Status Http for checking status of server regularly

$url = 'http://www.example.com'; // Your server link

while(true) {

    $strHeader = get_headers($url)[0];

    $statusCode = substr($strHeader, 9, 3 );

    if($statusCode != 200 ) {
        echo 'Server down.';
        // Send email 
    }
    else {
        echo 'oK';
    }

    sleep(30);
}

How can I select an element with multiple classes in jQuery?

For better performance you can use

$('div.a.b')

This will look only through the div elements instead of stepping through all the html elements that you have on your page.

Mac install and open mysql using terminal

(Updated for 2017)

When you installed MySQL it generated a password for the root user. You can connect using

/usr/local/mysql/bin/mysql -u root -p

and type in the generated password.

Previously, the root user in MySQL used to not have a password and could only connect from localhost. So you would connect using

/usr/local/mysql/bin/mysql -u root

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

I had surprising luck with with simple:

body {
    height: 100vh;
}

It works great to disable overscroll for pop-ups or menus and it doesn't force browser bars to appear like when using position:fixed. BUT - you need to save scroll position before setting fixed height and restore it when hiding the pop-up, otherwise, browser will scroll to top.

Can I use break to exit multiple nested 'for' loops?

goto can be very helpful for breaking nested loops

for (i = 0; i < 1000; i++) {
    for (j = 0; j < 1000; j++) {
        for (k = 0; k < 1000; k++) {
             for (l = 0; l < 1000; l++){
                ....
                if (condition)
                    goto break_me_here;
                ....
            }
        }
    }
}

break_me_here:
// Statements to be executed after code breaks at if condition

How to format a string as a telephone number in C#

Try this

string result;
if ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )
    result = string.Format("{0:(###)###-"+new string('#',phoneNumber.Length-6)+"}",
    Convert.ToInt64(phoneNumber)
    );
else
    result = phoneNumber;
return result;

Cheers.

How should I validate an e-mail address?

Don't use a reg-ex.

Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "[email protected]", as will org.apache.commons.validator.routines.EmailValidator)

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.

If you want to perform some basic checks you could just check that it's in the form *@*

If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

How to hide a mobile browser's address bar?

This should be the code you need to hide the address bar:

window.addEventListener("load",function() {
    setTimeout(function(){
        // This hides the address bar:
        window.scrollTo(0, 1);
    }, 0);
});

Also nice looking Pokedex by the way! Hope this helps!

How to convert Moment.js date to users local timezone?

Use utcOffset function.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00

Convert a JSON String to a HashMap

Brief and Useful:

/**
 * @param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
 *                     a <code>Boolean</code>, a <code>Number</code>,
 *                     a <code>null</code> or a <code>JSONObject.NULL</code>.
 * @return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
 * a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
 */
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
    if (jsonThing instanceof JSONArray) {
        final ArrayList<Object> list = new ArrayList<>();

        final JSONArray jsonArray = (JSONArray) jsonThing;
        final int l = jsonArray.length();
        for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
        return list;
    }

    if (jsonThing instanceof JSONObject) {
        final HashMap<String, Object> map = new HashMap<>();

        final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
        while (keysItr.hasNext()) {
            final String key = keysItr.next();
            map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
        }
        return map;
    }

    if (JSONObject.NULL.equals(jsonThing)) return null;

    return jsonThing;
}

Thank @Vikas Gupta.

What is the proper way to format a multi-line dict in Python?

From my experience with tutorials, and other things number 2 always seems preferred, but it's a personal preference choice more than anything else.

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

What is a database transaction?

Here's a simple explanation. You need to transfer 100 bucks from account A to account B. You can either do:

accountA -= 100;
accountB += 100;

or

accountB += 100;
accountA -= 100;

If something goes wrong between the first and the second operation in the pair you have a problem - either 100 bucks have disappeared, or they have appeared out of nowhere.

A transaction is a mechanism that allows you to mark a group of operations and execute them in such a way that either they all execute (commit), or the system state will be as if they have not started to execute at all (rollback).

beginTransaction;
accountB += 100;
accountA -= 100;
commitTransaction;

will either transfer 100 bucks or leave both accounts in the initial state.

Sql Server trigger insert values from new row into another table

You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.

Delete triggers have access to a similar logical table called DELETED.

Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.

Convert Variable Name to String?

Totally possible with the python-varname package (python3):

from varname import nameof

s = 'Hey!'

print (nameof(s))

Output:

s

Get the package here:

https://github.com/pwwang/python-varname

How to draw a graph in PHP?

You can use google's chart api to generate charts.

How to select last two characters of a string

var member = "my name is maanu";

var answer=member.substring(0,member.length - 2);

alert(answer);

Make more than one chart in same IPython Notebook cell

You can also call the show() function after each plot. e.g

   plt.plot(a)
   plt.show()
   plt.plot(b)
   plt.show()

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
        data.push({
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]
        });
    }

jQuery.ajax({
    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {
...

Now inside php when you do this

print_r($_POST);

You will get ..

Array
(
    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
        (
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75
        )
)

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

How to get an isoformat datetime string including the default timezone?

With arrow:

>>> import arrow
>>> arrow.now().isoformat()
'2015-04-17T06:36:49.463207-05:00'
>>> arrow.utcnow().isoformat()
'2015-04-17T11:37:17.042330+00:00'

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

How to outline text in HTML / CSS

With HTML5's support for svg, you don't need to rely on shadow hacks.

_x000D_
_x000D_
<svg  width="100%" viewBox="0 0 600 100">_x000D_
<text x=0 y=20 font-size=12pt fill=white stroke=black stroke-width=0.75>_x000D_
    This text exposes its vector representation, _x000D_
    making it easy to style shape-wise without hacks. _x000D_
    HTML5 supports it, so no browser issues. Only downside _x000D_
    is that svg has its own quirks and learning curve _x000D_
    (c.f. bounding box issue/no typesetting by default)_x000D_
</text>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Python pip install module is not found. How to link python to pip location?

For me the problem was that I had weird configuration settings in file pydistutils.cfg

Try running rm ~/.pydistutils.cfg

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

Data binding to SelectedItem in a WPF Treeview

It can also be done using the IsSelected property of the TreeView item. Here's how I managed it,

public delegate void TreeviewItemSelectedHandler(TreeViewItem item);
public class TreeViewItem
{      
  public static event TreeviewItemSelectedHandler OnItemSelected = delegate { };
  public bool IsSelected 
  {
    get { return isSelected; }
    set 
    { 
      isSelected = value;
      if (value)
        OnItemSelected(this);
    }
  }
}

Then in the ViewModel that contains the data your TreeView is bound to, just subscribe to the event in the TreeViewItem class.

TreeViewItem.OnItemSelected += TreeViewItemSelected;

And finally, implement this handler in the same ViewModel,

private void TreeViewItemSelected(TreeViewItem item)
{
  //Do something
}

And the binding of course,

<Setter Property="IsSelected" Value="{Binding IsSelected}" />    

How to check if a Docker image with a specific tag exist locally?

Just a bit from me to very good readers:

Build

#!/bin/bash -e
docker build -t smpp-gateway smpp
(if  [ $(docker ps -a | grep smpp-gateway | cut -d " " -f1) ]; then \
  echo $(docker rm -f smpp-gateway); \
else \
  echo OK; \
fi;);
docker run --restart always -d --network="host" --name smpp-gateway smpp-gateway:latest

Watch

docker logs --tail 50 --follow --timestamps smpp-gateway

Run

sudo docker exec -it \
$(sudo docker ps | grep "smpp-gateway:latest" | cut -d " " -f1) \
/bin/bash

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Delete the node_modules folder

Then you should run the commands:

npm install --no-bin-links

npm run dev

It's worked on my Laravel 5.5 and Windows.

Input button target="_blank" isn't causing the link to load in a new window/tab

The formtarget attribute is only used for buttons with type="submit".

That is from this reference.

Here is an answer using JavaScript:

<input type="button" onClick="openNewTab()" value="facebook">

<script type="text/javascript">
    function openNewTab() {
        window.open("http://www.facebook.com/");
    }
</script>

svn cleanup: sqlite: database disk image is malformed

I fixed this for an instance of it happening to me by deleting the hidden .svn folder and then performing a checkout on the folder to the same URL.

This did not overwrite any of my modified files & just versioned all of the existing files instead of grabbing fresh copies from the server.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Faced the same problem and solved it by editing my build.gradle file on the dependencies section, removing:

compile 'com.google.android.gms:play-services:7.8.0'

And replacing it with:

compile 'com.google.android.gms:play-services-location:7.8.0'
compile 'com.google.android.gms:play-services-analytics:7.8.0' 

how to get the value of a textarea in jquery?

You don't need to use textarea#message

var message = $('textarea#message').val();

You can directly use

var message = $('#message').val();

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

How do I open a second window from the first window in WPF?

When you have created a new WPF application you should have a .xaml file and a .cs file. These represent your main window. Create an additional .xaml file and .cs file to represent your sub window.

MainWindow.xaml

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Open Window" Click="ButtonClicked" Height="25" HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1" VerticalAlignment="Top" Width="100" />
    </Grid>
</Window>

MainWindow.xaml.cs

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

    private void ButtonClicked(object sender, RoutedEventArgs e)
    {
        SubWindow subWindow = new SubWindow();
        subWindow.Show();
    }
}

Then add whatever additional code you need to these classes:

SubWindow.xaml
SubWindow.xaml.cs

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The solution can be found here https://github.com/spring-projects/spring-framework/issues/22734

you can create two separate post request mappings. For example.

@PostMapping(path = "/test", consumes = "application/json")
public String test(@RequestBody User user) {
  return user.toString();
}

@PostMapping(path = "/test", consumes = "application/x-www-form-urlencoded")
public String test(User user) {
  return user.toString();
}

In reactJS, how to copy text to clipboard?

<input
value={get(data, "api_key")}
styleName="input-wrap"
title={get(data, "api_key")}
ref={apikeyObjRef}
/>
  <div
onClick={() => {
  apikeyObjRef.current.select();
  if (document.execCommand("copy")) {
    document.execCommand("copy");
  }
}}
styleName="copy"
>
  ??
</div>

Recursive sub folder search and return files in a list python

Its not the most pythonic answer, but I'll put it here for fun because it's a neat lesson in recursion

def find_files( files, dirs=[], extensions=[]):
    new_dirs = []
    for d in dirs:
        try:
            new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
        except OSError:
            if os.path.splitext(d)[1] in extensions:
                files.append(d)

    if new_dirs:
        find_files(files, new_dirs, extensions )
    else:
        return

On my machine I have two folders, root and root2

mender@multivax ]ls -R root root2
root:
temp1 temp2

root/temp1:
temp1.1 temp1.2

root/temp1/temp1.1:
f1.mid

root/temp1/temp1.2:
f.mi  f.mid

root/temp2:
tmp.mid

root2:
dummie.txt temp3

root2/temp3:
song.mid

Lets say I want to find all .txt and all .mid files in either of these directories, then I can just do

files = []
find_files( files, dirs=['root','root2'], extensions=['.mid','.txt'] )
print(files)

#['root2/dummie.txt',
# 'root/temp2/tmp.mid',
# 'root2/temp3/song.mid',
# 'root/temp1/temp1.1/f1.mid',
# 'root/temp1/temp1.2/f.mid']

Java Does Not Equal (!=) Not Working?

you can use equals() method to statisfy your demands. == in java programming language has a different meaning!

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<?php
 include 'cdb.php';
$show=mysqli_query( $conn,"SELECT *FROM 'reg'");


while($row1= mysqli_fetch_array($show)) 

{

                 $id=$row1['id'];
                $Name= $row1['name'];
                $email = $row1['email'];
                $username = $row1['username'];
                $password= $row1['password'];
                $birthm = $row1['bmonth'];
                $birthd= $row1['bday'];
                $birthy= $row1['byear'];
                $gernder = $row1['gender'];
                $phone= $row1['phone'];
                $image=$row1['image'];
}


?>


<html>
<head><title>hey</head></title></head>

<body>

<form>
<table border="-2" bgcolor="pink" style="width: 12px; height: 100px;" >

    <th>
    id<input type="text" name="" style="width: 30px;" value= "<?php echo $row1['id']; ?>"  >
</th>

<br>
<br>

    <th>

 name <input type="text" name=""  style="width: 60px;" value= "<?php echo $row1['Name']; ?>" >
</th>

<th>
 email<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['email']; ?>"  >
</th>
<th>
    username<input type="hidden" name="" style="width: 60px;"  value= "<?php echo $username['email']; ?>" >
</th>
<th>
    password<input type="hidden" name="" style="width: 60px;"  value= "<?php echo $row1['password']; ?>">
</ths>

<th>
    birthday month<input type="text" name="" style="width: 60px;"  value= "<?php echo $row1['birthm']; ?>">
</th>
<th>
   birthday day<input type="text" name="" style="width: 60px;"  value= "<?php echo $row1['birthd']; ?>">
</th>
<th>
       birthday year<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthy']; ?>" >
</th>
<th>
    gender<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['gender']; ?>">
</th>
<th>
    phone number<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['phone']; ?>">
</th>
<th>
    <th>
     image<input type="text" name="" style="width: 60px;"  value= "<?php echo $row1['image']; ?>">
</th>

<th>

<font color="pink"> <a href="update.php">update</a></font>

</th>
</table>

</body>
</form>
</body>
</html>

How do I view executed queries within SQL Server Management Studio?

More clear query, targeting Studio sql queries is :

SELECT text  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) 
  where program_name like '%Query'

How to generate and validate a software license key?

There are many ways to generate license keys, but very few of those ways are truly secure. And it's a pity, because for companies, license keys have almost the same value as real cash.

Ideally, you would want your license keys to have the following properties:

  1. Only your company should be able to generate license keys for your products, even if someone completely reverse engineers your products (which WILL happen, I speak from experience). Obfuscating the algorithm or hiding an encryption key within your software is really out of the question if you are serious about controlling licensing. If your product is successful, someone will make a key generator in a matter of days from release.

  2. A license key should be useable on only one computer (or at least you should be able to control this very tightly)

  3. A license key should be short and easy to type or dictate over the phone. You don't want every customer calling the technical support because they don't understand if the key contains a "l" or a "1". Your support department would thank you for this, and you will have lower costs in this area.

So how do you solve these challenges ?

  1. The answer is simple but technically challenging: digital signatures using public key cryptography. Your license keys should be in fact signed "documents", containing some useful data, signed with your company's private key. The signatures should be part of the license key. The product should validate the license keys with the corresponding public key. This way, even if someone has full access to your product's logic, they cannot generate license keys because they don't have the private key. A license key would look like this: BASE32(CONCAT(DATA, PRIVATE_KEY_ENCRYPTED(HASH(DATA)))) The biggest challenge here is that the classical public key algorithms have large signature sizes. RSA512 has an 1024-bit signature. You don't want your license keys to have hundreds of characters. One of the most powerful approaches is to use elliptic curve cryptography (with careful implementations to avoid the existing patents). ECC keys are like 6 times shorter than RSA keys, for the same strength. You can further reduce the signature sizes using algorithms like the Schnorr digital signature algorithm (patent expired in 2008 - good :) )

  2. This is achievable by product activation (Windows is a good example). Basically, for a customer with a valid license key, you need to generate some "activation data" which is a signed message embedding the computer's hardware id as the signed data. This is usually done over the internet, but only ONCE: the product sends the license key and the computer hardware id to an activation server, and the activation server sends back the signed message (which can also be made short and easy to dictate over the phone). From that moment on, the product does not check the license key at startup, but the activation data, which needs the computer to be the same in order to validate (otherwise, the DATA would be different and the digital signature would not validate). Note that the activation data checking do not require verification over the Internet: it is sufficient to verify the digital signature of the activation data with the public key already embedded in the product.

  3. Well, just eliminate redundant characters like "1", "l", "0", "o" from your keys. Split the license key string into groups of characters.

GridView Hide Column by code

If you wanna hide that column while grid populating, you can do it in aspx page itself like this

<asp:BoundField DataField="test" HeaderText="test" Visible="False" />

How do you get the Git repository's name in some Git repository?

Well, if, for the repository name you mean the Git root directory name (the one that contains the .git directory) you can run this:

basename `git rev-parse --show-toplevel`

The git rev-parse --show-toplevel part gives you the path to that directory and basename strips the first part of the path.

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

Ignore parent padding

Easy fix, just do

margin:-10px

on the hr.

javascript functions to show and hide divs

I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

Token Authentication vs. Cookies

I believe that there is some confusion here. The significant difference between cookie based authentication and what is now possible with HTML5 Web Storage is that browsers are built to send cookie data whenever they are requesting resources from the domain that set them. You can't prevent that without turning off cookies. Browsers do not send data from Web Storage unless code in the page sends it. And pages can only access data that they stored, not data stored by other pages.

So, a user worried about the way that their cookie data might be used by Google or Facebook might turn off cookies. But, they have less reason to turn off Web Storage (until the advertisers figure a way to use that as well).

So, that's the difference between cookie based and token based, the latter uses Web Storage.

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

Using variable in SQL LIKE statement

But in my opinion one important thing.

The "char(number)" it's lenght of variable.

If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:

DECLARE @variable char(5)
SET @variable = 'Test1%'
SELECT * FROM table WHERE Name like @variable

the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )

The rest of potential interested data like [Test11..Test200] will not be returned in the result.

It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).

In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:

DECLARE @variable varchar(max)
SET @variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like @variable

This returns (Test1 but also Test11..Test19 and Test100..Test199).

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

I also meet that problems,and just delete bottom code:

DELETE THESE LINES:
android {
    compileSdkVersion 22
    buildToolsVersion '22.0.1'
}

it worked?

How to Lazy Load div background images

First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.

Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.

Here is a example of the code change:

if (settings.appear) {
    var elements_left = elements.length;
    settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if($self.data("background"))
    loadImgUri = $self.data("background");
else
    loadImgUri  = $self.data(settings.data_attribute);

$("<img />")
    .bind("load", function() {
        $self
            .hide();
        if($self.data("background")){
            $self.css('backgroundImage', 'url('+$self.data("background")+')');
        }else
            $self.attr("src", $self.data(settings.data_attribute))

        $self[settings.effect](settings.effect_speed);

        self.loaded = true;

        /* Remove image from array so it is not looped next time. */
        var temp = $.grep(elements, function(element) {
            return !element.loaded;
        });
        elements = $(temp);

        if (settings.load) {
            var elements_left = elements.length;
            settings.load.call(self, elements_left, settings);
        }
    })
    .attr("src", loadImgUri );
}

the loading stays the same

$("#divToLoad").lazyload();

and in this example you need to modify the html code like this:

<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />?

but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.

Here's an fiddle example: http://jsfiddle.net/dtm3k/1/

Using arrays or std::vectors in C++, what's the performance gap?

The following simple test:

C++ Array vs Vector performance test explanation

contradicts the conclusions from "Comparison of assembly code generated for basic indexing, dereferencing, and increment operations on vectors and arrays/pointers."

There must be a difference between the arrays and vectors. The test says so... just try it, the code is there...

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

How to retrieve the current version of a MySQL database management system (DBMS)?

With CLI in one line :

mysql --user=root --password=pass --host=localhost db_name --execute='select version()';

or

mysql -uroot -ppass -hlocalhost db_name -e 'select version()';

return something like this :

+-----------+
| version() |
+-----------+
| 5.6.34    |
+-----------+

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

Another way to do this is as such:

INSERT CRLF SELECT 'fox 
jumped'

That is, simply inserting a line break in your query while writing it will add the like break to the database. This works in SQL server Management studio and Query Analyzer. I believe this will also work in C# if you use the @ sign on strings.

string str = @"INSERT CRLF SELECT 'fox 
    jumped'"

WARNING: sanitizing unsafe style value url

I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.

First, write below code in the component file.

constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
}

Now in your html image tag, you can write like this.

<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />

You can write as per your requirement instead of item.imageUrl

I got a reference from this site.dynamic urls. Hope this solution will help you :)

Pandas Split Dataframe into two Dataframes at a specific row

I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.

import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)

np.split(df, [100,200,300], axis=0] wants explicit index numbers which may or may not be desirable.

Good font for code presentations?

I'm personally very fond of Inconsolata

How to deserialize JS date using Jackson?

I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?

Here's what I did:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = jsonParser.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

}

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

In my case I use chrono and c function localtime_r which is thread-safe (in opposition to std::localtime).

#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>


int main() {
  std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
  std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  struct tm currentLocalTime;
  localtime_r(&currentTime, &currentLocalTime);
  char timeBuffer[80];
  std::size_t charCount { std::strftime( timeBuffer, 80,
                                         "%b %d %T",
                                          &currentLocalTime)
                         };

  if (charCount == 0) return -1;

  std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
  return 0;
}

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

Find repoName from the url, and then checkout to the specified directory.

String url = 'https://github.com/foo/bar.git';
String[] res = url.split('/');
String repoName = res[res.length-1];
if (repoName.endsWith('.git')) repoName=repoName.substring(0, repoName.length()-4);

checkout([
  $class: 'GitSCM', 
  branches: [[name: 'refs/heads/'+env.BRANCH_NAME]],
  doGenerateSubmoduleConfigurations: false,
  extensions: [
    [$class: 'RelativeTargetDirectory', relativeTargetDir: repoName],
    [$class: 'GitLFSPull'],
    [$class: 'CheckoutOption', timeout: 20],
    [$class: 'CloneOption',
        depth: 3,
        noTags: false,
        reference: '/other/optional/local/reference/clone',
        shallow: true,
        timeout: 120],
    [$class: 'SubmoduleOption', depth: 5, disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', shallow: true, trackingSubmodules: true]
  ],
  submoduleCfg: [],
  userRemoteConfigs: [
    [credentialsId: 'foobar',
    url: url]
  ]
])

Eclipse : Failed to connect to remote VM. Connection refused.

If you need to debug an application working on Tomcat, make sure that your Tomcat-folder/bin/startup.bat (if using windows) contains the following lines:

set JPDA_TRANSPORT="dt_socket"
set JPDA_ADDRESS=8000

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

How to check whether input value is integer or float?

Also:

(value % 1) == 0

would work!

How to quickly check if folder is empty (.NET)?

Here is the extra fast solution, that I finally implemented. Here I am using WinAPI and functions FindFirstFile, FindNextFile. It allows to avoid enumeration of all items in Folder and stops right after detecting the first object in the Folder. This approach is ~6(!!) times faster, than described above. 250 calls in 36ms!

private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct WIN32_FIND_DATA
{
    public uint dwFileAttributes;
    public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
    public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
    public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
    public uint nFileSizeHigh;
    public uint nFileSizeLow;
    public uint dwReserved0;
    public uint dwReserved1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string cFileName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
    public string cAlternateFileName;
}

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);

[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);

public static bool CheckDirectoryEmpty_Fast(string path)
{
    if (string.IsNullOrEmpty(path))
    {
        throw new ArgumentNullException(path);
    }

    if (Directory.Exists(path))
    {
        if (path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            path += "*";
        else
            path += Path.DirectorySeparatorChar + "*";

        WIN32_FIND_DATA findData;
        var findHandle = FindFirstFile(path, out findData);

        if (findHandle != INVALID_HANDLE_VALUE)
        {
            try
            {
                bool empty = true;
                do
                {
                    if (findData.cFileName != "." && findData.cFileName != "..")
                        empty = false;
                } while (empty && FindNextFile(findHandle, out findData));

                return empty;
            }
            finally
            {
                FindClose(findHandle);
            }
        }

        throw new Exception("Failed to get directory first file",
            Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
    }
    throw new DirectoryNotFoundException();
}

I hope it will be useful for somebody in the future.

How can I get the SQL of a PreparedStatement?

Very late :) but you can get the original SQL from an OraclePreparedStatementWrapper by

((OraclePreparedStatementWrapper) preparedStatement).getOriginalSql();

How do you round UP a number in Python?

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.

How to open a link in new tab using angular?

Just add target="_blank" to the

<a mat-raised-button target="_blank" [routerLink]="['/find-post/post', post.postID]"
    class="theme-btn bg-grey white-text mx-2 mb-2">
    Open in New Window
</a>

onclick or inline script isn't working in extension

I had the same problem, and didn´t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:

function compile(qSel){
    var matches = [];
    var match = null;
    var c = 0;

    var html = $(qSel).html();
    var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;

    while (match = pattern.exec(html)) {
        var arr = [];
        for (i in match) {
            if (!isNaN(i)) {
                arr.push(match[i]);
            }
        }
        matches.push(arr);
    }
    var items_with_events = [];
    var compiledHtml = html;

    for ( var i in matches ){
        var item_with_event = {
            custom_id : "my_app_identifier_"+i,
            code : matches[i][5],
            on : matches[i][3],
        };
        items_with_events.push(item_with_event);
        compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
    }

    $(qSel).html(compiledHtml);

    for ( var i in items_with_events ){
        $("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
            eval(items_with_events[i].code);
        });
    }
}

$(document).ready(function(){
    compile('#content');
})

This should remove all inline events from the selected node, and recreate them with jquery instead.

jQuery selector first td of each row

try

var children = null;
$('tr').each(function(){
    var td = $(this).children('td:first');
    if(children == null)
        children = td;
    else
        children.add(td);
});

// children should now hold all the first td elements

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

MySQL DAYOFWEEK() - my week begins with monday

Use WEEKDAY() instead of DAYOFWEEK(), it begins on Monday.

If you need to start at index 1, use or WEEKDAY() + 1.

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

How to search images from private 1.0 registry in docker?

So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:

Listing Repositories (link)

GET /v2/_catalog

Listing Image Tags (link)

GET /v2/<name>/tags/list

Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):

$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}

Insert Data Into Temp Table with Query

This is possible. Try this way:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;

Error: allowDefinition='MachineToApplication' beyond application level

I've this problem more frequent if "true" is enabled in the project file.

  1. Set false

As Jonny says:

  1. Clean solution whilst your solution is configured in Release mode.
  2. Clean solution whilst your solution is configured in Debug mode.
  3. Build whilst your solution is configured in Debug mode.

What is the preferred syntax for defining enums in JavaScript?

Here's what we all want:

function Enum(constantsList) {
    for (var i in constantsList) {
        this[constantsList[i]] = i;
    }
}

Now you can create your enums:

var YesNo = new Enum(['NO', 'YES']);
var Color = new Enum(['RED', 'GREEN', 'BLUE']);

By doing this, constants can be acessed in the usual way (YesNo.YES, Color.GREEN) and they get a sequential int value (NO = 0, YES = 1; RED = 0, GREEN = 1, BLUE = 2).

You can also add methods, by using Enum.prototype:

Enum.prototype.values = function() {
    return this.allValues;
    /* for the above to work, you'd need to do
            this.allValues = constantsList at the constructor */
};


Edit - small improvement - now with varargs: (unfortunately it doesn't work properly on IE :S... should stick with previous version then)

function Enum() {
    for (var i in arguments) {
        this[arguments[i]] = i;
    }
}

var YesNo = new Enum('NO', 'YES');
var Color = new Enum('RED', 'GREEN', 'BLUE');

Java Multiple Inheritance

May I suggest the concept of Duck-typing?

Most likely you would tend to make the Pegasus extend a Bird and a Horse interface but duck typing actually suggests that you should rather inherit behaviour. As already stated in the comments, a pegasus is not a bird but it can fly. So your Pegasus should rather inherit a Flyable-interface and lets say a Gallopable-interface.

This kind of concept is utilized in the Strategy Pattern. The given example actually shows you how a duck inherits the FlyBehaviour and QuackBehaviour and still there can be ducks, e.g. the RubberDuck, which can't fly. They could have also made the Duck extend a Bird-class but then they would have given up some flexibility, because every Duck would be able to fly, even the poor RubberDuck.

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

I believe that a much more reliable way to detect mobile devices is to look at the navigator.userAgent string. For example, on my iPhone the user agent string is:

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1

Note that this string contains two telltale keywords: iPhone and Mobile. Other user agent strings for devices that I don't have are provided at:

https://deviceatlas.com/blog/list-of-user-agent-strings

Using this string, I set a JavaScript Boolean variable bMobile on my website to either true or false using the following code:

var bMobile =   // will be true if running on a mobile device
  navigator.userAgent.indexOf( "Mobile" ) !== -1 || 
  navigator.userAgent.indexOf( "iPhone" ) !== -1 || 
  navigator.userAgent.indexOf( "Android" ) !== -1 || 
  navigator.userAgent.indexOf( "Windows Phone" ) !== -1 ;

Java Runtime.getRuntime(): getting output from executing a command line program

A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

Insert a line at specific line number with sed or awk

sed -i '8i8 This is Line 8' FILE

inserts at line 8

8 This is Line 8

into file FILE

-i does the modification directly to file FILE, no output to stdout, as mentioned in the comments by glenn jackman.

How to check java bit version on Linux?

Works for every binary, not only java:

file - < $(which java) # heavyly bashic

cat `which java` | file - # universal

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

Another "solution": skip all this frustration and use a UIScrollView instead to get a result that looks and feels identical to UITableView.

That was the painful "solution" for me, after having put in literally 20+ very frustrating hours total trying to build something like what smileyborg suggested and failing over many months and three versions of App Store releases.

My take is that if you really need iOS 7 support (for us, it's essential) then the technology is just too brittle and you'll pull your hair out trying. And that UITableView is complete overkill generally unless you're using some of the advanced row editing features and/or really need to support 1000+ "rows" (in our app, it's realistically never more than 20 rows).

The added bonus is that the code gets insanely simple versus all the delegate crap and back and forth that comes with UITableView. It's just one single loop of code in viewOnLoad that looks elegant and is easy to manage.

Here's some tips on how to do it:

  1. Using either Storyboard or a nib file, create a ViewController and associated root view.

  2. Drag over a UIScrollView onto your root view.

  3. Add constraints top, bottom, left and right constraints to the top-level view so the UIScrollView fills the entire root view.

  4. Add a UIView inside the UIScrollView and call it "container". Add top, bottom, left and right constraints to the UIScrollView (its parent). KEY TRICK: Also add a "Equal widths" constraints to link the UIScrollView and UIView.

    NOTE: You will get an error "scroll view has ambiguous scrollable content height" and that your container UIView should have a height of 0 pixels. Neither error seems to matter when the app is running.

  5. Create nib files and controllers for each of your "cells". Use UIView not UITableViewCell.

  6. In your root ViewController, you essentially add all the "rows" to the container UIView and programmatically add constraints linking their left and right edges to the container view, their top edges to either the container view top (for the first item) or the previous cell. Then link the final cell to the container bottom.

For us, each "row" is in a nib file. So the code looks something like this:

class YourRootViewController {

    @IBOutlet var container: UIView! //container mentioned in step 4

    override func viewDidLoad() {
        
        super.viewDidLoad()

        var lastView: UIView?
        for data in yourDataSource {

            var cell = YourCellController(nibName: "YourCellNibName", bundle: nil)
            UITools.addViewToTop(container, child: cell.view, sibling: lastView)
            lastView = cell.view
            //Insert code here to populate your cell
        }

        if(lastView != nil) {
            container.addConstraint(NSLayoutConstraint(
                item: lastView!,
                attribute: NSLayoutAttribute.Bottom,
                relatedBy: NSLayoutRelation.Equal,
                toItem: container,
                attribute: NSLayoutAttribute.Bottom,
                multiplier: 1,
                constant: 0))
        }

        ///Add a refresh control, if you want - it seems to work fine in our app:
        var refreshControl = UIRefreshControl()
        container.addSubview(refreshControl!)
    }
}

And here's the code for UITools.addViewToTop:

class UITools {
    ///Add child to container, full width of the container and directly under sibling (or container if sibling nil):
    class func addViewToTop(container: UIView, child: UIView, sibling: UIView? = nil)
    {
        child.setTranslatesAutoresizingMaskIntoConstraints(false)
        container.addSubview(child)
        
        //Set left and right constraints so fills full horz width:
        
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Leading,
            relatedBy: NSLayoutRelation.Equal,
            toItem: container,
            attribute: NSLayoutAttribute.Left,
            multiplier: 1,
            constant: 0))
        
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Trailing,
            relatedBy: NSLayoutRelation.Equal,
            toItem: container,
            attribute: NSLayoutAttribute.Right,
            multiplier: 1,
            constant: 0))
        
        //Set vertical position from last item (or for first, from the superview):
        container.addConstraint(NSLayoutConstraint(
            item: child,
            attribute: NSLayoutAttribute.Top,
            relatedBy: NSLayoutRelation.Equal,
            toItem: sibling == nil ? container : sibling,
            attribute: sibling == nil ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
            multiplier: 1,
            constant: 0))
    }
}

The only "gotcha" I've found with this approach so far is that UITableView has a nice feature of "floating" section headers at the top of the view as you scroll. The above solution won't do that unless you add more programming but for our particular case this feature wasn't 100% essential and nobody noticed when it went away.

If you want dividers between your cells, just add a 1 pixel high UIView at the bottom of your custom "cell" that looks like a divider.

Be sure to turn on "bounces" and "bounce vertically" for the refresh control to work and so it seems more like a tableview.

TableView shows some empty rows and dividers under your content, if it doesn't fill the full screen where as this solution doesn't. But personally, I prefer if those empty rows weren't there anyway - with variable cell height it always looked "buggy" to me anyway to have the empty rows in there.

Here's hoping some other programmer reads my post BEFORE wasting 20+ hours trying to figure it out with Table View in their own app. :)

How to add title to seaborn boxplot

.set_title('') can be used to add title to Seaborn Plot

import seaborn as sb
sb.boxplot().set_title('Title')

When should I really use noexcept?

In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):

Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a noexcept specifier (§13.5.1.1) can make that desire explicit.

Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore, terminate() supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly, noexcept provides a simple escape for errors where trying to recover seems infeasible.

double compute(double x) noexcept;     {
    string s = "Courtney and Anya";
    vector<double> tmp(10);
    // ...
}

The vector constructor may fail to acquire memory for its ten doubles and throw a std::bad_alloc. In that case, the program terminates. It terminates unconditionally by invoking std::terminate() (§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between the throw and the noexcept (e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding a noexcept specifier, we indicate that our code was not written to cope with a throw.

AngularJS: How to clear query parameters in the URL?

You can delete a specific query parameter by using:

delete $location.$$search.nameOfParameter;

Or you can clear all the query params by setting search to an empty object:

$location.$$search = {};

How to use Class<T> in Java?

All we know is "All instances of a any class shares the same java.lang.Class object of that type of class"

e.g)

Student a = new Student();
Student b = new Student();

Then a.getClass() == b.getClass() is true.

Now assume

Teacher t = new Teacher();

without generics the below is possible.

Class studentClassRef = t.getClass();

But this is wrong now ..?

e.g) public void printStudentClassInfo(Class studentClassRef) {} can be called with Teacher.class

This can be avoided using generics.

Class<Student> studentClassRef = t.getClass(); //Compilation error.

Now what is T ?? T is type parameters (also called type variables); delimited by angle brackets (<>), follows the class name.
T is just a symbol, like a variable name (can be any name) declared during writing of the class file. Later that T will be substituted with
valid Class name during initialization (HashMap<String> map = new HashMap<String>();)

e.g) class name<T1, T2, ..., Tn>

So Class<T> represents a class object of specific class type 'T'.

Assume that your class methods has to work with unknown type parameters like below

/**
 * Generic version of the Car class.
 * @param <T> the type of the value
 */
public class Car<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Here T can be used as String type as CarName

OR T can be used as Integer type as modelNumber,

OR T can be used as Object type as valid car instance.

Now here the above is the simple POJO which can be used differently at runtime.
Collections e.g) List, Set, Hashmap are best examples which will work with different objects as per the declaration of T, but once we declared T as String
e.g) HashMap<String> map = new HashMap<String>(); Then it will only accept String Class instance objects.

Generic Methods

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For generic methods, the type parameter section must appear before the method's return type.

 class Util {
    // Generic static method
    public static <K, V, Z, Y> boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

 class Pair<K, V> {

    private K key;
    private V value;
}

Here <K, V, Z, Y> is the declaration of types used in the method arguments which should before the return type which is boolean here.

In the below; type declaration <T> is not required at method level, since it is already declared at class level.

class MyClass<T> {
   private  T myMethod(T a){
       return  a;
   }
}

But below is wrong as class-level type parameters K, V, Z, and Y cannot be used in a static context (static method here).

class Util <K, V, Z, Y>{
    // Generic static method
    public static  boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

OTHER VALID SCENARIOS ARE

class MyClass<T> {

        //Type declaration <T> already done at class level
        private  T myMethod(T a){
            return  a;
        }

        //<T> is overriding the T declared at Class level;
        //So There is no ClassCastException though a is not the type of T declared at MyClass<T>. 
        private <T> T myMethod1(Object a){
                return (T) a;
        }

        //Runtime ClassCastException will be thrown if a is not the type T (MyClass<T>).  
        private T myMethod1(Object a){
                return (T) a;
        }       

        // No ClassCastException        
        // MyClass<String> obj= new MyClass<String>();
        // obj.myMethod2(Integer.valueOf("1"));
        // Since type T is redefined at this method level.
        private <T> T myMethod2(T a){
            return  a;
        }

        // No ClassCastException for the below
        // MyClass<String> o= new MyClass<String>();
        // o.myMethod3(Integer.valueOf("1").getClass())
        // Since <T> is undefined within this method; 
        // And MyClass<T> don't have impact here
        private <T> T myMethod3(Class a){
            return (T) a;
        }

        // ClassCastException for o.myMethod3(Integer.valueOf("1").getClass())
        // Should be o.myMethod3(String.valueOf("1").getClass())
    private  T myMethod3(Class a){
        return (T) a;
    }


        // Class<T> a :: a is Class object of type T
        //<T> is overriding of class level type declaration; 
        private <T> Class<T> myMethod4(Class<T> a){
            return  a;
        }
    }

And finally Static method always needs explicit <T> declaration; It wont derive from class level Class<T>. This is because of Class level T is bound with instance.

Also read Restrictions on Generics

Wildcards and Subtyping

type argument for a generic method

PowerShell script to check the status of a URL

For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest:

$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}

what is right way to do API call in react js?

You may want to check out the Flux Architecture. I also recommend checking out React-Redux Implementation. Put your api calls in your actions. It is much more cleaner than putting it all in the component.

Actions are sort of helper methods that you can call to change your application state or do api calls.

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

Difference between sh and bash

sh: http://man.cx/sh
bash: http://man.cx/bash

TL;DR: bash is a superset of sh with a more elegant syntax and more functionality. It is safe to use a bash shebang line in almost all cases as it's quite ubiquitous on modern platforms.

NB: in some environments, sh is bash. Check sh --version.

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.

AngularJS format JSON string output

You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

Your branch is ahead of 'origin/master' by 3 commits

This happened to me once after I merged a pull request on Bitbucket.

I just had to do:

git fetch

My problem was solved. I hope this helps!!!

Android, getting resource ID from string?

How to get an application resource id from the resource name is quite a common and well answered question.

How to get a native Android resource id from the resource name is less well answered. Here's my solution to get an Android drawable resource by resource name:

public static Drawable getAndroidDrawable(String pDrawableName){
    int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
    if(resourceId==0){
        return null;
    } else {
        return Resources.getSystem().getDrawable(resourceId);
    }
}

The method can be modified to access other types of resources.

ImportError: cannot import name main when running pip --version command in windows7 32 bit

On Windows 10, I had the same problem. PIP 19 was already installed in my system but wasn't showing up. The error was No Module Found.

python -m pip uninstall pip
python -m pip install pip==9.0.3

Downgrading pip to 9.0.3 worked fine for me.

How to add List<> to a List<> in asp.net

  1. Use Concat or Union extension methods. You have to make sure that you have this direction using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

Property getters and setters

Here is a theoretical answer. That can be found here

A { get set } property cannot be a constant stored property. It should be a computed property and both get and set should be implemented.

How do I address unchecked cast warnings?

The obvious answer, of course, is not to do the unchecked cast.

If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings annotation. According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.

Example:

@SuppressWarnings("unchecked")
Map<String, String> myMap = (Map<String, String>) deserializeMap();

There is no way to determine whether the Map really should have the generic parameters <String, String>. You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException). This is why the code generates a warning, because the compiler can't possibly know whether is safe.

How to select multiple rows filled with constants?

Here a way to create custom rows directly with MySQL request SELECT :

SELECT ALL *
FROM (
    VALUES
        ROW (1, 2, 3),
        ROW (4, 5, 6),
        ROW (7, 8, 9)
) AS dummy (c1, c2, c3)

Gives us a table dummy :

c1   c2   c3
-------------
 1    2    3
 4    5    6
 7    8    9

Tested with MySQL 8

The EntityManager is closed

You can reset your EM so

// reset the EM and all aias
$container = $this->container;
$container->set('doctrine.orm.entity_manager', null);
$container->set('doctrine.orm.default_entity_manager', null);
// get a fresh EM
$em = $this->getDoctrine()->getManager();

What are database constraints?

constraints are conditions, that can validate specific condition. Constraints related with database are Domain integrity, Entity integrity, Referential Integrity, User Defined Integrity constraints etc.

jQuery: Clearing Form Inputs

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

Select all occurrences of selected word in VSCode

Ctrl + F2 works for me in Windows 10.

Ctrl + Shift + L starts performance logging

read string from .resx file in C#

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

Javascript/Jquery Convert string to array

Change

var trainindIdArray = traingIds.split(',');

to

var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

C compile error: Id returned 1 exit status

This answer is written for C++ developers, because I was haunted by such problem as one. Here is the solution:

Instead of

main()
{

}

please type

int main()
{

}

so the main function can be executed.

By the way, if you compile a C/C++ source file with no main function to execute, there will definitely be a bug message saying:

"[Error] Id returned 1 exist status"

But sometimes we just don't need main function in the file, in such a case, just ignore the bug message.

How to catch segmentation fault in Linux?

Sometimes we want to catch a SIGSEGV to find out if a pointer is valid, that is, if it references a valid memory address. (Or even check if some arbitrary value may be a pointer.)

One option is to check it with isValidPtr() (worked on Android):

int isValidPtr(const void*p, int len) {
    if (!p) {
    return 0;
    }
    int ret = 1;
    int nullfd = open("/dev/random", O_WRONLY);
    if (write(nullfd, p, len) < 0) {
    ret = 0;
    /* Not OK */
    }
    close(nullfd);
    return ret;
}
int isValidOrNullPtr(const void*p, int len) {
    return !p||isValidPtr(p, len);
}

Another option is to read the memory protection attributes, which is a bit more tricky (worked on Android):

re_mprot.c:

#include <errno.h>
#include <malloc.h>
//#define PAGE_SIZE 4096
#include "dlog.h"
#include "stdlib.h"
#include "re_mprot.h"

struct buffer {
    int pos;
    int size;
    char* mem;
};

char* _buf_reset(struct buffer*b) {
    b->mem[b->pos] = 0;
    b->pos = 0;
    return b->mem;
}

struct buffer* _new_buffer(int length) {
    struct buffer* res = malloc(sizeof(struct buffer)+length+4);
    res->pos = 0;
    res->size = length;
    res->mem = (void*)(res+1);
    return res;
}

int _buf_putchar(struct buffer*b, int c) {
    b->mem[b->pos++] = c;
    return b->pos >= b->size;
}

void show_mappings(void)
{
    DLOG("-----------------------------------------------\n");
    int a;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    }
    if (b->pos) {
    DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    free(b);
    fclose(f);
    DLOG("-----------------------------------------------\n");
}

unsigned int read_mprotection(void* addr) {
    int a;
    unsigned int res = MPROT_0;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        char*end0 = (void*)0;
        unsigned long addr0 = strtoul(b->mem, &end0, 0x10);
        char*end1 = (void*)0;
        unsigned long addr1 = strtoul(end0+1, &end1, 0x10);
        if ((void*)addr0 < addr && addr < (void*)addr1) {
            res |= (end1+1)[0] == 'r' ? MPROT_R : 0;
            res |= (end1+1)[1] == 'w' ? MPROT_W : 0;
            res |= (end1+1)[2] == 'x' ? MPROT_X : 0;
            res |= (end1+1)[3] == 'p' ? MPROT_P
                 : (end1+1)[3] == 's' ? MPROT_S : 0;
            break;
        }
        _buf_reset(b);
    }
    }
    free(b);
    fclose(f);
    return res;
}

int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask) {
    unsigned prot1 = read_mprotection(addr);
    return (prot1 & prot_mask) == prot;
}

char* _mprot_tostring_(char*buf, unsigned int prot) {
    buf[0] = prot & MPROT_R ? 'r' : '-';
    buf[1] = prot & MPROT_W ? 'w' : '-';
    buf[2] = prot & MPROT_X ? 'x' : '-';
    buf[3] = prot & MPROT_S ? 's' : prot & MPROT_P ? 'p' :  '-';
    buf[4] = 0;
    return buf;
}

re_mprot.h:

#include <alloca.h>
#include "re_bits.h"
#include <sys/mman.h>

void show_mappings(void);

enum {
    MPROT_0 = 0, // not found at all
    MPROT_R = PROT_READ,                                 // readable
    MPROT_W = PROT_WRITE,                                // writable
    MPROT_X = PROT_EXEC,                                 // executable
    MPROT_S = FIRST_UNUSED_BIT(MPROT_R|MPROT_W|MPROT_X), // shared
    MPROT_P = MPROT_S<<1,                                // private
};

// returns a non-zero value if the address is mapped (because either MPROT_P or MPROT_S will be set for valid addresses)
unsigned int read_mprotection(void* addr);

// check memory protection against the mask
// returns true if all bits corresponding to non-zero bits in the mask
// are the same in prot and read_mprotection(addr)
int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask);

// convert the protection mask into a string. Uses alloca(), no need to free() the memory!
#define mprot_tostring(x) ( _mprot_tostring_( (char*)alloca(8) , (x) ) )
char* _mprot_tostring_(char*buf, unsigned int prot);

PS DLOG() is printf() to the Android log. FIRST_UNUSED_BIT() is defined here.

PPS It may not be a good idea to call alloca() in a loop -- the memory may be not freed until the function returns.

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Use grep --exclude/--include syntax to not grep through certain files

To ignore all binary results from grep

grep -Ri "pattern" * | awk '{if($1 != "Binary") print $0}'

The awk part will filter out all the Binary file foo matches lines

How to create an 2D ArrayList in java?

The best way is to use a List within a List:

List<List<String>> listOfLists = new ArrayList<List<String>>();  

How to copy a string of std::string type in C++?

strcpy example:

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

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

Restricting JTextField input to Integers

Here's one approach that uses a keylistener,but uses the keyChar (instead of the keyCode):

http://edenti.deis.unibo.it/utils/Java-tips/Validating%20numerical%20input%20in%20a%20JTextField.txt

 keyText.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE))) {
        getToolkit().beep();
        e.consume();
      }
    }
  });

Another approach (which personally I find almost as over-complicated as Swing's JTree model) is to use Formatted Text Fields:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

Execute JavaScript code stored as a string

You can execute it using a function. Example:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

Import functions from another js file. Javascript

From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

How do I get the path of a process in Unix / Linux

You can also get the path on GNU/Linux with (not thoroughly tested):

char file[32];
char buf[64];
pid_t pid = getpid();
sprintf(file, "/proc/%i/cmdline", pid);
FILE *f = fopen(file, "r");
fgets(buf, 64, f);
fclose(f);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

*strrchr(buf, '/') = '\0';
/*chdir(buf);*/

Passing Parameters JavaFX FXML

Recommended Approach

This answer enumerates different mechanisms for passing parameters to FXML controllers.

For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.

For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.

Passing Parameters Directly From the Caller to the Controller

Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.

Something like the following code:

public Stage showCustomerDialog(Customer customer) {
  FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
      "customerDialog.fxml"
    )
  );

  Stage stage = new Stage(StageStyle.DECORATED);
  stage.setScene(
    new Scene(loader.load())
  );

  CustomerDialogController controller = loader.getController();
  controller.initData(customer);

  stage.show();

  return stage;
}

...

class CustomerDialogController {
  @FXML private Label customerName;
  void initialize() {}
  void initData(Customer customer) {
    customerName.setText(customer.getName());
  }
}

A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:

new FXMLLoader(getClass().getResource("sample.fxml"));

Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.

FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:

  1. Construct an FXMLLoader based upon fxml markup at a specified location
  2. Get a controller from the FXMLLoader instance.
  3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.

This blog (by another writer) provides an alternate, but similar, example.

Setting a Controller on the FXMLLoader

CustomerDialogController dialogController = 
    new CustomerDialogController(param1, param2);

FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
        "customerDialog.fxml"
    )
);
loader.setController(dialogController);

Pane mainPane = loader.load();

You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.

To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.

Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.

Having the Controller Retrieve Parameters from an External Static Method

This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.

Use Dependency Injection

FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system.

An example of JavaFX application and controller dependency injection with Spring is provided in the answer to:

A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.

Use an Event Bus

Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus, such as the Guava EventBus, for communication between FXML instantiated controllers and other application logic.

The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.

Follow-up Q&A

on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage

It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.


Additional information supplied by StackOverflow user named @dzim

Example for Spring Boot Dependency Injection

The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink. The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE: https://stackoverflow.com/a/36310391/1281217


Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

jquery .html() vs .append()

This has happened to me . Jquery version : 3.3. If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.

How to get package name from anywhere?

If with the word "anywhere" you mean without having an explicit Context (for example from a background thread) you should define a class in your project like:

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance;
        // or return instance.getApplicationContext();
    }

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }
}

Then in your manifest you need to add this class to the Name field at the Application tab. Or edit the xml and put

<application
    android:name="com.example.app.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......

and then from anywhere you can call

String packagename= MyApp.getContext().getPackageName();

Hope it helps.

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I had the same issue, but the other answers only supplied one part of the solution.

The solution is two fold:

Remove the 64bit from the Register.

  • c:\windows\system32\regsvr32.exe /U <file.dll>
  • This will not remove references to other copied of the dll in other folders.

or

  • Find the key called HKEY_CLASSES_ROOT\CLSID{......}\InprocServer32. This key will have the filename of the DLL as its default value.
  • I removed the HKEY_CLASSES_ROOT\CLSID{......} folder.

Register it as 32bit:

  • C:\Windows\SysWOW64\regsvr32 <file.dll>

Registering it as 32bit without removing the 64bit registration does not resolve my issue.

How to Find App Pool Recycles in Event Log

IIS version 8.5 +

To enable Event Tracing for Windows for your website/application

  1. Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.

enter image description here

  1. Enable the desired Recycle logs in the Advanced Settings for the Application Pool:

enter image description here

  1. Go to the default Custom View: WebServer filters IIS logs:

Custom Views > ServerRoles > Web Server

enter image description here

  1. ... or System logs:

Windows Logs > System

Align image in center and middle within div

SIMPLE. 2018. FlexBox. To Check Browser Support - Can I Use

Minimal Solution:

div#over { 
   display: flex; 
   justify-content: center; 
   align-items: center; 
}


To get the widest browser support possible:

div#over { 
   display: -webkit-flex;
   display: -ms-flex; 
   display: flex; 
   justify-content: center; 
   -ms-align-items: center; 
   align-items: center; 
}

What is key=lambda

In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.

Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.

>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum
... 
>>> lambda num1, num2: num1 + num2 
<function <lambda> at 0x1004b5de8>
>>> 
>>> # Let's store the returned value in variable & call it(1st way to call)
... 
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>> 
>>> # Let's call it in other way(2nd way to call, one line call )
... 
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>> 

Now let me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.

Suppose we have a list of items(integers and strings with numeric contents) as follows,

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

and I want to sort it using sorted() function, lets see what happens.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums)
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>>

It didn't give me what I expected as I wanted like below,

['-10', '-1', 1, '2', 3, 4, '5', '8']

It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>> 

Lets use lambda function as a value of key

>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A')
...
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>

You can define your own function(callable) and provide it as value of key.

Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).

>>> def validator(item):
...     try:
...         return int(item)
...     except:
...         return 0
... 
>>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator)
[-2, 'gurmit', '0', 'front', 'great', 1, 2, 5]
>>>

I hope it would be useful.

Python timedelta in years

I would use datetime.date data type instead, as it is simpler when it comes to checking how many years, months and days have passed:

now = date.today()
birthday = date(1993, 4, 4)
print("you are", now.year - birthday.year, "years,", now.month - birthday.month, "months and",
  now.day - birthday.day, "days old")

Output:

you are 27 years, 7 months and 11 days old

I use timedelta when I need to perform arithmetic on a specific date:

age = now - birthday
print("addition of days to a date: ", birthday + timedelta(days=age.days))

Output:

addition of days to a date:  2020-11-15

CSS Div stretch 100% page height

If you are targeting more modern browsers, life can be very simple. try:

.elem{    
    height: 100vh;
 }

if you need it at 50% of the page, replace 100 with 50.

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

How to SHUTDOWN Tomcat in Ubuntu?

If you installed tomcat manually, run the shutdown.sh(/.../tomcat/bin) from the terminal to shut it down easily.