Programs & Examples On #Ec2 ami

For questions relating to virtual machine images (Amazon Machine Image) on Amazon's EC2 infrastructure.

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

grep 2.5.3 introduced the --exclude-dir parameter which will work the way you want.

grep -rI --exclude-dir=\.svn PATTERN .

You can also set an environment variable: GREP_OPTIONS="--exclude-dir=\.svn"

I'll second Andy's vote for ack though, it's the best.

Python string.join(list) on object array rather than string array

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Maven compile: package does not exist

the issue happened with me, I resolved by removing the scope tag only and built successfully.

PowerShell The term is not recognized as cmdlet function script file or operable program

Yet another way this error message can occur...

If PowerShell is open in a directory other than the target file, e.g.:

If someScript.ps1 is located here: C:\SlowLearner\some_missing_path\someScript.ps1, then C:\SlowLearner>. ./someScript.ps1 wont work.

In that case, navigate to the path: cd some_missing_path then this would work:

C:\SlowLearner\some_missing_path>. ./someScript.ps1

'uint32_t' identifier not found error

On Windows I usually use windows types. To use it you have to include <Windows.h>.

In this case uint32_t is UINT32 or just UINT.

All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx

C++ variable has initializer but incomplete type?

It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef directive. In this case compiler will just skip definition of the class thinking that it's a duplication.

Differences between Octave and MATLAB?

MATLAB is, first and foremost, a commercial offering. Therefore, everything in MATLAB pretty much works out of the box. All the core functionality is solid, and if you're working on a special project then MATLAB probably has an add-on they can sell you that adds a lot of additional domain-specific .m files for you. It ain't cheap, but it works and it will get the job done without complaint.

Octave always shows its open-source, information-wants-to-be-free roots. It's free, and it will remind you that it's free at every opportunity. It's developed by volunteers who hate Windows with a passion. Therefore Octave runs on Windows grudgingly. It's quite surprising that as many MATLAB features exist as they do.

But here's the rub. Anytime you try to do something more than trivially complex, Octave suddenly breaks in subtle and hard to understand ways. Oops -- the terminal driver had an overflow somewhere deep in the OpenGL layer. You can't print. Oops -- the figure plots do strange things with their fonts. Good luck figuring out why. Oops -- there's some hidden dependency between Octave and some other obscure bit of free software, so it won't compile. Good luck figuring out which it is.

And the Octave response is hey! It's free software! You have all the source code, you can fix all those bugs yourself! Maybe if I had infinite time and resources on my hands, I could spend all my time fixing bugs in free software, but I personally don't. If I worked in academia, I might.

So at the core, the issue of whether to choose MATLAB or Octave comes down to one question. Interestingly, that question is always the same, when choosing between commercial vs. free software variants.

And the question is:

Do you have more money than time?

How can I get all a form's values that would be submitted without submitting

If your form tag is like

<form action="" method="post" id="BookPackageForm">

Then fetch the form element by using forms object.

var formEl = document.forms.BookPackageForm;

Get the data from the form by using FormData objects.

var formData = new FormData(formEl);

Get the value of the fields by the form data object.

var name = formData.get('name');

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What are the First and Second Level caches in (N)Hibernate?

by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.

so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.

Why does Lua have no "continue" statement?

The way that the language manages lexical scope creates issues with including both goto and continue. For example,

local a=0
repeat 
    if f() then
        a=1 --change outer a
    end
    local a=f() -- inner a
until a==0 -- test inner a

The declaration of local a inside the loop body masks the outer variable named a, and the scope of that local extends across the condition of the until statement so the condition is testing the innermost a.

If continue existed, it would have to be restricted semantically to be only valid after all of the variables used in the condition have come into scope. This is a difficult condition to document to the user and enforce in the compiler. Various proposals around this issue have been discussed, including the simple answer of disallowing continue with the repeat ... until style of loop. So far, none have had a sufficiently compelling use case to get them included in the language.

The work around is generally to invert the condition that would cause a continue to be executed, and collect the rest of the loop body under that condition. So, the following loop

-- not valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if isstring(k) then continue end
  -- do something to t[k] when k is not a string
end

could be written

-- valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
  if not isstring(k) then 
    -- do something to t[k] when k is not a string
  end
end

It is clear enough, and usually not a burden unless you have a series of elaborate culls that control the loop operation.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

This answer complements the many great existing answers in the following ways:

  • The existing answers are packaged into flexible shell functions:

    • The functions take not only stdin input, but alternatively also filename arguments
    • The functions take extra steps to handle SIGPIPE in the usual way (quiet termination with exit code 141), as opposed to breaking noisily. This is important when piping the function output to a pipe that is closed early, such as when piping to head.
  • A performance comparison is made.


  • POSIX-compliant function based on awk, sort, and cut, adapted from the OP's own answer:
shuf() { awk 'BEGIN {srand(); OFMT="%.17f"} {print rand(), $0}' "$@" |
               sort -k1,1n | cut -d ' ' -f2-; }
shuf() { perl -MList::Util=shuffle -e 'print shuffle(<>);' "$@"; }
shuf() { python -c '
import sys, random, fileinput; from signal import signal, SIGPIPE, SIG_DFL;    
signal(SIGPIPE, SIG_DFL); lines=[line for line in fileinput.input()];   
random.shuffle(lines); sys.stdout.write("".join(lines))
' "$@"; }

See the bottom section for a Windows version of this function.

shuf() { ruby -e 'Signal.trap("SIGPIPE", "SYSTEM_DEFAULT");
                     puts ARGF.readlines.shuffle' "$@"; }

Performance comparison:

Note: These numbers were obtained on a late-2012 iMac with 3.2 GHz Intel Core i5 and a Fusion Drive, running OSX 10.10.3. While timings will vary with OS used, machine specs, awk implementation used (e.g., the BSD awk version used on OSX is usually slower than GNU awk and especially mawk), this should provide a general sense of relative performance.

Input file is a 1-million-lines file produced with seq -f 'line %.0f' 1000000.
Times are listed in ascending order (fastest first):

  • shuf
    • 0.090s
  • Ruby 2.0.0
    • 0.289s
  • Perl 5.18.2
    • 0.589s
  • Python
    • 1.342s with Python 2.7.6; 2.407s(!) with Python 3.4.2
  • awk + sort + cut
    • 3.003s with BSD awk; 2.388s with GNU awk (4.1.1); 1.811s with mawk (1.3.4);

For further comparison, the solutions not packaged as functions above:

  • sort -R (not a true shuffle if there are duplicate input lines)
    • 10.661s - allocating more memory doesn't seem to make a difference
  • Scala
    • 24.229s
  • bash loops + sort
    • 32.593s

Conclusions:

  • Use shuf, if you can - it's the fastest by far.
  • Ruby does well, followed by Perl.
  • Python is noticeably slower than Ruby and Perl, and, comparing Python versions, 2.7.6 is quite a bit faster than 3.4.1
  • Use the POSIX-compliant awk + sort + cut combo as a last resort; which awk implementation you use matters (mawk is faster than GNU awk, BSD awk is slowest).
  • Stay away from sort -R, bash loops, and Scala.

Windows versions of the Python solution (the Python code is identical, except for variations in quoting and the removal of the signal-related statements, which aren't supported on Windows):

  • For PowerShell (in Windows PowerShell, you'll have to adjust $OutputEncoding if you want to send non-ASCII characters via the pipeline):
# Call as `shuf someFile.txt` or `Get-Content someFile.txt | shuf`
function shuf {
  $Input | python -c @'
import sys, random, fileinput;
lines=[line for line in fileinput.input()];
random.shuffle(lines); sys.stdout.write(''.join(lines))
'@ $args  
}

Note that PowerShell can natively shuffle via its Get-Random cmdlet (though performance may be a problem); e.g.:
Get-Content someFile.txt | Get-Random -Count ([int]::MaxValue)

  • For cmd.exe (a batch file):

Save to file shuf.cmd, for instance:

@echo off
python -c "import sys, random, fileinput; lines=[line for line in fileinput.input()]; random.shuffle(lines); sys.stdout.write(''.join(lines))" %*

android studio 0.4.2: Gradle project sync failed error

same here, updating to 0.4.2 also broke everything in my case... It has nothing to do with memory usage : I've got 8 gig of memory and I have 3.5 gig free atm, so not having enough memory to start up a JVM is bullocks...

Actually it might have something to do with Gradle versions, I looked into the error log and found this :

2014-01-14 09:00:30,918 [ 61112] WARN - nal.AbstractExternalSystemTask - Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files.

You are using Gradle version 1.8, which is not supported. Please use version 1.9. Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.) com.intellij.openapi.externalSystem.model.ExternalSystemException: Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files

-

You are using Gradle version 1.8, which is not supported. Please use version 1.9.

Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.)

OK, I fixed it myself... In the project directory go to /gradle/wrapper directory and edit the gradle-wrapper properties file to this :

distributionUrl=http\://services.gradle.org/distributions/gradle-1.9-all.zip

After open your project in Android Studio and select the build.gradle file in the /src directory and edit it to this :

dependencies {
        classpath 'com.android.tools.build:gradle:0.7.+'
    }

After fixing it like this I discovered this article : http://tools.android.com/recent/androidstudio040released

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

Finding the Eclipse Version Number

I think, the easiest way is to read readme file inside your Eclipse directory at path eclipse/readme/eclipse_readme .

At the very top of this file it clearly tells the version number:

For My Eclipse Juno; it says version as Release 4.2.0

Plotting time in Python with Matplotlib

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

How to register multiple servlets in web.xml in one Spring application

Use config something like this:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

Access camera from a browser

You can use HTML5 for this:

<video autoplay></video>
<script>
  var onFailSoHard = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, onFailSoHard);
</script>

Source

How SID is different from Service name in Oracle tnsnames.ora

I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:

mySID, mySID.whereever.com =
(DESCRIPTION =
  (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
  )
  (CONNECT_DATA =
    (SERVICE_NAME = mySID.whereever.com)
    (SID = mySID)
    (SERVER = DEDICATED)
  )
)

I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

SSH to Elastic Beanstalk instance

Elastic Beanstalk can bind a single EC2 keypair to an instance profile. A manual solution to have multiple users ssh into EBS is to add their public keys in authorized_keys file.

Center Triangle at Bottom of Div

You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).

.hero:after,
.hero:after {
    z-index: -1;
    position: absolute;
    top: 98.1%;
    left: calc(50% - 25px);
    content: '';
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

How do I flush the cin buffer?

It worked for me. I have used for loop with getline().

cin.ignore()

Regular expression that matches valid IPv6 addresses

If you want only normal IP-s (no slashes), here:

^(?:[0-9a-f]{1,4}(?:::)?){0,7}::[0-9a-f]+$

I use it for my syntax highlighter in hosts file editor application. Works as charm.

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

what's the correct way to send a file from REST web service to client?

Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.

Client to call REST webservice:

package in.india.client.downloadfiledemo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;

public class DownloadFileClient {

    private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";

    public DownloadFileClient() {

        try {
            Client client = Client.create();
            WebResource objWebResource = client.resource(BASE_URI);
            ClientResponse response = objWebResource.path("/")
                    .type(MediaType.TEXT_HTML).get(ClientResponse.class);

            System.out.println("response : " + response);
            if (response.getStatus() == Status.OK.getStatusCode()
                    && response.hasEntity()) {
                MultiPart objMultiPart = response.getEntity(MultiPart.class);
                java.util.List<BodyPart> listBodyPart = objMultiPart
                        .getBodyParts();
                BodyPart filenameBodyPart = listBodyPart.get(0);
                BodyPart fileLengthBodyPart = listBodyPart.get(1);
                BodyPart fileBodyPart = listBodyPart.get(2);

                String filename = filenameBodyPart.getEntityAs(String.class);
                String fileLength = fileLengthBodyPart
                        .getEntityAs(String.class);
                File streamedFile = fileBodyPart.getEntityAs(File.class);

                BufferedInputStream objBufferedInputStream = new BufferedInputStream(
                        new FileInputStream(streamedFile));

                byte[] bytes = new byte[objBufferedInputStream.available()];

                objBufferedInputStream.read(bytes);

                String outFileName = "D:/"
                        + filename;
                System.out.println("File name is : " + filename
                        + " and length is : " + fileLength);
                FileOutputStream objFileOutputStream = new FileOutputStream(
                        outFileName);
                objFileOutputStream.write(bytes);
                objFileOutputStream.close();
                objBufferedInputStream.close();
                File receivedFile = new File(outFileName);
                System.out.print("Is the file size is same? :\t");
                System.out.println(Long.parseLong(fileLength) == receivedFile
                        .length());
            }
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new DownloadFileClient();
    }
}

Service to response client:

package in.india.service.downloadfiledemo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.multipart.MultiPart;

@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {

    @GET
    public Response getFile() {

        java.io.File objFile = new java.io.File(
                "D:/DanGilbert_2004-480p-en.mp4");
        MultiPart objMultiPart = new MultiPart();
        objMultiPart.type(new MediaType("multipart", "mixed"));
        objMultiPart
                .bodyPart(objFile.getName(), new MediaType("text", "plain"));
        objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
                "plain"));
        objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));

        return Response.ok(objMultiPart).build();

    }
}

JAR needed:

jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DownloadFileDemo</display-name>
    <servlet>
        <display-name>JAX-RS REST Servlet</display-name>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name> 
             <param-value>in.india.service.downloadfiledemo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Android XXHDPI resources

480 dpi is the standard QUANTIZED resolution for xxhdpi, it can vary something less (i.e.: 440 dpi) or more (i.e.: 520 dpi). Scale factor: 3x (3 * mdpi).

Now there's a higher resolution, xxxhdpi (640 dpi). Scale factor 4x (4 * mdpi).

Here's the source reference.

NoClassDefFoundError - Eclipse and Android

Right click your project folder, look for Properties in Java build path and select the jar files that you see. It has worked for me.

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

How to add a line break within echo in PHP?

The new line character is \n, like so:

echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');

How do I delete a Git branch locally and remotely?

In addition to the other answers, I often use the git_remote_branch tool. It's an extra install, but it gets you a convenient way to interact with remote branches. In this case, to delete:

grb delete branch

I find that I also use the publish and track commands quite often.

List distinct values in a vector in R

In R Language (version 3.0+) You can apply filter to get unique out of a list-

data.list <- data.list %>% unique

or couple it with other operation as well

data.list.rollnumbers <- data.list %>% pull(RollNumber) %>% unique

unique doesn't require dplyr.

Javascript array sort and unique

This might be adequate in circumstances where you can't define the function in advance (like in a bookmarklet):

myData.sort().filter(function(el,i,a){return i===a.indexOf(el)})

Inserting string at position x of another string

Quick fix! If you don't want to manually add a space, you can do this:

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

(edit: i see that this is actually answered above, sorry!)

How do I compare strings in Java?

I agree with the answer from zacherates.

But what you can do is to call intern() on your non-literal strings.

From zacherates example:

// ... but they are not the same object
new String("test") == "test" ==> false 

If you intern the non-literal String equality is true:

new String("test").intern() == "test" ==> true 

A reference to the dll could not be added

The following worked for me:

Short answer

Run the following via command line (cmd):

TlbImp.exe cvextern.dll        //where cvextern.dll is your dll you want to fix.

And a valid dll will be created for you.

Longer answer

  • Open cmd

  • Find TlbImp.exe. Probably located in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin. If you can't find it go to your root folder (C:\ or D:) and run:

    dir tlbimp.exe /s              //this will locate the file.
    
  • Run tlbimp.exe and put your dll behind it. Example: If your dll is cvextern.dll. You can run:

    TlbImp.exe cvextern.dll
    
  • A new dll has been created in the same folder of tlbimp.exe. You can use that as reference in your project.

Subset data to contain only columns whose names match a condition

Try grepl on the names of your data.frame. grepl matches a regular expression to a target and returns TRUE if a match is found and FALSE otherwise. The function is vectorised so you can pass a vector of strings to match and you will get a vector of boolean values returned.

Example

#  Data
df <- data.frame( ABC_1 = runif(3),
            ABC_2 = runif(3),
            XYZ_1 = runif(3),
            XYZ_2 = runif(3) )

#      ABC_1     ABC_2     XYZ_1     XYZ_2
#1 0.3792645 0.3614199 0.9793573 0.7139381
#2 0.1313246 0.9746691 0.7276705 0.0126057
#3 0.7282680 0.6518444 0.9531389 0.9673290

#  Use grepl
df[ , grepl( "ABC" , names( df ) ) ]
#      ABC_1     ABC_2
#1 0.3792645 0.3614199
#2 0.1313246 0.9746691
#3 0.7282680 0.6518444

#  grepl returns logical vector like this which is what we use to subset columns
grepl( "ABC" , names( df ) )
#[1]  TRUE  TRUE FALSE FALSE

To answer the second part, I'd make the subset data.frame and then make a vector that indexes the rows to keep (a logical vector) like this...

set.seed(1)
df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
            ABC_2 = sample(0:1,3,repl = TRUE),
            XYZ_1 = sample(0:1,3,repl = TRUE),
            XYZ_2 = sample(0:1,3,repl = TRUE) )

# We will want to discard the second row because 'all' ABC values are 0:
#  ABC_1 ABC_2 XYZ_1 XYZ_2
#1     0     1     1     0
#2     0     0     1     0
#3     1     1     1     0


df1 <- df[ , grepl( "ABC" , names( df ) ) ]

ind <- apply( df1 , 1 , function(x) any( x > 0 ) )

df1[ ind , ]
#  ABC_1 ABC_2
#1     0     1
#3     1     1

Troubleshooting BadImageFormatException

Background

We started getting this today when we switched our WCF service from AnyCPU to x64 on a Windows 2012 R2 server running IIS 6.2.

First we checked the only referenced assembly 10 times, to ensure it was not actually an x86 dll. Next we checked the application pool many times to ensure it was not enabling 32 bit applications.

On a whim I tried toggling the setting. It turns out the application pools in IIS were defaulting to an Enable 32-Bit Applications value of False, but IIS was ignoring it on our server for some reason and always ran our service in x86 mode.

Solution

  • Select the app pool.
  • Choose Set Application Pool Defaults... or Advanced Settings....
  • Change Enable 32-Bit Applications to True.
  • Click OK.
  • Choose Set Application Pool Defaults... or Advanced Settings... again.
  • Change Enable 32-Bit Applications back to False.
  • Click OK.

AttributeError: 'module' object has no attribute 'model'

In class poll, you inherited your class from models.model but there's no module in models called that name.

Because Python is case sensitive, you need to use the capital Model instead of model.

class poll(models.Model):
...

Side-by-side plots with ggplot2

There is also multipanelfigure package that is worth to mention. See also this answer.

library(ggplot2)
theme_set(theme_bw())

q1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
q2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
q3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
q4 <- ggplot(mtcars) + geom_bar(aes(carb))

library(magrittr)
library(multipanelfigure)
figure1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")
# show the layout
figure1

figure1 %<>%
  fill_panel(q1, column = 1, row = 1) %<>%
  fill_panel(q2, column = 2, row = 1) %<>%
  fill_panel(q3, column = 1, row = 2) %<>%
  fill_panel(q4, column = 2, row = 2)
figure1

# complex layout
figure2 <- multi_panel_figure(columns = 3, rows = 3, panel_label_type = "upper-roman")
figure2

figure2 %<>%
  fill_panel(q1, column = 1:2, row = 1) %<>%
  fill_panel(q2, column = 3, row = 1) %<>%
  fill_panel(q3, column = 1, row = 2) %<>%
  fill_panel(q4, column = 2:3, row = 2:3)
figure2

Created on 2018-07-06 by the reprex package (v0.2.0.9000).

Dynamically add script tag with src that may include document.write

You can try following code snippet.

function addScript(attribute, text, callback) {
    var s = document.createElement('script');
    for (var attr in attribute) {
        s.setAttribute(attr, attribute[attr] ? attribute[attr] : null)
    }
    s.innerHTML = text;
    s.onload = callback;
    document.body.appendChild(s);
}

addScript({
    src: 'https://www.google.com',
    type: 'text/javascript',
    async: null
}, '<div>innerHTML</div>', function(){});

"’" showing on page instead of " ' "

The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:

htmlText = htmlText.Replace('–', '-');

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

I solved my problem in AngularJS as follows:

var configPopOver = {
        animation: 500,
        container: 'body',
        placement: function (context, source) {
                    var elBounding = source.getBoundingClientRect();
                    var pageWidth = angular.element('body')[0].clientWidth
                    var pageHeith = angular.element('body')[0].clientHeith

                    if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "left";
                    }

                    if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "right";
                    }

                    if (elBounding.top < 110){
                        return "bottom";
                    }

                    return "top";
                },
        html: true
    };

This function do the position of Bootstrap popover float to the best position, based on element position.

Calling a javascript function in another js file

You could consider using the es6 import export syntax. In file 1;

export function f1() {...}

And then in file 2;

import { f1 } from "./file1.js";
f1();

Please note that this only works if you're using <script src="./file2.js" type="module">

You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.

How do I install pip on macOS or OS X?

Install python3 first, then use pip3 to install packages.

brew install python

python3 will be installed, and pip is shipped with it. To use pip to install some package, run the following

pip3 install package

Notice it's pip3 because you want to use python3.

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

Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.

An example from the android documentation:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

How can I check if an InputStream is empty without reading from it?

If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
    //stream not empty
} else {
    //stream empty
} 

If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

HTTP 1.0 vs 1.1

? HTTP 1.0 (1994)

  • It is still in use
  • Can be used by a client that cannot deal with chunked (or compressed) server replies

? HTTP 1.1 (1996- 2015)

  • Formalizes many extensions to version 1.0
  • Supports persistent and pipelined connections
  • Supports chunked transfers, compression/decompression
  • Supports virtual hosting (a server with a single IP Address hosting multiple domains)
  • Supports multiple languages
  • Supports byte-range transfers; useful for resuming interrupted data transfers

HTTP 1.1 is an enhancement of HTTP 1.0. The following lists the four major improvements:

  1. Efficient use of IP addresses, by allowing multiple domains to be served from a single IP address.

  2. Faster response, by allowing a web browser to send multiple requests over a single persistent connection.

  3. Faster response for dynamically-generated pages, by support for chunked encoding, which allows a response to be sent before its total length is known.
  4. Faster response and great bandwidth savings, by adding cache support.

Close Bootstrap Modal

I closed modal Programmatically with this trick

Add a button in modal with data-dismiss="modal" and hide the button with display: none. Here is how it will look like

<div class="modal fade" id="addNewPaymentMethod" role="dialog">
  <div class="modal-dialog">
   .
   .
   .
   <button type="button" id="close-modal" data-dismiss="modal" style="display: none">Close</button>
  </div>
</div>

Now when you want to close modal Programmatically just trigger a click event on that button, which is not visible to user

In Javascript you can trigger click on that button like this:

document.getElementById('close-modal').click();

Server.Mappath in C# classlibrary

Architecturally, System.web should not be referred in Business Logic Layer (BLL). Employ BLL into the solution structure to follow the separate of concern principle so refer System.Web is a bad practice. BLL should not load/run in Asp.net context. Because of the reason you should consider using of System.AppDomain.CurrentDomain.BaseDirectory instead of System.Web.HttpContext.Current.Server.MapPath

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";
}

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

Check if property has attribute

If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)

public class Foo
{
   public string A {get;set;}

   [Special]
   public string B {get;set;}   
}

var type = typeof(Foo);

var specialProperties = type.GetRuntimeProperties()
     .Where(pi => pi.PropertyType == typeof (string) 
      && pi.GetCustomAttributes<Special>(true).Any());

You can then check on the number of properties that have this special property if you need to.

How to change a field name in JSON using Jackson

Jackson

If you are using Jackson, then you can use the @JsonProperty annotation to customize the name of a given JSON property.

Therefore, you just have to annotate the entity fields with the @JsonProperty annotation and provide a custom JSON property name, like this:

@Entity
public class City {

   @Id
   @JsonProperty("value")
   private Long id;

   @JsonProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

JavaEE or JakartaEE JSON-B

JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty annotation:

@Entity
public class City {

   @Id
   @JsonbProperty("value")
   private Long id;

   @JsonbProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

Sql script to find invalid email addresses

SELECT EmailAddress AS ValidEmail
FROM Contacts
WHERE EmailAddress LIKE '%_@__%.__%'
        AND PATINDEX('%[^a-z,0-9,@,.,_,\-]%', EmailAddress) = 0
GO

Please check this link: https://blog.sqlauthority.com/2017/11/12/validate-email-address-sql-server-interview-question-week-147/

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

Event listener for when element becomes visible?

If you just want to run some code when an element becomes visible in the viewport:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

When the element has become visible the intersection observer calls callback and then destroys itself with .disconnect().

Use it like this:

onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

If you're facing this error but your issue is different and you're tired of searching for a long time then this might help you.

If you have changed your database and updated .env file and still facing same issue then you should check C:\xampp\htdocs{your-project-name}\bootstrap\cache\config.php file and replace or remove the old database name and other changed items.

How to print strings with line breaks in java

package test2;

public class main {

    public static void main(String[] args) {
        vehical vehical1 = new vehical("civic", "black","2012");
        System.out.println(vehical1.name+"\n"+vehical1.colour+"\n"+vehical1.model);
    }
}

How to secure an ASP.NET Web API

Have you tried DevDefined.OAuth?

I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.

It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:

1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder extensibility.

2) Build the library and reference it in your Web API project.

3) Create a custom context builder to support building a context from HttpRequestMessage:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;

using DevDefined.OAuth.Framework;

public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
    public WebApiOAuthContextBuilder()
        : base(UriAdjuster)
    {
    }

    public IOAuthContext FromHttpRequest(HttpRequestMessage request)
    {
        var context = new OAuthContext
            {
                RawUri = this.CleanUri(request.RequestUri), 
                Cookies = this.CollectCookies(request), 
                Headers = ExtractHeaders(request), 
                RequestMethod = request.Method.ToString(), 
                QueryParameters = request.GetQueryNameValuePairs()
                    .ToNameValueCollection(), 
            };

        if (request.Content != null)
        {
            var contentResult = request.Content.ReadAsByteArrayAsync();
            context.RawContent = contentResult.Result;

            try
            {
                // the following line can result in a NullReferenceException
                var contentType = 
                    request.Content.Headers.ContentType.MediaType;
                context.RawContentType = contentType;

                if (contentType.ToLower()
                    .Contains("application/x-www-form-urlencoded"))
                {
                    var stringContentResult = request.Content
                        .ReadAsStringAsync();
                    context.FormEncodedParameters = 
                        HttpUtility.ParseQueryString(stringContentResult.Result);
                }
            }
            catch (NullReferenceException)
            {
            }
        }

        this.ParseAuthorizationHeader(context.Headers, context);

        return context;
    }

    protected static NameValueCollection ExtractHeaders(
        HttpRequestMessage request)
    {
        var result = new NameValueCollection();

        foreach (var header in request.Headers)
        {
            var values = header.Value.ToArray();
            var value = string.Empty;

            if (values.Length > 0)
            {
                value = values[0];
            }

            result.Add(header.Key, value);
        }

        return result;
    }

    protected NameValueCollection CollectCookies(
        HttpRequestMessage request)
    {
        IEnumerable<string> values;

        if (!request.Headers.TryGetValues("Set-Cookie", out values))
        {
            return new NameValueCollection();
        }

        var header = values.FirstOrDefault();

        return this.CollectCookiesFromHeaderString(header);
    }

    /// <summary>
    /// Adjust the URI to match the RFC specification (no query string!!).
    /// </summary>
    /// <param name="uri">
    /// The original URI. 
    /// </param>
    /// <returns>
    /// The adjusted URI. 
    /// </returns>
    private static Uri UriAdjuster(Uri uri)
    {
        return
            new Uri(
                string.Format(
                    "{0}://{1}{2}{3}", 
                    uri.Scheme, 
                    uri.Host, 
                    uri.IsDefaultPort ?
                        string.Empty :
                        string.Format(":{0}", uri.Port), 
                    uri.AbsolutePath));
    }
}

4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute attribute:

public override void OnAuthorization(HttpActionContext actionContext)
{
    // the only change I made is use the custom context builder from step 3:
    OAuthContext context = 
        new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);

    try
    {
        provider.AccessProtectedResourceRequest(context);

        // do nothing here
    }
    catch (OAuthException authEx)
    {
        // the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
        // implementation is overloaded to return a problem report string as per
        // the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
               RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
            };
    }
}

I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder which I'm using in my provider) but it should work fine.

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

How to display Base64 images in HTML?

you can put your data directly in a url statment like

src = 'url(imageData)' ;

and to get the image data u can use the php function

$imageContent = file_get_contents("imageDir/".$imgName);

$imageData = base64_encode($imageContent);

so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image

Eclipse error "Could not find or load main class"

I had the same issue and solved it using:

Eclipse Mars
Egit
Github
Maven Project

The Problem was that i made my maven project available to github. It moved my project to my github folder.

Solution:

  • Close Eclipse
  • Delete the metadata folder inside your workspace
  • Restart Eclipse

Start screen will be displayed.

  • Close the start screen
  • Rightclick into package explorer
  • Chose "import maven project",
  • Navigate to your github folder and import the maven project.

After this my project compiled with success.

How to convert Json array to list of objects in c#

you have an unmatched jSon string, if you want to convert into a list, try this

{
    "id": "MyID",

     "values": [
        {
            "id": "100",
            "diaplayName": "MyValue1",
        },
        {
            "id": "200",
            "diaplayName": "MyValue2",
        }
   ]    
}

Django Forms: if not valid, show form with error message

If you render the same view when the form is not valid then in template you can access the form errors using form.errors.

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

An example:

def myView(request):
    form = myForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    return render(request, 'my_template.html', {'form': form})

Regular expression for letters, numbers and - _

The pattern you want is something like (see it on rubular.com):

^[a-zA-Z0-9_.-]*$

Explanation:

  • ^ is the beginning of the line anchor
  • $ is the end of the line anchor
  • [...] is a character class definition
  • * is "zero-or-more" repetition

Note that the literal dash - is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The . also has a different meaning outside character class definitions, but inside, it's just a literal .

References


In PHP

Here's a snippet to show how you can use this pattern:

<?php

$arr = array(
  'screen123.css',
  'screen-new-file.css',
  'screen_new.js',
  'screen new file.css'
);

foreach ($arr as $s) {
  if (preg_match('/^[\w.-]*$/', $s)) {
    print "$s is a match\n";
  } else {
    print "$s is NO match!!!\n";
  };
}

?>

The above prints (as seen on ideone.com):

screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!

Note that the pattern is slightly different, using \w instead. This is the character class for "word character".

API references


Note on specification

This seems to follow your specification, but note that this will match things like ....., etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.

The above regex also matches the empty string. If you need at least one character, then use + (one-or-more) instead of * (zero-or-more) for repetition.

In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.

Amazon Linux: apt-get: command not found

If you're using Amazon Linux it's CentOS-based, which is RedHat-based. RH-based installs use yum not apt-get. Something like yum search httpd should show you the available Apache packages - you likely want yum install httpd24.

Note: Amazon Linux 2 has diverged from CentOS since the writing of this answer, but still uses yum.

How to reverse a 'rails generate'

You can undo a rails generate in the following ways:

  • For the model: rails destroy MODEL
  • For the controller: rails destroy controller_name

Automated testing for REST Api

I implemented many automation cases based on REST Assured , a jave DSL for testing restful service. https://code.google.com/p/rest-assured/

The syntax is easy, it supports json and xml. https://code.google.com/p/rest-assured/wiki/Usage

Before that, I tried SOAPUI and had some issues with the free version. Plus the cases are in xml files which hard to extend and reuse, simply I don't like

What is the opposite of evt.preventDefault();

I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...

$("$theform").submit(function(e) {
    e.preventDefault();
    var $this = $(this);
    $.ajax('/path/to/script.php',
        {
        type: "POST",
        data: { value: $("#input_control").val() }
    }).done(function(response) {
        $this.unbind('submit').submit();
    });
});

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

How to capture the android device screen content?

if you want to do screen capture from Java code in Android app AFAIK you must have Root provileges.

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.

Searching for UUIDs in text with regex

[\w]{8}(-[\w]{4}){3}-[\w]{12} has worked for me in most cases.

Or if you want to be really specific [\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}.

C# getting the path of %AppData%

I don't think putting %AppData% in a string like that will work.

try

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString()

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

How to asynchronously call a method in Java

You can use Future-AsyncResult for this.

@Async
public Future<Page> findPage(String page) throws InterruptedException {
    System.out.println("Looking up " + page);
    Page results = restTemplate.getForObject("http://graph.facebook.com/" + page, Page.class);
    Thread.sleep(1000L);
    return new AsyncResult<Page>(results);
}

Reference: https://spring.io/guides/gs/async-method/

SQLite DateTime comparison

Below are the methods to compare the dates but before that we need to identify the format of date stored in DB

I have dates stored in MM/DD/YYYY HH:MM format so it has to be compared in that format

  1. Below query compares the convert the date into MM/DD/YYY format and get data from last five days till today. BETWEEN operator will help and you can simply specify start date AND end date.

    select * from myTable where myColumn BETWEEN strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day') AND strftime('%m/%d/%Y %H:%M',datetime('now','localtime')); 
    
  2. Below query will use greater than operator (>).

      select * from myTable where myColumn > strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day');  

All the computation I have done is using current time, you can change the format and date as per your need.

Hope this will help you

Summved

Android: Background Image Size (in Pixel) which Support All Devices

GIMP tool is exactly what you need to create the images for different pixel resolution devices.

Follow these steps:

  1. Open the existing image in GIMP tool.
  2. Go to "Image" menu, and select "Scale Image..."
  3. Use below pixel dimension that you need:

    xxxhdpi: 1280x1920 px

    xxhdpi: 960x1600 px

    xhdpi: 640x960 px

    hdpi: 480x800 px

    mdpi: 320x480 px

    ldpi: 240x320 px

  4. Then "Export" the image from "File" menu.

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

Convert list to dictionary using linq and not worrying about duplicates

Starting from Carra's solution you can also write it as:

foreach(var person in personList.Where(el => !myDictionary.ContainsKey(el.FirstAndLastName)))
{
    myDictionary.Add(person.FirstAndLastName, person);
}

Room persistance library. Delete all

If want to delete an entry from the the table in Room simply call this function,

@Dao
public interface myDao{
    @Delete
    void delete(MyModel model);
}

Update: And if you want to delete complete table, call below function,

  @Query("DELETE FROM MyModel")
  void delete();

Note: Here MyModel is a Table Name.

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

Parsing JSON array into java.util.List with Gson

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

What is WEB-INF used for in a Java EE web application?

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

This means that WEB-INF resources are accessible to the resource loader of your Web-Application and not directly visible for the public.

This is why a lot of projects put their resources like JSP files, JARs/libraries and their own class files or property files or any other sensitive information in the WEB-INF folder. Otherwise they would be accessible by using a simple static URL (usefull to load CSS or Javascript for instance).

Your JSP files can be anywhere though from a technical perspective. For instance in Spring you can configure them to be in WEB-INF explicitly:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" 
    p:suffix=".jsp" >
</bean>

The WEB-INF/classes and WEB-INF/lib folders mentioned in Wikipedia's WAR files article are examples of folders required by the Servlet specification at runtime.

It is important to make the difference between the structure of a project and the structure of the resulting WAR file.

The structure of the project will in some cases partially reflect the structure of the WAR file (for static resources such as JSP files or HTML and JavaScript files, but this is not always the case.

The transition from the project structure into the resulting WAR file is done by a build process.

While you are usually free to design your own build process, nowadays most people will use a standardized approach such as Apache Maven. Among other things Maven defines defaults for which resources in the project structure map to what resources in the resulting artifact (the resulting artifact is the WAR file in this case). In some cases the mapping consists of a plain copy process in other cases the mapping process includes a transformation, such as filtering or compiling and others.

One example: The WEB-INF/classes folder will later contain all compiled java classes and resources (src/main/java and src/main/resources) that need to be loaded by the Classloader to start the application.

Another example: The WEB-INF/lib folder will later contain all jar files needed by the application. In a maven project the dependencies are managed for you and maven automatically copies the needed jar files to the WEB-INF/lib folder for you. That explains why you don't have a lib folder in a maven project.

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

Simple way to measure cell execution time in ipython notebook

I simply added %%time at the beginning of the cell and got the time. You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s

get dictionary key by value

You could do that:

  1. By looping through all the KeyValuePair<TKey, TValue>'s in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary)
  2. Use two dictionaries, one for value-to-key mapping and one for key-to-value mapping (which would take up twice as much space in memory).

Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.

Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.

Is there any reason you can't reverse the key-value relationship?

How to calculate the sentence similarity using word2vec model of gensim with python

If you are using word2vec, you need to calculate the average vector for all words in every sentence/document and use cosine similarity between vectors:

import numpy as np
from scipy import spatial

index2word_set = set(model.wv.index2word)

def avg_feature_vector(sentence, model, num_features, index2word_set):
    words = sentence.split()
    feature_vec = np.zeros((num_features, ), dtype='float32')
    n_words = 0
    for word in words:
        if word in index2word_set:
            n_words += 1
            feature_vec = np.add(feature_vec, model[word])
    if (n_words > 0):
        feature_vec = np.divide(feature_vec, n_words)
    return feature_vec

Calculate similarity:

s1_afv = avg_feature_vector('this is a sentence', model=model, num_features=300, index2word_set=index2word_set)
s2_afv = avg_feature_vector('this is also sentence', model=model, num_features=300, index2word_set=index2word_set)
sim = 1 - spatial.distance.cosine(s1_afv, s2_afv)
print(sim)

> 0.915479828613

How to get coordinates of an svg element?

svg.selectAll("rect")
.attr('x',function(d,i){
    // get x coord
    console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
    // get y coord
    console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
    // get dx coord
    console.log(parseInt(d3.select(this).attr('dx')))
})

Pythonically add header to a csv file

You just add one additional row before you execute the loop. This row contains your CSV file header name.

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:    
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])   
#Data add in csv file       
     for x in xrange(rows):
         writer.writerow([g() for g in generators])

Round float to x decimals?

I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...

The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places) is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:

>>> round(52.15, 1)
52.1

With a naive understanding of what round does, this looks wrong: surely it should be rounding up to 52.2 rather than down to 52.1? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.

So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):

  1. First the numeric literal 52.15 gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47, or 52.14999999999999857891452847979962825775146484375.

  2. Internally as the first step of the round operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15, we end up rounding down and getting a string 52.1. This explains why we're getting 52.1 as the final output instead of 52.2.

  3. Then in the second step of the round operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1, which is now 7332423143312589 * 2**-47, or 52.10000000000000142108547152020037174224853515625.

  4. Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1 as the final output.

In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:

>>> x = 15.34509809234
>>> x
15.34509809234

Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:

>>> round(52.15, 1)
52.200000000000003

Not only do we round in the opposite direction, getting 52.2 instead of 52.1, but the displayed value doesn't even print as 52.2! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round that's broken, it's user expectations. (Okay, okay, round is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)

Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.

So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.

  • If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:

    >>> format(66.66666666666, '.4f')
    '66.6667'
    >>> format(1.29578293, '.6f')
    '1.295783'
    

    Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.

    >>> format(52.15, '.1f')
    '52.1'
    
  • If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal type. Doing a decimal round on the Decimal type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal module gives you better control of the rounding mode. In Python 3, round does the job directly. In Python 2, you need the quantize method.

    >>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
    Decimal('66.6667')
    >>> Decimal('1.29578293').quantize(Decimal('1e-6'))
    Decimal('1.295783')
    
  • In rare cases, the two-argument version of round really is what you want: perhaps you're binning floats into bins of size 0.01, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round builtin based on those cases alone.

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

How do I simulate a hover with a touch in touch enabled browsers?

The mouse hover effect cannot be implemented in touch device . When I'm appeared with same situation in safari ios I used :active in css to make effect.

ie.

p:active {
  color:red;
}

In my case its working .May be this is also the case that can be used with out using javascript. Just give a try.

Passing variables to the next middleware using next() in Express.js

That's because req and res are two different objects.

You need to look for the property on the same object you added it to.

The equivalent of wrap_content and match_parent in flutter?

Use FractionallySizedBox widget.

FractionallySizedBox(
  widthFactor: 1.0, // width w.r.t to parent
  heightFactor: 1.0,  // height w.r.t to parent
  child: *Your Child Here*
}

This widget is also very useful when you want to size your child at a fractional of its parent's size.

Example:

If you want the child to occupy 50% width of its parent, provide widthFactor as 0.5

How do I make an input field accept only letters in javaScript?

Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.

Get size of folder or file

  • Works for Android and Java
  • Works for both folders and files
  • Checks for null pointer everywhere where needed
  • Ignores symbolic link aka shortcuts
  • Production ready!

Source code:

   public long fileSize(File root) {
        if(root == null){
            return 0;
        }
        if(root.isFile()){
            return root.length();
        }
        try {
            if(isSymlink(root)){
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        long length = 0;
        File[] files = root.listFiles();
        if(files == null){
            return 0;
        }
        for (File file : files) {
            length += fileSize(file);
        }

        return length;
    }

    private static boolean isSymlink(File file) throws IOException {
        File canon;
        if (file.getParent() == null) {
            canon = file;
        } else {
            File canonDir = file.getParentFile().getCanonicalFile();
            canon = new File(canonDir, file.getName());
        }
        return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
    }

Asp.net Hyperlink control equivalent to <a href="#"></a>

Just write <a href="#"></a>.

If that's what you want, you don't need a server-side control.

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

If you have the OAuth PHP library installed, you don't have to worry about forming the request yourself.

$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);

$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());

print_r($twitter_data);

For more information, check out The docs or their example. You can use pecl install oauth to get the library.

What killed my process and why?

I encountered this problem lately. Finally, I found my processes were killed just after Opensuse zypper update was called automatically. To disable zypper update solved my problem.

How do I check whether a checkbox is checked in jQuery?

Simply use it like below

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });

Javascript: how to validate dates in format MM-DD-YYYY?

<script language = "Javascript">
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : dd/mm/yyyy")
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("Please enter a valid month")
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        alert("Please enter a valid day")
        return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date")
        return false
    }
return true
}

function ValidateForm(){
    var dt=document.frmSample.txtDateenter code here
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
    return true
 }

</script>

install cx_oracle for python

If you are trying to install in MAC , just unzip the Oracle client which you downloaded and place it into the folder where you written python scripts. it will start working.

There is too much problem of setting up environmental variables. It worked for me.

Hope this helps.

Thanks

How to represent multiple conditions in a shell if statement?

Classic technique (escape metacharacters):

if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi

I've enclosed the references to $g in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a and -o makes it correct even without them.

Note that the -a and -o operators are part of the POSIX specification for test, aka [, mainly for backwards compatibility (since they were a part of test in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a and -o with its own alternative operators that take arguments.


With some care, you can use the more modern [[ operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.

for g in 1 2 3
do
    for c in 123 456 789
    do
        if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
        then echo "g = $g; c = $c; true"
        else echo "g = $g; c = $c; false"
        fi
    done
done

Example run, using Bash 3.2.57 on Mac OS X:

g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false

You don't need to quote the variables in [[ as you do with [ because it is not a separate command in the same way that [ is.


Isn't it a classic question?

I would have thought so. However, there is another alternative, namely:

if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi

Indeed, if you read the 'portable shell' guidelines for the autoconf tool or related packages, this notation — using '||' and '&&' — is what they recommend. I suppose you could even go so far as:

if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi

Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then blocks.

How to get the max of two values in MySQL?

You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

select 
    if(
        fieldA is NULL, 
        if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
        if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
    ) as maxValue

You can change NULL to your preferred default value (if both values is NULL).

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

Try

var ts = TimeSpan.Parse(stringTime);

With a newer .NET you also have

TimeSpan ts;

if(!TimeSpan.TryParse(stringTime, out ts)){
     // throw exception or whatnot
}
// ts now has a valid format

This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

In my case I was trying to require this package, and I was getting the PHP Fatal error: Allowed memory size of.

I found it easy to run like this and you don't have to update the PHP INI file.

example: COMPOSER_MEMORY_LIMIT=-1 composer require huddledigital/zendesk-laravel

Hope this help someone.

Vim autocomplete for Python

I found a good choice to be coc.nvim with the python language server.

It takes a bit of effort to set up. I got frustrated with jedi-vim, because it would always freeze vim for a bit when completing. coc.nvim doesn't do it because it's asyncronous, meaning that . It also gives you linting for your code. It supports many other languages and is highly configurable.

The python language server uses jedi so you get the same completion as you would get from jedi.

mysqldump data only

If you just want the INSERT queries, use the following:

mysqldump --skip-triggers --compact --no-create-info

Commit empty folder structure (with git)

This is easy.

tell .gitignore to ignore everything except .gitignore and the folders you want to keep. Put .gitignore into folders that you want to keep in the repo.

Contents of the top-most .gitignore:

# ignore everything except .gitignore and folders that I care about:
*
!images*
!.gitignore

In the nested images folder this is your .gitignore:

# ignore everything except .gitignore
*
!.gitignore

Note, you must spell out in the .gitignore the names of the folders you don't want to be ignored in the folder where that .gitignore is located. Otherwise they are, obviously, ignored.

Your folders in the repo will, obviously, NOT be empty, as each one will have .gitignore in it, but that part can be ignored, right. :)

Laravel: PDOException: could not find driver

Solution 1:

1. php -v

Output: PHP 7.3.11-1+ubuntu16.04.1+deb.sury.org+1 (cli)

2. sudo apt-get install php7.3-mysql

Solution 2:

Check your DB credentials like DB Name, DB User, DB Password

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

How do I do base64 encoding on iOS?

This is a good use case for Objective C categories.

For Base64 encoding:

#import <Foundation/NSString.h>

@interface NSString (NSStringAdditions)

+ (NSString *) base64StringFromData:(NSData *)data length:(int)length;

@end

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

#import "NSStringAdditions.h"

static char base64EncodingTable[64] = {
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

@implementation NSString (NSStringAdditions)

+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
  unsigned long ixtext, lentext;
  long ctremaining;
  unsigned char input[3], output[4];
  short i, charsonline = 0, ctcopy;
  const unsigned char *raw;
  NSMutableString *result;

  lentext = [data length]; 
  if (lentext < 1)
    return @"";
  result = [NSMutableString stringWithCapacity: lentext];
  raw = [data bytes];
  ixtext = 0; 

  while (true) {
    ctremaining = lentext - ixtext;
    if (ctremaining <= 0) 
       break;        
    for (i = 0; i < 3; i++) { 
       unsigned long ix = ixtext + i;
       if (ix < lentext)
          input[i] = raw[ix];
       else
  input[i] = 0;
  }
  output[0] = (input[0] & 0xFC) >> 2;
  output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
  output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
  output[3] = input[2] & 0x3F;
  ctcopy = 4;
  switch (ctremaining) {
    case 1: 
      ctcopy = 2; 
      break;
    case 2: 
      ctcopy = 3; 
      break;
  }

  for (i = 0; i < ctcopy; i++)
     [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];

  for (i = ctcopy; i < 4; i++)
     [result appendString: @"="];

  ixtext += 3;
  charsonline += 4;

  if ((length > 0) && (charsonline >= length))
    charsonline = 0;
  }     
  return result;
}

@end

For Base64 decoding:

#import <Foundation/Foundation.h>

@class NSString;

@interface NSData (NSDataAdditions)

+ (NSData *) base64DataFromString:(NSString *)string;

@end

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

#import "NSDataAdditions.h"

@implementation NSData (NSDataAdditions)

+ (NSData *)base64DataFromString: (NSString *)string
{
    unsigned long ixtext, lentext;
    unsigned char ch, inbuf[4], outbuf[3];
    short i, ixinbuf;
    Boolean flignore, flendtext = false;
    const unsigned char *tempcstring;
    NSMutableData *theData;

    if (string == nil)
    {
        return [NSData data];
    }

    ixtext = 0;

    tempcstring = (const unsigned char *)[string UTF8String];

    lentext = [string length];

    theData = [NSMutableData dataWithCapacity: lentext];

    ixinbuf = 0;

    while (true)
    {
        if (ixtext >= lentext)
        {
            break;
        }

        ch = tempcstring [ixtext++];

        flignore = false;

        if ((ch >= 'A') && (ch <= 'Z'))
        {
            ch = ch - 'A';
        }
        else if ((ch >= 'a') && (ch <= 'z'))
        {
            ch = ch - 'a' + 26;
        }
        else if ((ch >= '0') && (ch <= '9'))
        {
            ch = ch - '0' + 52;
        }
        else if (ch == '+')
        {
            ch = 62;
        }
        else if (ch == '=')
        {
            flendtext = true;
        }
        else if (ch == '/')
        {
            ch = 63;
        }
        else
        {
            flignore = true; 
        }

        if (!flignore)
        {
            short ctcharsinbuf = 3;
            Boolean flbreak = false;

            if (flendtext)
            {
                if (ixinbuf == 0)
                {
                    break;
                }

                if ((ixinbuf == 1) || (ixinbuf == 2))
                {
                    ctcharsinbuf = 1;
                }
                else
                {
                    ctcharsinbuf = 2;
                }

                ixinbuf = 3;

                flbreak = true;
            }

            inbuf [ixinbuf++] = ch;

            if (ixinbuf == 4)
            {
                ixinbuf = 0;

                outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
                outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
                outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);

                for (i = 0; i < ctcharsinbuf; i++)
                {
                    [theData appendBytes: &outbuf[i] length: 1];
                }
            }

            if (flbreak)
            {
                break;
            }
        }
    }

    return theData;
}

    @end

Principal Component Analysis (PCA) in Python

I posted my answer even though another answer has already been accepted; the accepted answer relies on a deprecated function; additionally, this deprecated function is based on Singular Value Decomposition (SVD), which (although perfectly valid) is the much more memory- and processor-intensive of the two general techniques for calculating PCA. This is particularly relevant here because of the size of the data array in the OP. Using covariance-based PCA, the array used in the computation flow is just 144 x 144, rather than 26424 x 144 (the dimensions of the original data array).

Here's a simple working implementation of PCA using the linalg module from SciPy. Because this implementation first calculates the covariance matrix, and then performs all subsequent calculations on this array, it uses far less memory than SVD-based PCA.

(the linalg module in NumPy can also be used with no change in the code below aside from the import statement, which would be from numpy import linalg as LA.)

The two key steps in this PCA implementation are:

  • calculating the covariance matrix; and

  • taking the eivenvectors & eigenvalues of this cov matrix

In the function below, the parameter dims_rescaled_data refers to the desired number of dimensions in the rescaled data matrix; this parameter has a default value of just two dimensions, but the code below isn't limited to two but it could be any value less than the column number of the original data array.


def PCA(data, dims_rescaled_data=2):
    """
    returns: data transformed in 2 dims/columns + regenerated original data
    pass in: data as 2D NumPy array
    """
    import numpy as NP
    from scipy import linalg as LA
    m, n = data.shape
    # mean center the data
    data -= data.mean(axis=0)
    # calculate the covariance matrix
    R = NP.cov(data, rowvar=False)
    # calculate eigenvectors & eigenvalues of the covariance matrix
    # use 'eigh' rather than 'eig' since R is symmetric, 
    # the performance gain is substantial
    evals, evecs = LA.eigh(R)
    # sort eigenvalue in decreasing order
    idx = NP.argsort(evals)[::-1]
    evecs = evecs[:,idx]
    # sort eigenvectors according to same index
    evals = evals[idx]
    # select the first n eigenvectors (n is desired dimension
    # of rescaled data array, or dims_rescaled_data)
    evecs = evecs[:, :dims_rescaled_data]
    # carry out the transformation on the data using eigenvectors
    # and return the re-scaled data, eigenvalues, and eigenvectors
    return NP.dot(evecs.T, data.T).T, evals, evecs

def test_PCA(data, dims_rescaled_data=2):
    '''
    test by attempting to recover original data array from
    the eigenvectors of its covariance matrix & comparing that
    'recovered' array with the original data
    '''
    _ , _ , eigenvectors = PCA(data, dim_rescaled_data=2)
    data_recovered = NP.dot(eigenvectors, m).T
    data_recovered += data_recovered.mean(axis=0)
    assert NP.allclose(data, data_recovered)


def plot_pca(data):
    from matplotlib import pyplot as MPL
    clr1 =  '#2026B2'
    fig = MPL.figure()
    ax1 = fig.add_subplot(111)
    data_resc, data_orig = PCA(data)
    ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)
    MPL.show()

>>> # iris, probably the most widely used reference data set in ML
>>> df = "~/iris.csv"
>>> data = NP.loadtxt(df, delimiter=',')
>>> # remove class labels
>>> data = data[:,:-1]
>>> plot_pca(data)

The plot below is a visual representation of this PCA function on the iris data. As you can see, a 2D transformation cleanly separates class I from class II and class III (but not class II from class III, which in fact requires another dimension).

enter image description here

PHP/MySQL insert row then get 'id'

Another possible answer will be:

When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.

By this method, you don't have to worry about the id, it'll be made automatically.

For example (taken from w3schools )

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

Hope this will be helpful for someone.

Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Is a LINQ statement faster than a 'foreach' loop?

I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }


    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion


    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}

TextFX menu is missing in Notepad++

For 32 bit Notepad++ only

Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.

It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.

Event handlers for Twitter Bootstrap dropdowns?

Twitter bootstrap is meant to give a baseline functionality, and provides only basic javascript plugins that do something on screen. Any additional content or functionality, you'll have to do yourself.

<div class="btn-group">
  <button class="btn dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href="#" id="action-1">Action</a></li>
    <li><a href="#" id="action-2">Another action</a></li>
    <li><a href="#" id="action-3">Something else here</a></li>
  </ul>
</div><!-- /btn-group -->

and then with jQuery

jQuery("#action-1").click(function(e){
//do something
e.preventDefault();
});

Nesting await in Parallel.ForEach

After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}

Opening a CHM file produces: "navigation to the webpage was canceled"

There are apparently different levels of authentication. Most articles I read tell you to set the MaxAllowedZone to '1' which means that local machine zone and intranet zone are allowed but '4' allows access for 'all' zones.

For more info, read this article: https://support.microsoft.com/en-us/kb/892675

This is how my registry looks (I wasn't sure it would work with the wild cards but it seems to work for me):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"UrlAllowList"="\\\\<network_path_root>;\\\\<network_path_root>\*;\\ies-inc.local;http://www.*;http://*;https://www.*;https://*;"

As an additional note, weirdly the "UrlAllowList" key was required to make this work on another PC but not my test one. It's probably not required at all but when I added it, it fixed the problem. The user may have not closed the original file or something like that. So just a consideration. I suggest try the least and test it, then add if needed. Once you confirm, you can deploy if needed. Good Luck!

Edit: P.S. Another method that worked was mapping the path to the network locally by using mklink /d (symbolic linking in Windows 7 or newer) but mapping a network drive letter (Z: for testing) did not work. Just food for thought and I did not have to 'Unblock' any files. Also the accepted 'Solution' did not resolve the issue for me.

CSS ''background-color" attribute not working on checkbox inside <div>

My solution

Initially posted here.

_x000D_
_x000D_
input[type="checkbox"] {_x000D_
  cursor: pointer;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  outline: 0;_x000D_
  background: lightgray;_x000D_
  height: 16px;_x000D_
  width: 16px;_x000D_
  border: 1px solid white;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked {_x000D_
  background: #2aa1c0;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:hover {_x000D_
  filter: brightness(90%);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled {_x000D_
  background: #e6e6e6;_x000D_
  opacity: 0.6;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:after {_x000D_
  content: '';_x000D_
  position: relative;_x000D_
  left: 40%;_x000D_
  top: 20%;_x000D_
  width: 15%;_x000D_
  height: 40%;_x000D_
  border: solid #fff;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  transform: rotate(45deg);_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked:after {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled:after {_x000D_
  border-color: #7b7b7b;_x000D_
}
_x000D_
<input type="checkbox"><br>_x000D_
<input type="checkbox" checked><br>_x000D_
<input type="checkbox" disabled><br>_x000D_
<input type="checkbox" disabled checked><br>
_x000D_
_x000D_
_x000D_

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

How to inflate one view with a layout

AttachToRoot Set to True

Just think we specified a button in an XML layout file with its layout width and layout height set to match_parent.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

On This Buttons Click Event We Can Set Following Code to Inflate Layout on This Activity.

LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.yourlayoutname, this);

Hope this solution works for you.!

How to set user environment variables in Windows Server 2008 R2 as a normal user?

In command line prompt:

set __COMPAT_LAYER=RUNASINVOKER
SystemPropertiesAdvanced.exe

Now you can set user environment variables.

How do I generate random number for each row in a TSQL Select?

RAND(CHECKSUM(NEWID()))

The above will generate a (pseudo-) random number between 0 and 1, exclusive. If used in a select, because the seed value changes for each row, it will generate a new random number for each row (it is not guaranteed to generate a unique number per row however).

Example when combined with an upper limit of 10 (produces numbers 1 - 10):

CAST(RAND(CHECKSUM(NEWID())) * 10 as INT) + 1

Transact-SQL Documentation:

  1. CAST(): https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
  2. RAND(): http://msdn.microsoft.com/en-us/library/ms177610.aspx
  3. CHECKSUM(): http://msdn.microsoft.com/en-us/library/ms189788.aspx
  4. NEWID(): https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

You can use this, it works fine:

<input type="date" class="form1"  
  value="{{date | date:MM/dd/yyyy}}"
  ng-model="date" 
  name="id" 
  validatedateformat 
  data-date-format="mm/dd/yyyy"
  maxlength="10" 
  id="id" 
  calendar 
  maxdate="todays"
  ng-click="openCalendar('id')">
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
    </span>
</input>

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

HttpUtility does not exist in the current context

In order to resolve this, Kindly go to the below path

Project-->Properties-->Application-->TargetFramework

and change the Framework to ".NET Framework 4".

Once you do this, the project will close and re-open.

This should solve the error

(but for some reason @Karan Modi's answer does not...)

next right-click the references tab in the solution explorer and choose add reference,

choose "System.Web"

(declaring the namespace directly by "using System.Web;" doesnt seems to be enough...you have to add it to the solution explorer...i cant understand why - which is no surprise because i am a cobol programmer..

Checking for a null int value from a Java ResultSet

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

e.g for an Oracle database, use NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

Is there an easy way to strike through text in an app widget?

It is really easy if you are using strings:

<string name="line"> Not crossed <strike> crossed </strike> </string>

And then just:

<TextView 
        ...
         android:text="@string/line"
 />

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

function get_json(txt)
{  var data

   try     {  data = eval('('+txt+')'); }
   catch(e){  data = false;             }

   return data;
}

If there are errors, return false.

If there are no errors, return json data

Replacing objects in array

Since you're using Lodash you could use _.map and _.find to make sure major browsers are supported.

In the end I would go with something like:

_x000D_
_x000D_
function mergeById(arr) {_x000D_
  return {_x000D_
    with: function(arr2) {_x000D_
      return _.map(arr, item => {_x000D_
        return _.find(arr2, obj => obj.id === item.id) || item_x000D_
      })_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
var result = mergeById([{id:'124',name:'qqq'}, _x000D_
           {id:'589',name:'www'}, _x000D_
           {id:'45',name:'eee'},_x000D_
           {id:'567',name:'rrr'}])_x000D_
    .with([{id:'124',name:'ttt'}, {id:'45',name:'yyy'}])_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://raw.githubusercontent.com/lodash/lodash/4.13.1/dist/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How to access the ith column of a NumPy multidimensional array?

You could also transpose and return a row:

In [4]: test.T[0]
Out[4]: array([1, 3, 5])

Command not found after npm install in zsh

I've solved this by brew upgrade node

SQL - Query to get server's IP address

SELECT  
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address 

The code here Will give you the IP Address;

This will work for a remote client request to SQL 2008 and newer.

If you have Shared Memory connections allowed, then running above on the server itself will give you

  • "Shared Memory" as the value for 'net_transport', and
  • NULL for 'local_net_address', and
  • '<local machine>' will be shown in 'client_net_address'.

'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.

I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.

How to fix apt-get: command not found on AWS EC2?

I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.

Align DIV to bottom of the page

Right I think I know what you mean so lets see....

HTML:

<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>
</div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
div {
    outline: 1px solid;
}
#con {
   min-height:100%;
   position:relative;
}
#content {
   height: 1000px; /* Changed this height */
   padding-bottom:60px;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
}

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.

DEMO HERE

This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.

DEMO HERE

So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

How to create unique keys for React elements?

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
    });

Wherever you're lopping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, As pointed by the user Martin Dawson in the comment below, This is not always ideal.

So whats the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

How can I stop redis-server?

Option 1: go to redis installation directory and navigate to src , in my case :

/opt/redis3/src/redis-cli -p 6379 shutdown

where 6379 is the default port.

Option 2: find redis process and kill

ps aux | grep redis-server

t6b3fg   22292  0.0  0.0 106360  1588 pts/0    S+   01:19   0:00 /bin/sh /sbin/service redis start
t6b3fg   22299  0.0  0.0  11340  1200 pts/0    S+   01:19   0:00 /bin/sh /etc/init.d/redis start

And Then initiate kill:

kill -9 22292

kill -9 22299

I'm using Centos 6.7 , x86_64

hope it helps

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Lock, mutex, semaphore... what's the difference?

It is a general vision. Details are depended on real language realisation

lock - thread synchronization tool. When thread get a lock it becomes a single thread which is able to execute a block of code. All others thread are blocked. Only thread which owns by lock can unlock it

mutex - mutual exclusion lock. It is a kind of lock. On some languages it is inter-process mechanism, on some languages it is a synonym of lock. For example Java uses lock in synchronised and java.util.concurrent.locks.Lock

semaphore - allows a number of threads to access a shared resource. You can find that mutex also can be implemented by semaphore. It is a standalone object which manage an access to shared resource. You can find that any thread can signal and unblock. Also it is used for signalling

[iOS lock, mutex, semaphore]

WPF Label Foreground Color

The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:

<StackPanel>
    <Label Foreground="Red">Red text</Label>
    <Label Foreground="Blue">Blue text</Label>
</StackPanel>

In summary, No, there was nothing wrong with your snippet.

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

Get property value from string using reflection

public static TValue GetFieldValue<TValue>(this object instance, string name)
{
    var type = instance.GetType(); 
    var field = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.FieldType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}

public static TValue GetPropertyValue<TValue>(this object instance, string name)
{
    var type = instance.GetType();
    var field = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.PropertyType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}

How do I delete multiple rows in Entity Framework (without foreach)

EF 6.1

public void DeleteWhere<TEntity>(Expression<Func<TEntity, bool>> predicate = null) 
where TEntity : class
{
    var dbSet = context.Set<TEntity>();
    if (predicate != null)
        dbSet.RemoveRange(dbSet.Where(predicate));
    else
        dbSet.RemoveRange(dbSet);

    context.SaveChanges();
} 

Usage:

// Delete where condition is met.
DeleteWhere<MyEntity>(d => d.Name == "Something");

Or:

// delete all from entity
DeleteWhere<MyEntity>();

How do I remove accents from characters in a PHP string?

One of the tricks I stumbled upon on the web was using htmlentities then stripping the encoded character :

$stripped = preg_replace('`&[^;]+;`','',htmlentities($string));

Not perfect but it does work well in some case.

But, you're writing about creating an URL string, so urlencode and its counterpart urldecode may be better. Or, if you are creating a query string, use this last function : http_build_query.

How do you perform address validation?

There are companies that provide this service. Service bureaus that deal with mass mailing will scrub an entire mailing list to that it's in the proper format, which results in a discount on postage. The USPS sells databases of address information that can be used to develop custom solutions. They also have lists of approved vendors who provide this kind of software and service.

There are some (but not many) packages that have APIs for hooking address validation into your software.

However, you're right that its a pretty nasty problem.

http://www.usps.com/ncsc/ziplookup/vendorslicensees.htm

IsNullOrEmpty with Object

I found that DataGridViewTextBox values and some JSON objects don't equal Null but instead are "{}" values. Comparing them to Null doesn't work but using these do the trick:

if (cell.Value is System.DBNull)

if (cell.Value == System.DBNull.Value)

A good excerpt I found concerning the difference between Null and DBNull:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

You can learn more about the DBNull class here.

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

Remove all the elements that occur in one list from another

One way is to use sets:

>>> set([1,2,6,8]) - set([2,3,5,8])
set([1, 6])

Note, however, that sets do not preserve the order of elements, and cause any duplicated elements to be removed. The elements also need to be hashable. If these restrictions are tolerable, this may often be the simplest and highest performance option.

How do you pass view parameters when navigating from an action in JSF2?

You can do it using Primefaces like this :

<p:button 
      outcome="/page2.xhtml?faces-redirect=true&amp;id=#{myBean.id}">
</p:button>

How to find MAC address of an Android device programmatically

Here the Kotlin version of Arth Tilvas answer:

fun getMacAddr(): String {
    try {
        val all = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (nif in all) {
            if (!nif.getName().equals("wlan0", ignoreCase=true)) continue

            val macBytes = nif.getHardwareAddress() ?: return ""

            val res1 = StringBuilder()
            for (b in macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b))
            }

            if (res1.length > 0) {
                res1.deleteCharAt(res1.length - 1)
            }
            return res1.toString()
        }
    } catch (ex: Exception) {
    }

    return "02:00:00:00:00:00"
}

It says that TypeError: document.getElementById(...) is null

You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting

$(document).ready(
    function()
    {
        document.getElementById(elmId).innerHTML = value;
    }
);

Understanding checked vs unchecked exceptions in Java

I think that checked exceptions are a good reminder for the developer that uses an external library that things can go wrong with the code from that library in exceptional situations.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

How to hide action bar before activity is created, and then show it again?

I was also trying to hide Action Bar on Android 2.2, but none of these solution worked. Everything ends with a crash. I checked the DDMS LOg, It was telling me to use 'Theme.AppCompat'.At last I Solved the problem by changing the android:theme="@android:style/Theme.Holo.Light.NoActionBar"Line

into android:theme="@style/Theme.AppCompat.NoActionBar"and it worked, but the the Interface was dark.

then i tried android:theme="@style/Theme.AppCompat.Light.NoActionBar" and finally got what i wanted.

After that when I Searched about 'AppCompat' on Developer Site I got This.

So I think the Solution for Android 2.2 is

<activity
    android:name=".MainActivity"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

And Sorry for my bad English Like Always.

Integrating CSS star rating into an HTML form

I'm going to say right off the bat that you will not be able to achieve the look they have with radio buttons with strictly CSS.

You could, however, stick to the list style in the example you posted and replace the anchors with clickable spans that would trigger a javascript event that would in turn save that rating to your database via ajax.

If you went that route you would probably also want to save a cookie to the users machine so that they could not submit over and over again to your database. That would prevent them from submitting more than once at least until they deleted their cookies.

But of course there are many ways to address this problem. This is just one of them. Hope that helps.

Tuples( or arrays ) as Dictionary keys in C#

The good, clean, fast, easy and readable ways is:

  • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
  • just make a simple key class derived from a tuple.

add something similar like this:

public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
    public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }

    public TypeA DataA => Item1; 

    public TypeB DataB => Item2;

    public TypeC DataC => Item3;
}

So you can use it with dictionary:

var myDictinaryData = new Dictionary<myKey, string>()
{
    {new myKey(1, 2, 3), "data123"},
    {new myKey(4, 5, 6), "data456"},
    {new myKey(7, 8, 9), "data789"}
};
  • You also can use it in contracts
  • as a key for join or groupings in linq
  • going this way you never ever mistype order of Item1, Item2, Item3 ...
  • you no need to remember or look into to code to understand where to go to get something
  • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

How to set Python's default version to 3.x on OS X?

The following worked for me

cd /usr/local/bin
mv python python.old
ln -s python3 python

Get method arguments using Spring AOP?

If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.

If you have to log a specific arg, you can annoted it and then recover its value like this :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
 String methodName() default "";
}

@Aspect
public class YourAspect {

 @Around("...")
 public Object around(ProceedingJoinPoint point) throws Throwable {
  Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
  Object[] args = point.getArgs();
  StringBuilder data = new StringBuilder();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    for (int argIndex = 0; argIndex < args.length; argIndex++) {
        for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
            if (!(paramAnnotation instanceof Data)) {
                continue;
            }
            Data dataAnnotation = (Data) paramAnnotation;
            if (dataAnnotation.methodName().length() > 0) {
                Object obj = args[argIndex];
                Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
                data.append(dataMethod.invoke(obj));
                continue;
            }
            data.append(args[argIndex]);
        }
    }
 }
}

Examples of use :

public void doSomething(String someValue, @Data String someData, String otherValue) {
    // Apsect will log value of someData param
}

public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
    // Apsect will log returned value of someData.id() method
}

HTTP error 403 in Python 3 Web Scraping

This is probably because of mod_security or some similar server security feature which blocks known spider/bot user agents (urllib uses something like python urllib/3.3.0, it's easily detected). Try setting a known browser user agent with:

from urllib.request import Request, urlopen

req = Request('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

This works for me.

By the way, in your code you are missing the () after .read in the urlopen line, but I think that it's a typo.

TIP: since this is exercise, choose a different, non restrictive site. Maybe they are blocking urllib for some reason...

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

How can I make robocopy silent in the command line except for progress?

A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).

Robocopy src dest > output.log
del output.log

Using Position Relative/Absolute within a TD?

With regards to your second attempt, did you try using vertical align ? Either

<td valign="bottom">

or with css

vertical-align:bottom

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

get the margin size of an element with jquery

From jQuery's website

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

Laravel: Using try...catch with DB::transaction()

You could wrapping the transaction over try..catch or even reverse them, here my example code I used to in laravel 5,, if you look deep inside DB:transaction() in Illuminate\Database\Connection that the same like you write manual transaction.

Laravel Transaction

public function transaction(Closure $callback)
    {
        $this->beginTransaction();

        try {
            $result = $callback($this);

            $this->commit();
        }

        catch (Exception $e) {
            $this->rollBack();

            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();

            throw $e;
        }

        return $result;
    }

so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back() it won't redirect immediately, because the it returned at variable which handle the transaction.

Wrap Transaction

$result = DB::transaction(function () use ($request, $message) {
   try{

      // execute query 1
      // execute query 2
      // ..

      return redirect(route('account.article'));

   } catch (\Exception $e) {
       return redirect()->back()->withErrors(['error' => $e->getMessage()]);
    }
 });

// redirect the page
return $result;

then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage() inside catch(Exception $e){...}

Multiple submit buttons on HTML form – designate one button as default

You should not be using buttons of the same name. It's bad semantics. Instead, you should modify your backend to look for different name values being set:

<input type="submit" name="COMMAND_PREV" value="&lsaquo; Prev">
<input type="submit" name="COMMAND_SAVE" value="Save">
<input type="reset"  name="NOTHING" value="Reset">
<input type="submit" name="COMMAND_NEXT" value="Next &rsaquo;">
<input type="button" name="NOTHING" value="Skip &rsaquo;" onclick="window.location = 'yada-yada.asp';">

Since I don't know what language you are using on the backend, I'll give you some pseudocode:

if (input name COMMAND_PREV is set) {

} else if (input name COMMAND_SAVE is set) {

} else if (input name COMMENT_NEXT is set) {

}

Best C++ IDE or Editor for Windows

The Zeus editor has support for C/C++ and it also has a form of intellisensing.

It does its intellisensing using the tags information produced by ctags:

alt text http://www.zeusedit.com/images/_lookmain.jpg

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

Truncate a string straight JavaScript

Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.

From the documentation:

Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred.

Example:

'just sittin on the dock of the bay'.truncate(20)

Output:

just sitting on...

Asp.net - Add blank item at top of dropdownlist

I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems property of the list control.

We use the following method to bind any data source to any list control...

public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
{
    list.Items.Clear();
    list.Items.Add("", "");
    list.AppendDataBoundItems = true;
    list.DataValueField = valueName;
    list.DataTextField = textName;
    list.DataSource = datasource;
    list.DataBind();
}

Failed to add the host to the list of know hosts

I was having this issue and found that within ~/.ssh/config I had a line that read:

UserKnownHostsFile=/home/.ssh-agent/known_hosts

I just modified this line to read:

UserKnownHostsFile=~/.ssh/known_hosts

That fixed the problem for me.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

This works for me: http://gitblit.com/setup_client.html

Eclipse/EGit/JGit

Window->Preferences->Team->Git->Configuration
Click the New Entry button

Key = http.sslVerify
Value = false

Javascript Array of Functions

var array_of_functions = [
    first_function,
    second_function,
    third_function,
    forth_function
]

and then when you want to execute a given function in the array:

array_of_functions[0]('a string');

Readably print out a python dict() sorted by key

The Python pprint module actually already sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, all dictionaries are sorted.

Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via pprint and loaded via eval can be a frustrating and error-prone task.

Saving data to a file in C#

Starting with the System.IO namespace (particularly the File or FileInfo objects) should get you started.

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

Facebook Oauth Logout

Here's an alternative to the accepted answer that works in the current (2.12) version of the API.

<a href="#" onclick="logoutFromFacebookAndRedirect('/logout')">Logout</a>

<script>
    FB.init({
        appId: '{your-app-id}',
        cookie: true,
        xfbml: true,
        version: 'v2.12'
    });

    function logoutFromFacebookAndRedirect(redirectUrl) {
        FB.getLoginStatus(function (response) {
            if (response.status == 'connected')
                FB.logout(function (response) {
                    window.location.href = redirectUrl;
                });
            else
                window.location.href = redirectUrl;
        });
    }
</script>

how to access downloads folder in android?

You need to set this permission in your manifest.xml file

android.permission.WRITE_EXTERNAL_STORAGE

How to set a class attribute to a Symfony2 form input

{{ form_widget(form.content, { 'attr': {'class': 'tinyMCE', 'data-theme': 'advanced'} })  }}

How can I make one python file run another?

from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

Bootstrap 3: how to make head of dropdown link clickable in navbar

Alternatively here's a simple jQuery solution:

$('#menu-main > li > .dropdown-toggle').click(function () {
    window.location = $(this).attr('href');
});