Programs & Examples On #Filebrowse

How to close the current fragment by using Button like the back button?

Button ok= view.findViewById(R.id.btSettingOK);
Fragment me=this;
ok.setOnClickListener( new View.OnClickListener(){
    public void onClick(View v){
     getActivity().getFragmentManager().beginTransaction().remove(me).commit();
    }
});

Django: TemplateSyntaxError: Could not parse the remainder

Template Syntax Error: is due to many reasons one of them is {{ post.date_posted|date: "F d, Y" }} is the space between colon(:) and quote (") if u remove the space then it work like this ..... {{ post.date_posted|date:"F d, Y" }}

No module named Image

Problem:

~$ simple-image-reducer

Traceback (most recent call last):

  File "/usr/bin/simple-image-reducer", line 28, in <module>
    import Image

**ImportError: No module named Image**

Reason:

Image != image

Solution:

1) make sure it is available

python -m pip install  Image

2) where is it available?

sudo find ~ -name image -type d

-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image ->> OK

3) make simple-image-reducer understand via link:

ln -s ~/.local/lib/python2.7/site-packages/image
~/.local/lib/python2.7/site-packages/Image

4) invoke simple-image-reducer again. Works:-)

CKEditor, Image Upload (filebrowserUploadUrl)

May be it's too late. Your code is correct so please check again your url in filebrowserUploadUrl

CKEDITOR.replace( 'editor1', {
    filebrowserUploadUrl: "upload/upload.php" 
} );

And the Upload.php file

if (file_exists("images/" . $_FILES["upload"]["name"]))
{
 echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
 move_uploaded_file($_FILES["upload"]["tmp_name"],
 "images/" . $_FILES["upload"]["name"]);
 echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}

How to resize an image to a specific size in OpenCV?

The two functions you need are documented here:

  1. imread: read an image from disk.
  2. Image resizing: resize to just any size.

In short:

// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");

// Resize src so that is has the same size as img
cv::resize(src, src, img.size());

And please, please, stop using the old and completely deprecated IplImage* classes

In Excel, sum all values in one column in each row where another column is a specific value

If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

=SUMIF(B:B,"No",A:A)

or

=SUMIFS(A:A,B:B,"No")

Here is an example that will display the amounts paid and outstanding for a small set of sample data.

 A         B            C                   D
 Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
 $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
 $200      No           
 $300      No
 $400      Yes
 $500      No

Result of Excel calculations

Add jars to a Spark Job - spark-submit

ClassPath:

ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:

  • spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
  • spark.executor.extraClassPath to set extra class path on the Worker nodes.

If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.

Separation character:

Following the same rules as the JVM:

  • Linux: A colon :
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
  • Windows: A semicolon ;
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"

File distribution:

This depends on the mode which you're running your job under:

  1. Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:

    16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
    16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
    16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
    
  2. Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.

Accepted URI's for files

In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:

When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:

  • file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
  • hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
  • local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.

Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.

As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:

drwxr-xr-x    3 spark spark   4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x    3 spark spark   4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x    3 spark spark   4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x    3 spark spark   4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x    3 spark spark   4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172045-0033

And when you look inside, you'll see all the JARs you deployed along:

[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark   801117 May  8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May  8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May  8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark  2308517 May  8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark      457 May  8 17:34 stderr
-rw-r--r-- 1 spark spark        0 May  8 17:34 stdout

Affected options:

The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:

Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file

So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.

Lets analyze each option in question:

  • --jars vs SparkContext.addJar: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath config on both.
  • SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
  • --conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, doesn't matter which one you choose
  • --conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
  • --conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
  • --conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.

Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:

You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path is useless, you need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:

spark-submit --jars additional1.jar,additional2.jar \
  --driver-class-path additional1.jar:additional2.jar \
  --conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
  --class MyClass main-application.jar

Add a summary row with totals

If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

SELECT
  Type = ISNULL(Type, 'Total'),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

SELECT
  Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

For me, on a mac, it turned out I had an old VirtualBox image stored on my machine that didn't have metadata, so it wasn't being updated to the latest version.

That old image had an older version of the vbguest plugin installed in it, which the newer vbguest plugin on my machine couldn't work with.

So to fix it, I just removed the image that my Vagrant was based on, and then Vagrant downloaded the newer version and it worked fine.

# Remove an old version of the virtual box image that my vagrant was using    
$ vagrant box remove centos/7 

You can find out which boxes you have cached on your machine by running:

$ vagrant box list

I had also upgraded my vbguest plugin in my earlier attempts at getting this to work, using the following process, but I don't think this helped. FYI !

# Get rid of old plugins
vagrant plugin expunge 

# Globally install the latest version of the vbguest plugin`
vagrant plugin install vagrant-vbguest 

If you find bring the box fails on guest addtions, you can try doing the following to ensure the plugins install correctly. This downloads the latest based image for your system (for me CentOS), and may resolve the issue (it did for me!)

$ vagrant box update

How can I read a text file in Android?

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()

The process cannot access the file because it is being used by another process (File is created but contains nothing)

You are writing to the file prior to closing your filestream:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

The above code should work, using the methods you are currently using. You should also look into the using statement and wrap your streams in a using block.

iOS9 Untrusted Enterprise Developer with no option to trust

Device: iPad Mini

OS: iOS 9 Beta 3

App downloaded from: Hockey App

Provisioning profile with Trust issues: Enterprise

In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.

Settings>General>Profile

Here are the steps that I followed:

  1. Connect the Device
  2. Open Xcode
  3. Navigate to Window > Devices
  4. Right click on the Device and select Show Provisioning Profiles...
  5. Delete your Enterprise provisioning profile. Hit Done. Window>Device>Provisioning Profile
  6. Open HockeyApp. Install your app.
  7. Once the app finished installing, go back to Settings>General>Profiles. You should now be able to see your Enterprise provisioning profile. enter image description here
  8. Click Trust enter image description here

That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)

Set width of a "Position: fixed" div relative to parent div

You can also solve it by jQuery:

var new_width = $('#container').width();
$('#fixed').width(new_width); 

This was so helpful to me because my layout was responsive, and the inherit solution wasn't working with me!

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

Answering this old question (for others which may help)

Configuring your httpd conf correctly will make the problem solved. Install any httpd server, if you don't have one.

Listing my config here.

[smilyface@box002 ~]$ cat /etc/httpd/conf/httpd.conf | grep shirts | grep -v "#"


        ProxyPass /shirts-service http://local.box002.com:16743/shirts-service
        ProxyPassReverse /shirts-service http://local.box002.com:16743/shirts-service
        ProxyPass /shirts http://local.box002.com:16443/shirts
        ProxyPassReverse /shirts http://local.box002.com:16443/shirts
        ...
        ...
        ...

edit the file as above and then restart httpd as below

[smilyface@box002 ~]$ sudo service httpd restart


And then request with with https will work without exception.
Also request with http will forward to https ! No worries.

How to make an executable JAR file?

A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main Class is in the jar file. Example code would be as follows.

public class JarExample {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // your logic here
            }
        });
    }
}

Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF). For example,

Manifest-Version: 1.0
Main-Class: JarExample

Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)

jar cfm jarexample.jar jexample.mf *.class

It will create executable jarexample.jar.

How to get the absolute coordinates of a view

Get Both View Position and Dimension on screen

val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;

    if (viewTreeObserver.isAlive) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                //Remove Listener
                videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
                
                //View Dimentions
                viewWidth = videoView.width;
                viewHeight = videoView.height;

                //View Location
                val point = IntArray(2)
                videoView.post {
                    videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
                    viewPositionX = point[0]
                    viewPositionY = point[1]
                }

            }
        });
    }

Inner join vs Where

In a scenario where tables are in 3rd normal form, joins between tables shouldn't change. I.e. join CUSTOMERS and PAYMENTS should always remain the same.

However, we should distinguish joins from filters. Joins are about relationships and filters are about partitioning a whole.

Some authors, referring to the standard (i.e. Jim Melton; Alan R. Simon (1993). Understanding The New SQL: A Complete Guide. Morgan Kaufmann. pp. 11–12. ISBN 978-1-55860-245-8.), wrote about benefits to adopt JOIN syntax over comma-separated tables in FROM clause.

I totally agree with this point of view.

There are several ways to write SQL and achieve the same results but for many of those who do teamwork, source code legibility is an important aspect, and certainly separate how tables relate to each other from specific filters was a big leap in sense of clarifying source code.

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

Hide password with "•••••••" in a textField

In XCode 6.3.1, if you use a NSTextField you will not see the checkbox for secure.

Instead of using NSTextField use NSSecureTextField

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSSecureTextField_Class/index.html

I'm guessing this is a Swift/Objective-C change since there is now a class for secure text fields. In the above link it says Available in OS X v10.0 and later. If you know more about when/why/what versions of Swift/Objective-C, XCode, or OS X this

Changing project port number in Visual Studio 2013

Steps to resolve this:

  1. Open the solution file.
  2. Find the Port tag against your project name.
  3. Assign any different port as current.
  4. Right click on your project and select Property Pages.
  5. Click on Start Options tab and checked Start URL: option.
  6. Assign the start URL in front of Start URL option like:
    localhost:8080/login.aspx

Alternate table with new not null Column in existing table in SQL

IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

What exactly is Spring Framework for?

Basically Spring is a framework for which is a pattern that allows building very decoupled systems.

The problem

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:

public interface UserLister {
    List<User> getUsers();
}

And maybe an implementation accessing a database to get all the users:

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

In your view you'll need to access an instance (just an example, remember):

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

Note that the code above hasn't initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:

UserLister userLister = new UserListerDB();

...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:

UserLister userLister = new UserListerCommaSeparatedFile();

This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!

Spring (Dependency Injection) approach

What Spring does is to wire the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).

Going back to the example in Spring we just need to have a setter for the userLister field and have either an XML file like this:

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

or more simply annotate the filed in our view class with @Inject:

@Inject
private UserLister userLister;

This way when the view is created it magically will have a UserLister ready to work.

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

It is great! Isn't it?

  • What if you want to use another implementation of your UserLister interface? Just change the XML.
  • What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view.
  • What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".

There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

Hope this helps. Anyway, I encourage you to read Martin Fowler's article about Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look at Spring Documentation, in my opinion, it is used to be the best Spring book ever.

HMAC-SHA256 Algorithm for signature calculation

The answer that you got there is correct. One minor thing in the code above, you need to init(key) before you can call doFinal()

    final Charset charSet = Charset.forName("US-ASCII");
    final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

    final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
    try {
        sha256_HMAC.init(secret_key);
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...

JavaScript: How do I print a message to the error console?

With es6 syntax you can use:

console.log(`x = ${x}`);

Matplotlib scatter plot with different text at each data point

As a one liner using list comprehension and numpy:

[ax.annotate(x[0], (x[1], x[2])) for x in np.array([n,z,y]).T]

setup is ditto to Rutger's answer.

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

git error: failed to push some refs to remote

For me the Problem was, I did not add the files before the commit.

git add .

git commit -m "your msg"

Javascript Audio Play on click

Now that the Web Audio API is here and gaining browser support, that could be a more robust option.

Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.

Django: Get list of model fields?

At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields() actually also "considers" any foreign model as a field, which may be problematic. Say you have:

class Parent(models.Model):
    id = UUIDField(primary_key=True)

class Child(models.Model):
    parent = models.ForeignKey(Parent)

It follows that

>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']

while, as shown by @Rockallite

>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']

How can I encode a string to Base64 in Swift?

Swift 4.0.3

import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}

How do I left align these Bootstrap form items?

If you are saying that your problem is how to left align the form labels, see if this helps:
http://jsfiddle.net/panchroma/8gYPQ/

Try changing the text-align left / right in the CSS

.form-horizontal .control-label{
    /* text-align:right; */
    text-align:left;
    background-color:#ffa;
}

Good luck!

symfony2 : failed to write cache directory

If the folder is already writable so thats not the problem.

You can also just navigate to /www/projet_etienne/app/cache/ and manualy remove the folders in there (dev, dev_new, dev_old).

Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem

I know this is not the way it should be done but it worked for me a couple of times now.

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

It may be that the Windows Credential Manager is holding onto credentials for the network share.

Credential Manager - Windows Credentials

Load up Credential Manager (the easiest way is perhaps just to Search for that in the Start Menu), see if there are any Windows Credentials for your network share, and try deleting/updating them.

Java 8 List<V> into Map<K, V>

This can be done in 2 ways. Let person be the class we are going to use to demonstrate it.

public class Person {

    private String name;
    private int age;

    public String getAge() {
        return age;
    }
}

Let persons be the list of Persons to be converted to the map

1.Using Simple foreach and a Lambda Expression on the List

Map<Integer,List<Person>> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));

2.Using Collectors on Stream defined on the given List.

 Map<Integer,List<Person>> mapPersons = 
           persons.stream().collect(Collectors.groupingBy(Person::getAge));

Does Android keep the .apk files? if so where?

If you just want to get an APK file of something you previously installed, do this:

  1. Get AirDroid from Google Play
  2. Access your phone using AirDroid from your PC web browser
  3. Go to Apps and select the installed app
  4. Click the "download" button to download the APK version of this app from your phone

You don't need to root your phone, use adb, or write anything.

Corrupt jar file

Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Here's the JavaScript rejex for YYYY-MM-DD format

/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

How do I repair an InnoDB table?

Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.

How do I log errors and warnings into a file?

add this code in .htaccess (as an alternative of php.ini / ini_set function):

<IfModule mod_php5.c>
php_flag log_errors on 
php_value error_log ./path_to_MY_PHP_ERRORS.log
# php_flag display_errors on 
</IfModule>

* as commented: this is for Apache-type servers, and not for Nginx or others.

Assign output of a program to a variable using a MS batch file

assuming that your application's output is a numeric return code, you can do the following

application arg0 arg1
set VAR=%errorlevel%

How do I install chkconfig on Ubuntu?

alias chkconfig=sysv-rc-conf
chkconfig --list

syntax

sysv-rc-conf command line usage:  

        sysv-rc-conf --list [service name]
        sysv-rc-conf [--level <runlevels>] <service name> <on|off>

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

All error codes are on "CFNetwork Errors Codes References" on the documentation (link)

A small extraction for CFURL and CFURLConnection Errors:

  kCFURLErrorUnknown   = -998,
  kCFURLErrorCancelled = -999,
  kCFURLErrorBadURL    = -1000,
  kCFURLErrorTimedOut  = -1001,
  kCFURLErrorUnsupportedURL = -1002,
  kCFURLErrorCannotFindHost = -1003,
  kCFURLErrorCannotConnectToHost    = -1004,
  kCFURLErrorNetworkConnectionLost  = -1005,
  kCFURLErrorDNSLookupFailed        = -1006,
  kCFURLErrorHTTPTooManyRedirects   = -1007,
  kCFURLErrorResourceUnavailable    = -1008,
  kCFURLErrorNotConnectedToInternet = -1009,
  kCFURLErrorRedirectToNonExistentLocation = -1010,
  kCFURLErrorBadServerResponse             = -1011,
  kCFURLErrorUserCancelledAuthentication   = -1012,
  kCFURLErrorUserAuthenticationRequired    = -1013,
  kCFURLErrorZeroByteResource        = -1014,
  kCFURLErrorCannotDecodeRawData     = -1015,
  kCFURLErrorCannotDecodeContentData = -1016,
  kCFURLErrorCannotParseResponse     = -1017,
  kCFURLErrorInternationalRoamingOff = -1018,
  kCFURLErrorCallIsActive               = -1019,
  kCFURLErrorDataNotAllowed             = -1020,
  kCFURLErrorRequestBodyStreamExhausted = -1021,
  kCFURLErrorFileDoesNotExist           = -1100,
  kCFURLErrorFileIsDirectory            = -1101,
  kCFURLErrorNoPermissionsToReadFile    = -1102,
  kCFURLErrorDataLengthExceedsMaximum   = -1103,

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

I run this

var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);

$.ajax({
    type: 'GET',
    url: 'linkserverApi',
    success: function(success) {
        console.log('Success!');
        console.log(success);
    },
    error: function() {
        console.log('Uh Oh!');
    },
    jsonp: 'jsonp'

});

And edit header in the response

'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'

'Access-Control-Max-Age' , '3628800'

'Access-Control-Allow-Origin', 'websiteresponseUrl'

'Content-Type', 'text/javascript; charset=utf8'

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

I encountered the same issue when trying to use Cordova. Turns out I already had brew, try which brew, but it was outdated. So, I had to update it first:

  1. Update brew: brew update
  2. Install Apache Ant: brew install ant

How do I Merge two Arrays in VBA?

Following the @johannes solution, but merging without loosing data (it was missing first elements):

    Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant

    Dim returnThis() As Variant
    Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
    len1 = UBound(arr1)
    len2 = UBound(arr2)
    lenRe = len1 + len2 + 1
    ReDim returnThis(0 To lenRe)
    counter = 0

    For counter = 0 To len1 'get first array in returnThis
        returnThis(counter) = arr1(counter)
    Next


    For counter = 0 To len2 'get the second array in returnThis
        returnThis(counter + len1 + 1) = arr2(counter)
    Next
mergeArrays = returnThis
End Function

Does adding a duplicate value to a HashSet/HashMap replace the previous value

To say it differently: When you insert a key-value-pair into a HashMap where the key already exists (in a sense hashvalue() gives the same value und equal() is true, but the two objects can still differ in several ways), the key isn't replaced but the value is overwritten. The key is just used to get the hashvalue() and find the value in the table with it. Since HashSet uses the keys of a HashMap and sets arbitrary values which don't really matter (to the user) as a result the Elements of the Set aren't replaced either.

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

Setting java locale settings

With the user.language, user.country and user.variant properties.

Example:

java -Duser.language=th -Duser.country=TH -Duser.variant=TH SomeClass

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

"starting Tomcat server 7 at localhost has encountered a prob"

Open the terminal in ubuntu (ctrl+shift+t)
sudo gedit /etc/tomcat7/server.xml

change the default port in the server.xml,from 8080 to anything like 8081,8181,8008. Then save the file .

Now the project will work nicely without any interruption.

Renaming columns in Pandas

Note that the approaches in previous answers do not work for a MultiIndex. For a MultiIndex, you need to do something like the following:

>>> df = pd.DataFrame({('$a','$x'):[1,2], ('$b','$y'): [3,4], ('e','f'):[5,6]})
>>> df
   $a $b  e
   $x $y  f
0  1  3  5
1  2  4  6
>>> rename = {('$a','$x'):('a','x'), ('$b','$y'):('b','y')}
>>> df.columns = pandas.MultiIndex.from_tuples([
        rename.get(item, item) for item in df.columns.tolist()])
>>> df
   a  b  e
   x  y  f
0  1  3  5
1  2  4  6

Null or empty check for a string variable

Yes, it works. Check the below example. Assuming @value is not int

WITH CTE 
AS
(
    SELECT NULL AS test
    UNION
    SELECT '' AS test
    UNION
    SELECT '123' AS test
)

SELECT 
    CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY 
FROM CTE

Result :

IS_EMPTY
--------
empty
empty
123

Show "loading" animation on button click

$("#btnId").click(function(e){
      e.preventDefault();
      $.ajax({
        ...
        beforeSend : function(xhr, opts){
            //show loading gif
        },
        success: function(){

        },
        complete : function() {
           //remove loading gif
        }
    });
});

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

Check string length in PHP

[0]=> string(141) means $message is an array so you should do strlen($message[0]) < 141 ...

Regex match everything after question mark?

\?(.*)

You want the content of the first capture group.

jQuery DataTables Getting selected row values

var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);

parseInt with jQuery

Two issues:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseInt will call toString on it and get back "[object Object]". You need to use val or text or something (depending on what the element is) to get the string you want.

  2. You're not telling parseInt what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt guesses which radix to use.

Fix if the element is a form field:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Conversion of a datetime2 data type to a datetime data type results out-of-range value

The easiest thing would be to change your database to use datetime2 instead of datetime. The compatibility works nicely, and you won't get your errors.

You'll still want to do a bunch of testing...

The error is probably because you're trying to set a date to year 0 or something - but it all depends on where you have control to change stuff.

while EOF in JAVA?

you should use while (fileReader.hasNextLine())

How can I use regex to get all the characters after a specific character, e.g. comma (",")

.+,(.+)

Explanation:

.+,

will search for everything before the comma, including the comma.

(.+) 

will search for everything after the comma, and depending on your regex environment,

\1

is the reference for the first parentheses captured group that you need, in this example, everything after the comma.

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

jQuery ui dialog change title after load-callback

An enhancement of the hacky idea by Nick Craver to put custom HTML in a jquery dialog title:

var newtitle= '<b>HTML TITLE</b>';
$(".selectorUsedToCreateTheDialog").parent().find("span.ui-dialog-title").html(newtitle);

How to prevent scanf causing a buffer overflow in C?

It's not that much work to make a function that's allocating the needed memory for your string. That's a little c-function i wrote some time ago, i always use it to read in strings.

It will return the read string or if a memory error occurs NULL. But be aware that you have to free() your string and always check for it's return value.

#define BUFFER 32

char *readString()
{
    char *str = malloc(sizeof(char) * BUFFER), *err;
    int pos;
    for(pos = 0; str != NULL && (str[pos] = getchar()) != '\n'; pos++)
    {
        if(pos % BUFFER == BUFFER - 1)
        {
            if((err = realloc(str, sizeof(char) * (BUFFER + pos + 1))) == NULL)
                free(str);
            str = err;
        }
    }
    if(str != NULL)
        str[pos] = '\0';
    return str;
}

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

apt-get for Cygwin?

You can do this using Cygwin’s setup.exe from Windows command line. Example:

cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim

For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin

Now that apt-cyg is installed. Here are a few examples of installing some packages:

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

ORA-01008: not all variables bound. They are bound

The solution in my situation was similar answer to Charles Burns; and the problem was related to SQL code comments.

I was building (or updating, rather) an already-functioning SSRS report with Oracle datasource. I added some more parameters to the report, tested it in Visual Studio, it works great, so I deployed it to the report server, and then when the report is executed the report on the server I got the error message:

"ORA-01008: not all variables bound"

I tried quite a few different things (TNSNames.ora file installed on the server, Removed single line comments, Validate dataset query mapping). What it came down to was I had to remove a comment block directly after the WHERE keyword. The error message was resolved after moving the comment block after the WHERE CLAUSE conditions. I have other comments in the code also. It was just the one after the WHERE keyword causing the error.

SQL with error: "ORA-01008: not all variables bound"...

WHERE
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto) 

SQL executes successfully on the report server...

WHERE
    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)   
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

Here is what the dataset parameter mapping screen looks like.

enter image description here

Using (Ana)conda within PyCharm

I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.

The short answer

Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.

The long answer

Create a new Conda environment:

conda create --name foo pandas bokeh

This environment lives under conda_root/envs/foo. Your python interpreter is conda_root/envs/foo/bin/pythonX.X and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.

Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!

Now install more packages:

conda install scikit-learn

OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!

And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:

conda list

The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.

Conclusion

This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.

NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.

EDIT: PyCharm5 is out with Conda support! In the community edition too.

Detect the Internet connection is offline?

The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.

Here is my code:

 var xhr = new XMLHttpRequest();
 //index.php is in my web
 xhr.open('HEAD', 'index.php', true);
 xhr.send();

 xhr.addEventListener("readystatechange", processRequest, false);

 function processRequest(e) {
     if (xhr.readyState == 4) {
         //If you use a cache storage manager (service worker), it is likely that the
         //index.php file will be available even without internet, so do the following validation
         if (xhr.status >= 200 && xhr.status < 304) {
             console.log('On line!');
         } else {
             console.log('Offline :(');
         }
     }
}

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

How to Sort Multi-dimensional Array by Value?

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"order");

How do you get the magnitude of a vector in Numpy?

Fastest way I found is via inner1d. Here's how it compares to other numpy methods:

import numpy as np
from numpy.core.umath_tests import inner1d

V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)   
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))

print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]

import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)')              # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))')             # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))')            # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))')                 # 2 function calls in 0.009 seconds

inner1d is ~3x faster than linalg.norm and a hair faster than einsum

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Easiest solution for this to remove the index.php code which is allocated on

xammp-> htdocs-> index.php 

you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck

node.js require all files in a folder?

Can use : https://www.npmjs.com/package/require-file-directory

  • Require selected files with name only or all files.
  • No need of absoulute path.
  • Easy to understand and use.

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

How to create an empty R vector to add new items

vec <- vector()

See also vector help

?vector

How do I set a textbox's value using an anchor with jQuery?

I wrote this code snippet and it works fine:

<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
    $(document).ready(function(){
        $("a.clickable").click(function(event){
            event.preventDefault();
            $("input#textbox").val($(this).html());
        });  
    });
</script>

Maybe you forgot to give a class name "clickable" to your links?

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

The user manual covers this topic in depth. You can:

  • pg_upgrade in-place; or

  • pg_dump and pg_restore.

If in doubt, do it with dumps. Don't delete the old data directory, just keep it in case something goes wrong / you make a mistake; that way you can just go back to your unchanged 9.3 install.

For details, see the manual.

If you're stuck, post a detailed question explaining how you're stuck, where, and what you tried first. It depends a bit on how you installed PostgreSQL too, as there are several different "distributions" of PostgreSQL for OS X (unfortunately). So you'd need to provide that info.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

The only difference between files that causing the issue is the 8th byte of file

CA FE BA BE 00 00 00 33 - Java 7

vs.

CA FE BA BE 00 00 00 32 - Java 6

Setting -XX:-UseSplitVerifier resolves the issue. However, the cause of this issue is https://bugs.eclipse.org/bugs/show_bug.cgi?id=339388

How to automatically generate getters and setters in Android Studio

Using Alt+ Insert or Right-click and choose "Generate..." You may easily generate getter and setter or Override methods in Android Studio. This has the same effect as using the Menu Bar Code -> Generate...

enter image description here enter image description here

How to wait 5 seconds with jQuery?

Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.

button = $('.status-button a', whatever);
if(button.hasClass('close')) {
  button.delay(10000).queue(function() {
    $(this).click().dequeue();
  });
}

Angular 1.6.0: "Possibly unhandled rejection" error

The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections in $qProvider configuration as suggested Cengkuru Michael

BUT this will only switch off logging. The error itself will remain

The better solution in this case will be - handling a rejection with .catch(fn) method:

resource.get().$promise
    .then(function (response) {})
    .catch(function (err) {});

LINKS:

What are the parameters for the number Pipe - Angular 2

'1.0-0' will give you zero decimal places i.e. no decimals. e.g.$500

iPhone app could not be installed at this time

Here is what worked for me:

  1. Clear the Cache and Cookies (Settings > Safari).
  2. Remove existing profile (if any) linked to "Test Flight App" (Settings > General > Profiles).
  3. Open Safari and go to https://testflightapp.com/. Login and follow the steps to start over.

P.S. I used to have a Test Flight App, but it looks like it crashed and the icon turned to be all white. Restarting my iPhone made it reappear correctly.

How to clear the canvas for redrawing

context.clearRect(0,0,w,h)   

fill the given rectangle with RGBA values :
0 0 0 0 : with Chrome
0 0 0 255 : with FF & Safari

But

context.clearRect(0,0,w,h);    
context.fillStyle = 'rgba(0,0,0,1)';  
context.fillRect(0,0,w,h);  

let the rectangle filled with
0 0 0 255
no matter the browser !

Set style for TextView programmatically

You can create a generic style and re-use it on multiple textviews like the one below:

textView.setTextAppearance(this, R.style.MyTextStyle);

Edit: this refers to Context

Cleanest way to build an SQL string in Java

I have been working on a Java servlet application that needs to construct very dynamic SQL statements for adhoc reporting purposes. The basic function of the app is to feed a bunch of named HTTP request parameters into a pre-coded query, and generate a nicely formatted table of output. I used Spring MVC and the dependency injection framework to store all of my SQL queries in XML files and load them into the reporting application, along with the table formatting information. Eventually, the reporting requirements became more complicated than the capabilities of the existing parameter mapping frameworks and I had to write my own. It was an interesting exercise in development and produced a framework for parameter mapping much more robust than anything else I could find.

The new parameter mappings looked as such:

select app.name as "App", 
       ${optional(" app.owner as "Owner", "):showOwner}
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = ${integer(0,50):serverId}
   and app.id in ${integerList(50):appId}
 group by app.name, ${optional(" app.owner, "):showOwner} sv.name
 order by app.name, sv.name

The beauty of the resulting framework was that it could process HTTP request parameters directly into the query with proper type checking and limit checking. No extra mappings required for input validation. In the example query above, the parameter named serverId would be checked to make sure it could cast to an integer and was in the range of 0-50. The parameter appId would be processed as an array of integers, with a length limit of 50. If the field showOwner is present and set to "true", the bits of SQL in the quotes will be added to the generated query for the optional field mappings. field Several more parameter type mappings are available including optional segments of SQL with further parameter mappings. It allows for as complex of a query mapping as the developer can come up with. It even has controls in the report configuration to determine whether a given query will have the final mappings via a PreparedStatement or simply ran as a pre-built query.

For the sample Http request values:

showOwner: true
serverId: 20
appId: 1,2,3,5,7,11,13

It would produce the following SQL:

select app.name as "App", 
       app.owner as "Owner", 
       sv.name as "Server", sum(act.trans_ct) as "Trans"
  from activity_records act, servers sv, applications app
 where act.server_id = sv.id
   and act.app_id = app.id
   and sv.id = 20
   and app.id in (1,2,3,5,7,11,13)
 group by app.name,  app.owner,  sv.name
 order by app.name, sv.name

I really think that Spring or Hibernate or one of those frameworks should offer a more robust mapping mechanism that verifies types, allows for complex data types like arrays and other such features. I wrote my engine for only my purposes, it isn't quite read for general release. It only works with Oracle queries at the moment and all of the code belongs to a big corporation. Someday I may take my ideas and build a new open source framework, but I'm hoping one of the existing big players will take up the challenge.

How to connect to remote Oracle DB with PL/SQL Developer?

I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.

Next, simply add an entry like this:

MYDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
    (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
  )

You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.

Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.

If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.

How to get all properties values of a JavaScript Object (without knowing the keys)?

Here's a function similar to PHP's array_values()

function array_values(input) {
  var output = [], key = '';
  for ( key in input ) { output[output.length] = input[key]; }
  return output;
}

Here's how to get the object's values if you're using ES6 or higher:

Array.from(values(obj));

Building executable jar with maven?

Right click the project and give maven build,maven clean,maven generate resource and maven install.The jar file will automatically generate.

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

Plot a horizontal line using matplotlib

You're looking for axhline (a horizontal axis line). For example, the following will give you a horizontal line at y = 0.5:

import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

sample figure

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I had the similar problem solved it with this:

@section ***{
@RenderSection("****", required: false)
}

Thats a pretty way to inject i guesse.

How should I edit an Entity Framework connection string?

You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.

In the output window it will show something like this,

Generated model file: UpostDataModel.edmx. Loading metadata from the database took 00:00:00.4258157. Generating the model took 00:00:01.5623765. Added the connection string to the App.Config file.

Change the background color of a pop-up dialog

To expand on @DaneWhite's answer, you don't have to rely on the built-in themes. You can easily supply your own style:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/myColor</item>
</style>

and then apply it in the Builder constructor:

Java:

AlertDialog alertDialog = new AlertDialog.Builder(getContext(), R.style.MyDialogTheme)
        ...
        .create();

Kotlin:

var alertDialog = AlertDialog.Builder(context, R.style.MyDialogTheme)
        ...
        .create()

This should work whether you are using android.support.v7.app.AlertDialog or android.app.AlertDialog

This also works better than @DummyData's answer because you don't resize the dialog. If you set window's background drawable you overwrite some existing dimensional information and get a dialog that is not standard width.

If you set background on theme and the set the theme on dialog you'll end up with a dialog that is colored how you want but still the correct width.

error MSB6006: "cmd.exe" exited with code 1

error MSB6006: "cmd.exe" exited with code -Solved

I also face this problem . In my case it is due to output exe already running .I solved my problem simply close the application instance before building.

Python time measure function

I don't see what the problem with the timeit module is. This is probably the simplest way to do it.

import timeit
timeit.timeit(a, number=1)

Its also possible to send arguments to the functions. All you need is to wrap your function up using decorators. More explanation here: http://www.pythoncentral.io/time-a-python-function/

The only case where you might be interested in writing your own timing statements is if you want to run a function only once and are also want to obtain its return value.

The advantage of using the timeit module is that it lets you repeat the number of executions. This might be necessary because other processes might interfere with your timing accuracy. So, you should run it multiple times and look at the lowest value.

runOnUiThread in fragment

For Kotlin on fragment just do this

activity?.runOnUiThread(Runnable {
        //on main thread
    })

Using switch statement with a range of value in each case?

No you can't do that. The best you can do is that

case 1:
case 2:
case 3:
case 4:
case 5: 
  System.Out.Println("testing case 1 to 5");
break;

JAVA_HOME does not point to the JDK

It looks like you are currently pointing JAVA_HOME to /usr/lib/jvm/java-6-openjdk/jre which appears to be a JRE not a JDK. Try setting JAVA_HOME to /usr/lib/jvm/java-6-openjdk.

The JRE does not contain the Java compiler, only the JDK (Java Developer Kit) contains it.

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

I want to convert std::string into a const wchar_t *

You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:

#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);

You can also specify a code page, so if your std::string contains UTF-8 chars you can use:

CA2W pszWide(str.c_str(), CP_UTF8);

Very useful but Windows only.

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

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

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Find files with size in Unix

find . -size +10000k -exec ls -sd {} +

If your version of find won't accept the + notation (which acts rather like xargs does), then you might use (GNU find and xargs, so find probably supports + anyway):

find . -size +10000k -print0 | xargs -0 ls -sd

or you might replace the + with \; (and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:

find . -size +10000k -print | xargs ls -sd

The -d on the ls commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k to 1000k or maybe +1024k, or +2048 (for 512-byte blocks, the default unit for -size). This will list the size and then the file name. You could avoid the need for -d by adding -type f to the find command, of course.

Read file line by line using ifstream in C++

Although there is no need to close the file manually but it is good idea to do so if the scope of the file variable is bigger:

    ifstream infile(szFilePath);

    for (string line = ""; getline(infile, line); )
    {
        //do something with the line
    }

    if(infile.is_open())
        infile.close();

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

What's the difference between <b> and <strong>, <i> and <em>?

<b> and <i> are explicit - they specify bold and italic respectively.

<strong> and <em> are semantic - they specify that the enclosed text should be "strong" or "emphasised" in some way, usually bold and italic, but allow for the actual styling to be controlled via CSS. Hence these are preferred in modern web pages.

How to add border around linear layout except at the bottom?

Kenny is right, just want to clear some things out.

  1. Create the file border.xml and put it in the folder res/drawable/
  2. add the code

    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
       <stroke android:width="4dp" android:color="#FF00FF00" /> 
       <solid android:color="#ffffff" /> 
       <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
       <corners android:radius="4dp" /> 
    </shape>
    
  3. set back ground like android:background="@drawable/border" wherever you want the border

Mine first didn't work cause i put the border.xml in the wrong folder!

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How do I remove the title bar from my app?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getSupportActionBar().hide();

    setContentView(R.layout.activity_main);

Just simply put getSupportActionBar().hide(); between super.onCreate and setContentView method.

How to define a relative path in java

Try something like this

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

So your new file points to the path where it is created, usually your project home folder.

[EDIT]

As @cmc said,

    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);

    String path = new File("src/main/resources/conf.properties")
                                                           .getAbsolutePath();
    System.out.println(path);

Both give the same value.

How to determine the longest increasing subsequence using dynamic programming?

Here's another O(n^2) JAVA implementation. No recursion/memoization to generate the actual subsequence. Just a string array that stores the actual LIS at every stage and an array to store the length of the LIS for each element. Pretty darn easy. Have a look:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Shreyans on 4/16/2015
 */

class LNG_INC_SUB//Longest Increasing Subsequence
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter Numbers Separated by Spaces to find their LIS\n");
        String[] s1=br.readLine().split(" ");
        int n=s1.length;
        int[] a=new int[n];//Array actual of Numbers
        String []ls=new String[n];// Array of Strings to maintain LIS for every element
        for(int i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(s1[i]);
        }
        int[]dp=new int[n];//Storing length of max subseq.
        int max=dp[0]=1;//Defaults
        String seq=ls[0]=s1[0];//Defaults
        for(int i=1;i<n;i++)
        {
            dp[i]=1;
            String x="";
            for(int j=i-1;j>=0;j--)
            {
                //First check if number at index j is less than num at i.
                // Second the length of that DP should be greater than dp[i]
                // -1 since dp of previous could also be one. So we compare the dp[i] as empty initially
                if(a[j]<a[i]&&dp[j]>dp[i]-1)
                {
                    dp[i]=dp[j]+1;//Assigning temp length of LIS. There may come along a bigger LIS of a future a[j]
                    x=ls[j];//Assigning temp LIS of a[j]. Will append a[i] later on
                }
            }
            x+=(" "+a[i]);
            ls[i]=x;
            if(dp[i]>max)
            {
                max=dp[i];
                seq=ls[i];
            }
        }
        System.out.println("Length of LIS is: " + max + "\nThe Sequence is: " + seq);
    }
}

Code in action: http://ideone.com/sBiOQx

How to print out a variable in makefile

This makefile will generate the 'missing separator' error message:

all
    @echo NDK_PROJECT_PATH=$(NDK_PROJECT_PATH)

done:
        @echo "All done"

There's a tab before the @echo "All done" (though the done: rule and action are largely superfluous), but not before the @echo PATH=$(PATH).

The trouble is that the line starting all should either have a colon : or an equals = to indicate that it is a target line or a macro line, and it has neither, so the separator is missing.

The action that echoes the value of a variable must be associated with a target, possibly a dummy or PHONEY target. And that target line must have a colon on it. If you add a : after all in the example makefile and replace the leading blanks on the next line by a tab, it will work sanely.

You probably have an analogous problem near line 102 in the original makefile. If you showed 5 non-blank, non-comment lines before the echo operations that are failing, it would probably be possible to finish the diagnosis. However, since the question was asked in May 2013, it is unlikely that the broken makefile is still available now (August 2014), so this answer can't be validated formally. It can only be used to illustrate a plausible way in which the problem occurred.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

update capabilities in conf.js as

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['todo-spec.js'],
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: ['--disable-gpu', '--no-sandbox', '--disable-extensions', '--disable-dev-shm-usage']
    }
  },

};

CSS file not refreshing in browser

The Ctrl + F5 solusion didn't work for me in Chrome.

But I found How to Clear Chrome Cache for Specific Website Only (3 Steps):

  1. As the page is loaded, open Chrome Developer Tools (Right-Click > Inspect) or (Menu > More Tools > Developer Tools)
  2. Next, go to the Refresh button in Chrome browser, and Right-Click the Refresh button.
  3. Select "Empty Cache and Hard Refresh".

Hope this answer helps someone!

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

How to uncheck a radio button?

$('input[id^="rad"]').dblclick(function(){
    var nombre = $(this).attr('id');
    var checked =  $(this).is(":checked") ;
    if(checked){
        $("input[id="+nombre+"]:radio").prop( "checked", false );
    }
});

Every time you have a double click in a checked radio the checked changes to false

My radios begin with id=radxxxxxxxx because I use this id selector.

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

Get Folder Size from Windows Command Line

You can just add up sizes recursively (the following is a batch file):

@echo off
set size=0
for /r %%x in (folder\*) do set /a size+=%%~zx
echo %size% Bytes

However, this has several problems because cmd is limited to 32-bit signed integer arithmetic. So it will get sizes above 2 GiB wrong1. Furthermore it will likely count symlinks and junctions multiple times so it's at best an upper bound, not the true size (you'll have that problem with any tool, though).

An alternative is PowerShell:

Get-ChildItem -Recurse | Measure-Object -Sum Length

or shorter:

ls -r | measure -sum Length

If you want it prettier:

switch((ls -r|measure -sum Length).Sum) {
  {$_ -gt 1GB} {
    '{0:0.0} GiB' -f ($_/1GB)
    break
  }
  {$_ -gt 1MB} {
    '{0:0.0} MiB' -f ($_/1MB)
    break
  }
  {$_ -gt 1KB} {
    '{0:0.0} KiB' -f ($_/1KB)
    break
  }
  default { "$_ bytes" }
}

You can use this directly from cmd:

powershell -noprofile -command "ls -r|measure -sum Length"

1 I do have a partially-finished bignum library in batch files somewhere which at least gets arbitrary-precision integer addition right. I should really release it, I guess :-)

How to implement onBackPressed() in Fragments?

Its just simple if you have An Activity A and you make 3 fragments like B ,C and D.Now if you are in fragment B or C and onBackPressed you want to move on Fragment D every time .Then you have to just Override the onBackPressed() method in main Activity A and also when you jump to any fragment then pass a TAG or name of that fragment by which you recognized that fragment in main Activity A.

I am giving the example of that one by which you can easily understand that....

if (savedInstanceState == null) {

   getSupportFragmentManager().beginTransaction().add(R.id.container, new C_fragment(),"xyz").commit();

}

or if you are moving from fragment B to fragment C..and on back press you want to come on Fragment D...like below

btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, new C_frament(), "xyz").commit();
        ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Fragment C");
    }
});

Now you have to just override the onBackPressed() method in main activity....like below..

@Override
public void onBackPressed() {
    FragmentManager fragmentManager =getSupportFragmentManager();
    if (((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")) != null && ((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")).isVisible()) {
        Fragment fragment = new D_Fragment();
        fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
        getSupportActionBar().setTitle("D fragment ");
    } else {
        super.onBackPressed();
    }
}

How to include *.so library in Android Studio?

Solution 1 : Creation of a JniLibs folder

Create a folder called “jniLibs” into your app and the folders containing your *.so inside. The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.

Solution 2 : Modification of the build.gradle file

If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !

In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.

sourceSets {
    main {
        jniLibs.srcDirs = ["libs"]
    }
}

You will have more explanations, with screenshots to help you here ( Step 6 ):

http://blog.guillaumeagis.eu/setup-andengine-with-android-studio/

EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

Validation error: "No validator could be found for type: java.lang.Integer"

As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Sql connection-string for localhost server

In .Net configuration I would use something like:

"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=..."

This information is from https://www.connectionstrings.com/sql-server-2016/

How do I get a YouTube video thumbnail from the YouTube API?

Here is a simple function I created for getting the thumbnails. It is easy to understand and use.

$link is the YouTube link copied exactly as it is in the browser, for example, https://www.youtube.com/watch?v=BQ0mxQXmLsk

function get_youtube_thumb($link){
    $new = str_replace('https://www.youtube.com/watch?v=', '', $link);
    $thumbnail = 'https://img.youtube.com/vi/' . $new . '/0.jpg';
    return $thumbnail;
}

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

How to update attributes without validation

You can do something like:

object.attribute = value
object.save(:validate => false)

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

How to read and write excel file

Please use Apache POI libs and try this.

    try
    {
        FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls"));

        //Create Workbook instance holding reference to .xlsx file
        Workbook workbook = new HSSFWorkbook(x);

        //Get first/desired sheet from the workbook
        Sheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) {
            Row row = (Row) iterator.next();
            for (Iterator<Cell> iterator2 = row.iterator(); iterator2
                    .hasNext();) {
                Cell cell = (Cell) iterator2.next();
                System.out.println(cell.getStringCellValue());              
            }               
        }         
        x.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
   }
}

Animation CSS3: display + opacity

I know, this is not really a solution for your question, because you ask for

display + opacity

My approach solves a more general question, but maybe this was the background problem that should be solved by using display in combination with opacity.

My desire was to get the Element out of the way when it is not visible. This solution does exactly that: It moves the element out of the away, and this can be used for transition:

.child {
  left: -2000px;
  opacity: 0;
  visibility: hidden;
  transition: left 0s 0.8s, visibility 0s 0.8s, opacity 0.8s;
}

.parent:hover .child {
  left: 0;
  opacity: 1;
  visibility: visible;
  transition: left 0s, visibility 0s, opacity 0.8s;
}

This code does not contain any browser prefixes or backward compatibility hacks. It just illustrates the concept how the element is moved away as it is not needed any more.

The interesting part are the two different transition definitions. When the mouse-pointer is hovering the .parent element the .child element needs to be put in place immediately and then the opacity will be changed:

transition: left 0s, visibility 0s, opacity 0.8s;

When there is no hover, or the mouse-pointer was moved off the element, one has to wait until the opacity change has finished before the element can be moved off screen:

transition: left 0s 0.8s, visibility 0s 0.8s, opacity 0.8s;

Moving the object away will be a viable alternative in a case where setting display:none would not break the layout.

I hope I hit the nail on the head for this question although I did not answer it.

Package opencv was not found in the pkg-config search path

it seems that the ubuntu community has completed the documentation on installing openCV,

so all you have to do now is to download the installation script from here and execute it.

don't forget to make it executable:

chmod +x opencv_latest.sh

then

./opencv_latest.sh

jQuery Date Picker - disable past dates

set startDate attribute of datepicker, it works, below is the working code

$(function(){
$('#datepicker').datepicker({
    startDate: '-0m'
    //endDate: '+2d'
}).on('changeDate', function(ev){
    $('#sDate1').text($('#datepicker').data('date'));
    $('#datepicker').datepicker('hide');
});
})

.htaccess rewrite to redirect root URL to subdirectory

This seemed the simplest solution:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://www.example.com/store [R=301,L]

I was getting redirect loops with some of the other solutions.

Create SQLite database in android

A simple database example to insert Todo List of day today life in DB and get list of all todo list.

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Logcat tag
private static final String LOG = "DatabaseHelper";

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";

// Table Names
private static final String TABLE_TODO = "todos";

// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";

// *********************************************************************************************
public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_TABLE_TODO);


}

// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);


    // Create tables again
    onCreate(db);
}

// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_TODO + " text, "
        + KEY_CREATED_AT + " text" + ")";


// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TODO, todo);
    contentValues.put(KEY_CREATED_AT, createdAt);


    long rowInserted = db.insert(TABLE_TODO, null, contentValues);
    db.close();
    return true;
}


// Select values of todo
public Cursor GetAllTodoDetails() {
    SQLiteDatabase db = this.getReadableDatabase();


    String query = "SELECT * FROM " + TABLE_TODO;
    Cursor mcursor = db.rawQuery(query, null);

    if (mcursor != null) {
        mcursor.moveToFirst();
    }

    return mcursor;

}



}

My activity To save and get the record.

public class MyDbActivity extends AppCompatActivity {

    @Bind(R.id.edt_todo)
    EditText edtTodo;
    @Bind(R.id.btn_save)
    Button btnSave;

    MyDatabaseHelper db;
    @Bind(R.id.btn_getTodo)
    Button btnGetTodo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_db);
        ButterKnife.bind(this);

// creating database object
        db = new MyDatabaseHelper(this);


    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {


        String datetime = "";
        try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            datetime = dateformat.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);

    }

    @OnClick(R.id.btn_getTodo)
    public void onGetTodoClicked() {
        String todos = "";
        Cursor TodoList = db.GetAllTodoDetails();
        if (TodoList.moveToFirst()) {
            do {
                if (todos.equals("")) {
                    todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));

                } else {
                    todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
                }
                // do what ever you want here
            } while (TodoList.moveToNext());
        }
        TodoList.close();
        Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();

    }
}

Return the characters after Nth character in a string

Mid(strYourString, 4) (i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.

How do I get a background location update every n minutes in my iOS application?

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

This is needed for background location tracking since iOS 9.

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

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

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

AngularJS ng-repeat handle empty list case

you can use ng-if because this is not render in html page and you dont see your html tag in inspect...

<ul ng-repeat="item in items" ng-if="items.length > 0">
    <li>{{item}}<li>
</ul>
<div class="alert alert-info">there is no items!</div>

Top 5 time-consuming SQL queries in Oracle

I found this SQL statement to be a useful place to start (sorry I can't attribute this to the original author; I found it somewhere on the internet):

SELECT * FROM
(SELECT
    sql_fulltext,
    sql_id,
    elapsed_time,
    child_number,
    disk_reads,
    executions,
    first_load_time,
    last_load_time
FROM    v$sql
ORDER BY elapsed_time DESC)
WHERE ROWNUM < 10
/

This finds the top SQL statements that are currently stored in the SQL cache ordered by elapsed time. Statements will disappear from the cache over time, so it might be no good trying to diagnose last night's batch job when you roll into work at midday.

You can also try ordering by disk_reads and executions. Executions is useful because some poor applications send the same SQL statement way too many times. This SQL assumes you use bind variables correctly.

Then, you can take the sql_id and child_number of a statement and feed them into this baby:-

SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id', &child));

This shows the actual plan from the SQL cache and the full text of the SQL.

Comparing two hashmaps for equal values and same key sets?

Make an equals check on the keySet() of both HashMaps.

NOTE:

If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

Understanding slice notation

My brain seems happy to accept that lst[start:end] contains the start-th item. I might even say that it is a 'natural assumption'.

But occasionally a doubt creeps in and my brain asks for reassurance that it does not contain the end-th element.

In these moments I rely on this simple theorem:

for any n,    lst = lst[:n] + lst[n:]

This pretty property tells me that lst[start:end] does not contain the end-th item because it is in lst[end:].

Note that this theorem is true for any n at all. For example, you can check that

lst = range(10)
lst[:-42] + lst[-42:] == lst

returns True.

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Adding placeholder text to textbox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace App_name
{
   public class CustomTextBox : TextBox
    {
        private string Text_ = "";
        public CustomTextBox() : base()
        {}

        public string setHint
        {
            get { return Text_; }
            set { Text_ = value; }
        }
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            if (Text_.Equals(this.Text))
                this.Clear();
        }
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            if (String.IsNullOrWhiteSpace(this.Text))
                this.Text = Text_;
        }
    }
}
>    xmlns:local="clr-namespace:app_name"
>  <local:CustomTextBox
>                 x:Name="id_number_txt"
>                 Width="240px"
>                 Height="auto"/>

EF Migrations: Rollback last applied migration?

Update-Database –TargetMigration:"Your migration name"

For this problem I suggest this link:

https://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

Switch statement equivalent in Windows batch file

If if is not working you use:

:switch case %n%=1 
statements;
goto :switch case end
etc..

http://lallouslab.net/2016/12/21/batchography-switch-case/

Git push requires username and password

If you've got 2FA enabled on your Github account, your regular password won't work for this purpose, but you can generate a Personal Access Token and use that in its place instead.

Visit the Settings -> Developer Settings -> Personal Access Tokens page in GitHub (https://github.com/settings/tokens/new), and generate a new Token with all Repo permissions:

generate GitHub personal access token

The page will then display the new token value. Save this value and use it in place of your password when pushing to your repository on GitHub:

> git push origin develop
Username for 'https://github.com': <your username>
Password for 'https://<your username>@github.com': <your personal access token>

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

How to cancel/abort jQuery AJAX request?

I know this might be a little late but i experience similar issues where calling the abort method didnt really aborted the request. instead the browser was still waiting for a response that it never uses. this code resolved that issue.

 try {
        xhr.onreadystatechange = null;
        xhr.abort();
} catch (e) {}

How do I change the background color with JavaScript?

This code makes random color for background every second.

_x000D_
_x000D_
setInterval(changeColor,1000);
function changeColor(){
  let r = Math.random() * 255 ;
  let g = Math.random() * 255 ;
  let b = Math.random() * 255 ;
  
  document.body.style.backgroundColor = `rgb( ${r}, ${g}, ${b} )`;
}
_x000D_
_x000D_
_x000D_

I hope helps someone.?

SQL ORDER BY multiple columns

It depends on the size of your database.

SQL is based on the SET theory: there is no order inherently used when querying a table.

So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.

If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.

String replacement in batch file

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

Can't update: no tracked branch

I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:

git fetch

which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.

Angular 2 Date Input not binding to date value

In Typescript - app.component.ts file

export class AppComponent implements OnInit {
    currentDate = new Date();
}

In HTML Input field

<input id="form21_1" type="text" tabindex="28" title="DATE" [ngModel]="currentDate | date:'MM/dd/yyyy'" />

It will display the current date inside the input field.

How to open a different activity on recyclerView item onclick

you can implement your adapter's onClickListener:

  public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener

and use interface with method in it

public interface mClickListener {
    public void mClick(View v, int position);
}

and in your onClick method call the method in the interface and pass it the view and position

in your main activity implement that interface

public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener

and override that method

@Override
public void onCommentsClick(View v, int position) {
    final Intent intent = new Intent(this, OtherActivity.class);
}

as its better to manage your activity transition by the activity not other classes

Match the path of a URL, minus the filename extension

|(?<=\w)/.+(?=\.\w+$)|

  • select everything from the first literal '/' preceded by
  • look behind a Word(\w) character
  • until followed by a look ahead
    • literal '.' appended by
    • one or more Word(\w) characters
    • before the end $
  re> |(?<=\w)/.+(?=\.\w+$)|
Compile time 0.0011 milliseconds
Memory allocation (code space): 32
  Study time 0.0002 milliseconds
Capturing subpattern count = 0
No options
First char = '/'
No need char
Max lookbehind = 1
Subject length lower bound = 2
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0007 milliseconds
 0: /manual/en/function.preg-match

|//[^/]*(.*)\.\w+$|

  • find two literal '//' followed by anything but a literal '/'
  • select everything until
  • find literal '.' followed by only Word \w characters before the end $
  re> |//[^/]*(.*)\.\w+$|
Compile time 0.0010 milliseconds
Memory allocation (code space): 28
  Study time 0.0002 milliseconds
Capturing subpattern count = 1
No options
First char = '/'
Need char = '.'
Subject length lower bound = 4
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: //php.net/manual/en/function.preg-match.php
 1: /manual/en/function.preg-match

|/[^/]+(.*)\.|

  • find literal '/' followed by at least 1 or more non literal '/'
  • aggressive select everything before the last literal '.'
  re> |/[^/]+(.*)\.|
Compile time 0.0008 milliseconds
Memory allocation (code space): 23
  Study time 0.0002 milliseconds
Capturing subpattern count = 1
No options
First char = '/'
Need char = '.'
Subject length lower bound = 3
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: /php.net/manual/en/function.preg-match.
 1: /manual/en/function.preg-match

|/[^/]+\K.*(?=\.)|

  • find literal '/' followed by at least 1 or more non literal '/'
  • Reset select start \K
  • aggressive select everything before
  • look ahead last literal '.'
  re> |/[^/]+\K.*(?=\.)|
Compile time 0.0009 milliseconds
Memory allocation (code space): 22
  Study time 0.0002 milliseconds
Capturing subpattern count = 0
No options
First char = '/'
No need char
Subject length lower bound = 2
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: /manual/en/function.preg-match

|\w+\K/.*(?=\.)|

  • find one or more Word(\w) characters before a literal '/'
  • reset select start \K
  • select literal '/' followed by
  • anything before
  • look ahead last literal '.'
  re> |\w+\K/.*(?=\.)|
Compile time 0.0009 milliseconds
Memory allocation (code space): 22
  Study time 0.0003 milliseconds
Capturing subpattern count = 0
No options
No first char
Need char = '/'
Subject length lower bound = 2
Starting byte set: 0 1 2 3 4 5 6 7 8 9 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 
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0011 milliseconds
 0: /manual/en/function.preg-match

Is Python strongly typed?

Python is strongly, dynamically typed.

  • Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
  • Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.

As for your example

bob = 1
bob = "bob"

This works because the variable does not have a type; it can name any object. After bob=1, you'll find that type(bob) returns int, but after bob="bob", it returns str. (Note that type is a regular function, so it evaluates its argument, then returns the type of the value.)

Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)

I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.

The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., + is overloaded so that it works on two numbers or two strings, but not a string and an number. This is a design choice made when + was implemented, but not really a necessity following from the language's semantics. In fact, when you overload + on a custom type, you can make it implicitly convert anything to a number:

def to_number(x):
    """Try to convert function argument to float-type object."""
    try: 
        return float(x) 
    except (TypeError, ValueError): 
        return 0 

class Foo:
    def __init__(self, number): 
        self.number = number

    def __add__(self, other):
        return self.number + to_number(other)

Instance of class Foo can be added to other objects:

>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42

Observe that even though strongly typed Python is completely fine with adding objects of type int and float and returns an object of type float (e.g., int(42) + float(1) returns 43.0). On the other hand, due to the mismatch between types Haskell would complain if one tries the following (42 :: Integer) + (1 :: Float). This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.

Setting environment variables on OS X

It's simple:

Edit ~/.profile and put your variables as follow

$ vim ~/.profile

In file put:

MY_ENV_VAR=value

  1. Save ( :wq )

  2. Restart the terminal (Quit and open it again)

  3. Make sure that`s all be fine:

$ echo $MY_ENV_VAR

$ value


Java array assignment (multiple values)

for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values

char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};

How to simulate a button click using code?

there is a better way.

View.performClick();

http://developer.android.com/reference/android/view/View.html#performClick()

this should answer all your problems. every View inherits this function, including Button, Spinner, etc.

Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call

View.performClick();

Instead, do something like:

View myView = findViewById(R.id.myview);
myView.performClick();

Variables not showing while debugging in Eclipse

Window --> Show View --> Variables

How do I display a text file content in CMD?

I don't think there is a built-in function for that

xxxx.txt > con

This opens the files in the default text editor in windows...

type xxxx.txt

This displays the file in the current window. Maybe this has params you can use...

There is a similar question here: CMD.EXE batch script to display last 10 lines from a txt file So there is a "more" command to display a file from the given line, or you can use the GNU Utilities for Win32 what bryanph suggested in his link.

Tomcat in Intellij Idea Community Edition

I am using intellij CE to create the WAR, and deploying the war externally using tomcat deployment manager. This works for testing the application however I still couldnt find the way to debug it.

  1. open cmd and current dir to tomcat/bin.
  2. you can start and stop the server using the batch files start.bat and shutdown.bat.
  3. Now build your app using mvn goal in intellij.
  4. Open localhost:8080/ **Your port number may differ.
  5. Use this tomcat application to deploy the application, If you get the authentication error, you would need to set the credentials under conf/tomcat-users.xml.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

you should be sure

to add this line at your manifest

https://developer.android.com/studio/run/index.html#instant-run

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

C: printf a float value

You need to use %2.6f instead of %f in your printf statement

Rails 4: before_filter vs. before_action

It is just a name change. before_action is more specific, because it gets executed before an action.

Throwing exceptions from constructors

If your project generally relies on exceptions to distinguish bad data from good data, then throwing an exception from the constructor is better solution than not throwing. If exception is not thrown, then object is initialized in a zombie state. Such object needs to expose a flag which says whether the object is correct or not. Something like this:

class Scaler
{
    public:
        Scaler(double factor)
        {
            if (factor == 0)
            {
                _state = 0;
            }
            else
            {
                _state = 1;
                _factor = factor;
            }
        }

        double ScaleMe(double value)
        {
            if (!_state)
                throw "Invalid object state.";
            return value / _factor;
        }

        int IsValid()
        {
            return _status;
        }

    private:
        double _factor;
        int _state;

}

Problem with this approach is on the caller side. Every user of the class would have to do an if before actually using the object. This is a call for bugs - there's nothing simpler than forgetting to test a condition before continuing.

In case of throwing an exception from the constructor, entity which constructs the object is supposed to take care of problems immediately. Object consumers down the stream are free to assume that object is 100% operational from the mere fact that they obtained it.

This discussion can continue in many directions.

For example, using exceptions as a matter of validation is a bad practice. One way to do it is a Try pattern in conjunction with factory class. If you're already using factories, then write two methods:

class ScalerFactory
{
    public:
        Scaler CreateScaler(double factor) { ... }
        int TryCreateScaler(double factor, Scaler **scaler) { ... };
}

With this solution you can obtain the status flag in-place, as a return value of the factory method, without ever entering the constructor with bad data.

Second thing is if you are covering the code with automated tests. In that case every piece of code which uses object which does not throw exceptions would have to be covered with one additional test - whether it acts correctly when IsValid() method returns false. This explains quite well that initializing objects in zombie state is a bad idea.

Is there a command to refresh environment variables from the command prompt in Windows?

I use the following code in my batch scripts:

if not defined MY_ENV_VAR (
    setx MY_ENV_VAR "VALUE" > nul
    set MY_ENV_VAR=VALUE
)
echo %MY_ENV_VAR%

By using SET after SETX it is possible to use the "local" variable directly without restarting the command window. And on the next run, the enviroment variable will be used.

How does the "view" method work in PyTorch?

Let's try to understand view by the following examples:

    a=torch.range(1,16)

print(a)

    tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14.,
            15., 16.])

print(a.view(-1,2))

    tensor([[ 1.,  2.],
            [ 3.,  4.],
            [ 5.,  6.],
            [ 7.,  8.],
            [ 9., 10.],
            [11., 12.],
            [13., 14.],
            [15., 16.]])

print(a.view(2,-1,4))   #3d tensor

    tensor([[[ 1.,  2.,  3.,  4.],
             [ 5.,  6.,  7.,  8.]],

            [[ 9., 10., 11., 12.],
             [13., 14., 15., 16.]]])
print(a.view(2,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.],
             [ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.],
             [13., 14.],
             [15., 16.]]])

print(a.view(4,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.]],

            [[ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.]],

            [[13., 14.],
             [15., 16.]]])

-1 as an argument value is an easy way to compute the value of say x provided we know values of y, z or the other way round in case of 3d and for 2d again an easy way to compute the value of say x provided we know values of y or vice versa..

Add two numbers and display result in textbox with Javascript

You can simply convert the given number using Number primitive type in JavaScript as shown below.

var c = Number(first) + Number(second);

Display label text with line breaks in c#

You may append HTML <br /> in between your lines. Something like:

MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";

With StringBuilder you can try:

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");

Overlaying a DIV On Top Of HTML 5 Video

Here's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.

<div class="outer-container">
    <div class="inner-container">
        <div class="video-overlay">Bug Buck Bunny - Trailer</div>
        <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
    </div>
</div>

with css as

.outer-container {
    border: 1px dotted black;
    width: 100%;
    height: 100%;
    text-align: center;
}
.inner-container {
    border: 1px solid black;
    display: inline-block;
    position: relative;
}
.video-overlay {
    position: absolute;
    left: 0px;
    top: 0px;
    margin: 10px;
    padding: 5px 5px;
    font-size: 20px;
    font-family: Helvetica;
    color: #FFF;
    background-color: rgba(50, 50, 50, 0.3);
}
video {
    width: 100%;
    height: 100%;
}

here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/

Hope that helps :)

Generics/templates in python?

Because Python is dynamically typed, the types of the objects don't matter in many cases. It's a better idea to accept anything.

To demonstrate what I mean, this tree class will accept anything for its two branches:

class BinaryTree:
    def __init__(self, left, right):
        self.left, self.right = left, right

And it could be used like this:

branch1 = BinaryTree(1,2)
myitem = MyClass()
branch2 = BinaryTree(myitem, None)
tree = BinaryTree(branch1, branch2)

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

How to delete rows from a pandas DataFrame based on a conditional expression

To directly answer this question's original title "How to delete rows from a pandas DataFrame based on a conditional expression" (which I understand is not necessarily the OP's problem but could help other users coming across this question) one way to do this is to use the drop method:

df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)

Example

To remove all rows where column 'score' is < 50:

df = df.drop(df[df.score < 50].index)

In place version (as pointed out in comments)

df.drop(df[df.score < 50].index, inplace=True)

Multiple conditions

(see Boolean Indexing)

The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

To remove all rows where column 'score' is < 50 and > 20

df = df.drop(df[(df.score < 50) & (df.score > 20)].index)