Programs & Examples On #Em

em is a unit of measurement in the context of typography. It can also stand for expectation-maximization in the context of statistics: use the [expectation-maximization] tag instead for this category of question.

Why em instead of px?

It's of use for everything that has to scale according to the font size.

It's especially useful on browsers which implement zoom by scaling the font size. So if you size all your elements using em they scale accordingly.

Responsive font size in CSS

One way to solve the problem of the text to look good on both desktop and mobile/tablet is in fixing the text size to physical units like physical centimeters or inches, which don't depend on the screen PPI (points per inch).

Based on this answer, below is the code I use at the end of the HTML document for a responsive font size:

<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
  var devicePixelRatio = window.devicePixelRatio || 1;
  dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;
  dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;

  function setFontSizeForClass(className, fontSize) {
      var elms = document.getElementsByClassName(className);
      for(var i=0; i<elms.length; i++) {
          elms[i].style.fontSize = String(fontSize * dpi_y / 96) + "px";
      }
  }

  setFontSizeForClass('h1-font-size', 30);
  setFontSizeForClass('action-font-size', 20);
  setFontSizeForClass('guideline-font-size', 25);
  // etc for your different classes
</script>

In the code above the items of a different class are assigned font sizes in physical units, as long as the browser/OS is configured correctly for the PPI of its screen.

A physical-unit font is always not too large and not too small, so long as the distance to the screen is usual (book-reading distance).

How to use JUnit to test asynchronous processes

It's worth mentioning that there is very useful chapter Testing Concurrent Programs in Concurrency in Practice which describes some unit testing approaches and gives solutions for issues.

How to negate specific word in regex?

If it's truly a word, bar that you don't want to match, then:

^(?!.*\bbar\b).*$

The above will match any string that does not contain bar that is on a word boundary, that is to say, separated from non-word characters. However, the period/dot (.) used in the above pattern will not match newline characters unless the correct regex flag is used:

^(?s)(?!.*\bbar\b).*$

Alternatively:

^(?!.*\bbar\b)[\s\S]*$

Instead of using any special flag, we are looking for any character that is either white space or non-white space. That should cover every character.

But what if we would like to match words that might contain bar, but just not the specific word bar?

(?!\bbar\b)\b\[A-Za-z-]*bar[a-z-]*\b
  1. (?!\bbar\b) Assert that the next input is not bar on a word boundary.
  2. \b\[A-Za-z-]*bar[a-z-]*\b Matches any word on a word boundary that contains bar.

See Regex Demo

Binding multiple events to a listener (without JQuery)?

For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.

var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
    element.addEventListener(event, function() {
        // your function body...
        console.log("you inserted things by paste or typing etc.");
    });
}

What is WebKit and how is it related to CSS?

Webkit is a web browser rendering engine used by Safari and Chrome (among others, but these are the popular ones).

The -webkit prefix on CSS selectors are properties that only this engine is intended to process, very similar to -moz properties. Many of us are hoping this goes away, for example -webkit-border-radius will be replaced by the standard border-radius and you won't need multiple rules for the same thing for multiple browsers. This is really the result of "pre-specification" features that are intended to not interfere with the standard version when it comes about.

For your update:...no it's not related to IE really, IE at least before 9 uses a different rendering engine called Trident.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Do you mean like:

$val1 = rand( 1, 10 ); // gives one integer between 1 and 10
$val2 = rand( 20, 40 ) ; // gives one integer between 20 and 40

or perhaps:

$range = range( 1, 10 ); // gives array( 1, 2, ..., 10 );
$range2 = range( 20, 40 ); // gives array( 20, 21, ..., 40 );

or maybe:

$truth1 = $val >= 1 && $val <= 10; // true if 1 <= x <= 10
$truth2 = $val >= 20 && $val <= 40; // true if 20 <= x <= 40

suppose you wanted:

$in_range = ( $val > 1 && $val < 10 ) || ( $val > 20 && $val < 40 ); // true if 1 < x < 10 OR 20 < x < 40

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Relative path to absolute path in C#?

This worked.

var s = Path.Combine(@"C:\some\location", @"..\other\file.txt");
s = Path.GetFullPath(s);

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

How to use if, else condition in jsf to display image

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

How to call function that takes an argument in a Django template?

What you could do is, create the "function" as another template file and then include that file passing the parameters to it.

Inside index.html

<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}

Inside song_player_list.html

<ul>
{%  for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i>&nbsp;Download</a>

</div>
</li>
{% endfor %}
</ul>

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

byte[] to file in Java

This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.

`Enter code here

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

//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     

public class ReadandWriteAByte {
    public void readandWriteBytesToFile(){
        File file = new File("count.char"); //(abcdefghijk)
        File bfile = new File("bytefile.txt");//(New File)
        byte[] b;
        FileInputStream fis = null;              
        FileOutputStream fos = null;          

        try{               
            fis = new FileInputStream (file);           
            fos = new FileOutputStream (bfile);             
            b = new byte [1024];              
            int i;              
            StringBuilder sb = new StringBuilder();

            while ((i = fis.read(b))!=-1){                  
                sb.append(new String(b,5,5));               
                fos.write(b, 2, 5);               
            }               

            System.out.println(sb.toString());               
        }catch (IOException e) {                    
            e.printStackTrace();                
        }finally {               
            try {              
                if(fis != null);           
                    fis.close();    //This helps to close the stream          
            }catch (IOException e){           
                e.printStackTrace();              
            }            
        }               
    }               

    public static void main (String args[]){              
        ReadandWriteAByte rb = new ReadandWriteAByte();              
        rb.readandWriteBytesToFile();              
    }                 
}                

O/P in console : fghij

O/P in new file :cdefg

Creating a directory in /sdcard fails

The correct path to the sdcard is

/mnt/sdcard/

but, as answered before, you shouldn't hardcode it. If you are on Android 2.1 or after, use

getExternalFilesDir(String type) 

Otherwise:

Environment.getExternalStorageDirectory()

Read carefully https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Also, you'll need to use this method or something similar

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

From Now() to Current_timestamp in Postgresql

You can also use now() in Postgres. The problem is you can't add/subtract integers from timestamp or timestamptz. You can either do as Mark Byers suggests and subtract an interval, or use the date type which does allow you to add/subtract integers

SELECT now()::date + 100 AS date1, current_date - 100 AS date2

Should we @Override an interface's method implementation?

You should always annotate methods with @Override if it's available.

In JDK 5 this means overriding methods of superclasses, in JDK 6, and 7 it means overriding methods of superclasses, and implementing methods of interfaces. The reason, as mentioned previously, is it allows the compiler to catch errors where you think you are overriding (or implementing) a method, but are actually defining a new method (different signature).

The equals(Object) vs. equals(YourObject) example is a standard case in point, but the same argument can be made for interface implementations.

I'd imagine the reason it's not mandatory to annotate implementing methods of interfaces is that JDK 5 flagged this as a compile error. If JDK 6 made this annotation mandatory, it would break backwards compatibility.

I am not an Eclipse user, but in other IDEs (IntelliJ), the @Override annotation is only added when implementing interface methods if the project is set as a JDK 6+ project. I would imagine that Eclipse is similar.

However, I would have preferred to see a different annotation for this usage, maybe an @Implements annotation.

Why are unnamed namespaces used and what are their benefits?

The example shows that the people in the project you joined don't understand anonymous namespaces :)

namespace {
    const int SIZE_OF_ARRAY_X;
    const int SIZE_OF_ARRAY_Y;

These don't need to be in an anonymous namespace, since const object already have static linkage and therefore can't possibly conflict with identifiers of the same name in another translation unit.

    bool getState(userType*,otherUserType*);
}

And this is actually a pessimisation: getState() has external linkage. It is usually better to prefer static linkage, as that doesn't pollute the symbol table. It is better to write

static bool getState(/*...*/);

here. I fell into the same trap (there's wording in the standard that suggest that file-statics are somehow deprecated in favour of anonymous namespaces), but working in a large C++ project like KDE, you get lots of people that turn your head the right way around again :)

What's the "average" requests per second for a production web application?

less than 2 seconds per user usually - ie users that see slower responses than this think the system is slow.

Now you tell me how many users you have connected.

How to import set of icons into Android Studio project

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Clear a terminal screen for real

Just to add that tmux scroll buffer does not clear with clear, reset or printf. You need to :clear-history. See link.

Pip install Matplotlib error with virtualenv

On OSX I was able to get matplotlib to install via:

pip install matplotlib==1.4.0

only after I ran:

brew install freetype

How to tell which commit a tag points to in Git?

In order to get the sha/hash of the commit that a tag refers to (not the sha of the tag):

git rev-list -1 <tag>

What does bundle exec rake mean?

bundle exec is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile). rake db:migrate is the script where db is the namespace and migrate is the task name defined.

So bundle exec rake db:migrate executes the rake script with the command db:migrate in the context of the current bundle.

As to the "why?" I'll quote from the bundler page:

In some cases, running executables without bundle exec may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.

However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.

PHP Convert String into Float/Double

If the function floatval does not work you can try to make this :

    $string = "2968789218";
    $float = $string * 1.0;
    echo $float;

But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

Netbeans installation doesn't find JDK

Set the JAVA_HOME variable as noted above, but also set the JRE_HOME variable to the Java Runtime Environment folder (example: C:\Program Files (x86)\Java\jdk1.6.0_23\jre )

To set the windows environment variable, right click on My Computer and select "Properties" and choose the "Advanced" tab on older windows versions, or click the "Advanced system settings" link on new versions of windows. Click the "Environment Variables" button and, in the System Variables section, click the "New" button and add the above variable names and enter the appropriate filesystem paths as the values.

After you've installed Netbeans, check the following:

Open C:\Program Files (x86)\NetBeans 6.0.1\etc\netbeans.conf

Change this value to the location of your JDK folder if it isn't set correctly already:

netbeans_jdkhome="C:\Program Files (x86)\Java\jdk1.6.0_23"

switch case statement error: case expressions must be constant expression

R.id.*, since ADT 14 are not more declared as final static int so you can not use in switch case construct. You could use if else clause instead.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

The problem, as stated in your logs, is 2 dependencies trying to use different versions of 3rd dependency. Add one of the following to the app-gradle file:

androidTestCompile 'com.google.code.findbugs:jsr305:2.0.1'
androidTestCompile 'com.google.code.findbugs:jsr305:1.3.9'

Read entire file in Scala?

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

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

equivalent:

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

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

No resource found that matches the given name '@style/Theme.AppCompat.Light'

If you are looking for the solution in Android Studio :

  1. Right click on your app
  2. Open Module Settings
  3. Select Dependencies tab
  4. Click on green + symbol which is on the right side
  5. Select Library Dependency
  6. Choose appcompat-v7 from list

PHP cURL HTTP PUT

You have mixed 2 standard.

The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";

The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

How to both read and write a file in C#

You need a single stream, opened for both reading and writing.

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

Creating Unicode character from its number

The other answers here either only support unicode up to U+FFFF (the answers dealing with just one instance of char) or don't tell how to get to the actual symbol (the answers stopping at Character.toChars() or using incorrect method after that), so adding my answer here, too.

To support supplementary code points also, this is what needs to be done:

// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);

// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));

I also did a quick test as to which conversion methods work and which don't

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);

System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

Import existing source code to GitHub

Yes. Create a new repository, doing a git init in the directory where the source currently exists.

More here: http://help.github.com/creating-a-repo/

How do I access my SSH public key?

It can be found on this path (default path):

/Users/john/.ssh

john is your Mac username.

How to mount a host directory in a Docker container

Had the same problem. Found this in the docker documentation:

Note: The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.

So, mounting a read/write host directory is only possible with the -v parameter in the docker run command, as the other answers point out correctly.

Making TextView scrollable on Android

You can either

  1. surround the TextView by a ScrollView; or
  2. set the Movement method to ScrollingMovementMethod.getInstance();.

Split an integer into digits to compute an ISBN checksum

On Older versions of Python...

map(int,str(123))

On New Version 3k

list(map(int,str(123)))

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to solve "Fatal error: Class 'MySQLi' not found"?

If you are on Docker...

Inside php-container RUN:

#docker-php-ext-install mysqli

#apachectl restart

Converting List<Integer> to List<String>

I just wanted to chime in with an object oriented solution to the problem.

If you model domain objects, then the solution is in the domain objects. The domain here is a List of integers for which we want string values.

The easiest way would be to not convert the list at all.

That being said, in order to convert without converting, change the original list of Integer to List of Value, where Value looks something like this...

class Value {
    Integer value;
    public Integer getInt()
    {
       return value;
    }
    public String getString()
    {
       return String.valueOf(value);
    }
}

This will be faster and take up less memory than copying the List.

Good Luck!

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

ImportError: No module named 'Tkinter'

You should try this :

pip install tkinter

I hope this would solve the issue.

is there a css hack for safari only NOT chrome?

There is a way to filter Safari 5+ from Chrome:

@media screen and (-webkit-min-device-pixel-ratio:0) { 
    /* Safari and Chrome */
    .myClass {
     color:red;
    }

    /* Safari only override */
    ::i-block-chrome,.myClass {
     color:blue;
    }
}

POST request not allowed - 405 Not Allowed - nginx, even with headers included

In my case it was POST submission of a json to be processed and get a return value. I cross checked logs of my app server with and without nginx. What i got was my location was not getting appended to proxy_pass url and the version of HTTP protocol version is different.

  • Without nginx: "POST /xxQuery HTTP/1.1" 200 -
  • With nginx: "POST / HTTP/1.0" 405 -

My earlier location block was

location /xxQuery {
    proxy_method POST;
    proxy_pass http://127.0.0.1:xx00/;
    client_max_body_size 10M;
}

I changed it to

location /xxQuery {
    proxy_method POST;
    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:xx00/xxQuery;
    client_max_body_size 10M;
}

It worked.

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

How to find my Subversion server version number?

One more option: If you have Firefox (I am using 14.0.1) and a SVN web interface:

  • Open Tools->Web Developer->Web Console on a repo page
  • Refresh page
  • Click on the GET line
  • Look in the Response Headers section at the Server: line

There should be an "SVN/1.7.4" string or similar there. Again, this will probably only work if you have "ServerTokens Full" as mentioned above.

Convert a positive number to negative in C#

long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);

Nobody said it had to be any particular negative number.

How to get the root dir of the Symfony2 application?

UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...

Java Desktop application: SWT vs. Swing

pro swing:

  • The biggest advantage of swing IMHO is that you do not need to ship the libraries with you application (which avoids dozen of MB(!)).
  • Native look and feel is much better for swing than in the early years
  • performance is comparable to swt (swing is not slow!)
  • NetBeans offers Matisse as a comfortable component builder.
  • The integration of Swing components within JavaFX is easier.

But at the bottom line I wouldn't suggest to use 'pure' swing or swt ;-) There are several application frameworks for swing/swt out. Look here. The biggest players are netbeans (swing) and eclipse (swt). Another nice framework could be griffon and a nice 'set of components' is pivot (swing). Griffon is very interesting because it integrates a lot of libraries and not only swing; also pivot, swt, etc

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

Where IN clause in LINQ

I like it as an extension method:

public static bool In<T>(this T source, params T[] list)
{
    return list.Contains(source);
}

Now you call:

var states = _objdatasources.StateList().Where(s => s.In(countrycodes));

You can pass individual values too:

var states = tooManyStates.Where(s => s.In("x", "y", "z"));

Feels more natural and closer to sql.

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

jQuery Mobile - back button

try to use li can be more even

<ul>
 <li><a href="#one"  data-role="button" role="button">back</a></li>
 </ul>

What is Android keystore file, and what is it used for?

The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.

How do you sort an array on multiple columns?

I had a similar problem while displaying memory pool blocks from the output of some virtual DOM h-functions composition. Basically I faced to the same problem as sorting multi-criteria data like scoring results from players around the world.

I have noticed that multi-criteria sorting is:

- sort by the first column
- if equal, sort by the second
- if equal, sort by the third
-  etc... nesting and nesting if-else

And if you don't care, you could fail quickly in a if-else nesting hell... like callback hell of promises...

What about if we write a "predicate" function to decide if which part of alternative using ? The predicate is simply :

// useful for chaining test
const decide = (test, other) => test === 0 ? other : test

Now after having written your classifying tests (byCountrySize, byAge, byGameType, byScore, byLevel...) whatever who need, you can weight your tests (1 = asc, -1 = desc, 0 = disable), put them in an array, and apply a reducing 'decide' function like this:

const multisort = (s1, s2) => {
  const bcs = -1 * byCountrySize(s1, s2) // -1 = desc 
  const ba =  1 *byAge(s1, s2)
  const bgt = 0 * byGameType(s1, s2) // 0 = doesn't matter
  const bs = 1 * byScore(s1, s2)
  const bl = -1 * byLevel(s1, s2) // -1 = desc

  // ... other weights and criterias

  // array order matters !
  return [bcs, ba, bgt, bs, bl].reduce((acc, val) => decide(val, acc), 0)
}

// invoke [].sort with custom sort...
scores.sort(multisort)

And voila ! It's up to you to define your own criterias / weights / orders... but you get the idea. Hope this helps !

EDIT: * ensure that there is a total sorting order on each column * be aware of not having dependencies between columns orders, and no circular dependencies

if, not, sorting can be unstable !

Daylight saving time and time zone best practices

If you happen to maintain database systems that are running with DST active, check carefully whether they need to be shut down during the transition in fall. Mandy DBS (or other systems as well) don't like passing the same point in (local) time twice, which is exactly what happens when you turn back the clock in fall. SAP has solved this with a (IMHO really neat) workaround - instead of turning back the clock, they just let the internal clock run at half the usual speed for two hours...

Measure execution time for a Java method

Check this: System.currentTimeMillis.

With this you can calculate the time of your method by doing:

long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;

Using group by on multiple columns

Group By X means put all those with the same value for X in the one group.

Group By X, Y means put all those with the same values for both X and Y in the one group.

To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:

Table: Subject_Selection

+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001  |        1 | John     |
| ITB001  |        1 | Bob      |
| ITB001  |        1 | Mickey   |
| ITB001  |        2 | Jenny    |
| ITB001  |        2 | James    |
| MKB114  |        1 | John     |
| MKB114  |        1 | Erica    |
+---------+----------+----------+

When you use a group by on the subject column only; say:

select Subject, Count(*)
from Subject_Selection
group by Subject

You will get something like:

+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001  |     5 |
| MKB114  |     2 |
+---------+-------+

...because there are 5 entries for ITB001, and 2 for MKB114

If we were to group by two columns:

select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester

we would get this:

+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001  |        1 |     3 |
| ITB001  |        2 |     2 |
| MKB114  |        1 |     2 |
+---------+----------+-------+

This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")

Hopefully that makes sense.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

The namespace name http://www.w3.org/1999/xhtml 
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

C default arguments

Not really. The only way would be to write a varargs function and manually fill in default values for arguments which the caller doesn't pass.

How to properly create composite primary keys - MYSQL

Suppose you have already created a table now you can use this query to make composite primary key

alter table employee add primary key(emp_id,emp_name);

Row count with PDO

when you make a COUNT(*) in your mysql statement like in

$q = $db->query("SELECT COUNT(*) FROM ...");

your mysql query is already counting the number of result why counting again in php? to get the result of your mysql

$q = $db->query("SELECT COUNT(*) as counted FROM ...");
$nb = $q->fetch(PDO::FETCH_OBJ);
$nb = $nb->counted;

and $nb will contain the integer you have counted with your mysql statement a bit long to write but fast to execute

Edit: sorry for the wrong post but as some example show query with count in, I was suggesting using the mysql result, but if you don't use the count in sql fetchAll() is efficient, if you save the result in a variable you won't loose a line.

$data = $dbh->query("SELECT * FROM ...");
$table = $data->fetchAll(PDO::FETCH_OBJ);

count($table) will return the number of row and you can still use the result after like $row = $table[0] or using a foreach

foreach($table as $row){
  print $row->id;
}

Setting a Sheet and cell as variable

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I used following logic and it worked for me like marvel:

CONVERT(TIME, DATEADD(MINUTE, DATEDIFF(MINUTE, AP.Time_IN, AP.Time_OUT), 0)) 

Python Pandas Counting the Occurrences of a Specific value

for finding a specific value of a column you can use the code below

irrespective of the preference you can use the any of the method you like

df.col_name.value_counts().Value_you_are_looking_for

take example of the titanic dataset

df.Sex.value_counts().male

this gives a count of all male on the ship Although if you want to count a numerical data then you cannot use the above method because value_counts() is used only with series type of data hence fails So for that you can use the second method example

the second method is

#this is an example method of counting on a data frame
df[(df['Survived']==1)&(df['Sex']=='male')].counts()

this is not that efficient as value_counts() but surely will help if you want to count values of a data frame hope this helps

How do I get the "id" after INSERT into MySQL database with Python?

Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...

id = cursor.lastrowid

...should work too, and it's per-connection based obviously.

NULL or BLANK fields (ORACLE)

COUNT(expresion) returns the count of of rows where expresion is not null. So SELECT COUNT (COL_NAME) FROM TABLE WHERE COL_NAME IS NULL will return 0, because you are only counting col_name where col_name is null, and a count of nothing but nulls is zero. COUNT(*) will return the number of rows of the query:

SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL

The other two queries are probably not returning any rows, since they are trying to match against strings with one blank character, and your dump query indicates that the column is actually holding nulls.

If you have rows with variable strings of space characters that you want included in the count, use:

SELECT COUNT (*) FROM TABLE WHERE trim(COL_NAME) IS NULL

trim(COL_NAME) will remove beginning and ending spaces. If the string is nothing but spaces, then the string becomes '' (empty string), which is equivalent to null in Oracle.

.NET String.Format() to add commas in thousands place for a number

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

Getting content/message from HttpResponseMessage

I think the following image helps for those needing to come by T as the return type.

enter image description here

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

import the HttpClientModule in your app.module.ts

import {HttpClientModule} from '@angular/common/http';

...
@NgModule({
...
  imports: [
    //other content,
    HttpClientModule
  ]
})

Why is the use of alloca() not considered good practice?

A place where alloca() is especially dangerous than malloc() is the kernel - kernel of a typical operating system has a fixed sized stack space hard-coded into one of its header; it is not as flexible as the stack of an application. Making a call to alloca() with an unwarranted size may cause the kernel to crash. Certain compilers warn usage of alloca() (and even VLAs for that matter) under certain options that ought to be turned on while compiling a kernel code - here, it is better to allocate memory in the heap that is not fixed by a hard-coded limit.

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Changing the width of Bootstrap popover

container: 'body' normally does the trick (see JustAnil's answer above), but there's a problem if your popover is in a modal. The z-index places it behind the modal when the popover's attached to body. This seems to be related to BS2 issue 5014, but I'm getting it on 3.1.1. You're not meant to use a container of body, but if you fix the code to

   $('#fubar').popover({
   trigger : 'hover',
   html    : true,
   dataContainer : '.modal-body',
   ...etc });

then you fix the z-index problem, but the popover width is still wrong.

The only fix I can find is to use container: 'body' and to add some extra css:

.popover { 
  max-width : 400px;
  z-index   : 1060;
}

Note that css solutions by themselves won't work.

How to embed small icon in UILabel

Try dragging a UIView onto the screen in IB. From there you can drag a UIImageView and UILabel into the view you just created. Set the image of the UIImageView in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.

Can I position an element fixed relative to parent?

With multiple divs I managed to get a fixed-y and absolute-x divs. In my case I needed a div on left and right sides, aligned to a centered 1180px width div.

    <div class="parentdiv" style="
        background: transparent;
        margin: auto;
        width: 100%;
        max-width: 1220px;
        height: 10px;
        text-align: center;">
        <div style="
            position: fixed;
            width: 100%;
            max-width: 1220px;">
            <div style="
                position: absolute;
                background: black;
                height: 20px;
                width: 20px;
                left: 0;">
            </div>
            <div style="
                width: 20px;
                height: 20px;
                background: blue;
                position: absolute;                                           
                right: 0;">
            </div>
        </div>
    </div>

eclipse stuck when building workspace

The only solution for me (Luna 4.4.1) was this:

Go to Project Properties > Builders and then uncheck the Javascript Validator.

How to draw a dotted line with css?

To do this, you simple need to add a border-top or border-bottom to your <hr/> tag as the following:

<hr style="border-top: 2px dotted navy" />

with any line type or color you want

Good MapReduce examples

One of the best examples of Hadoop-like MapReduce implementation.

Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).

MySQL command line client for Windows

Its pretty simple. I saved the mysql community server in my D:\ drive. Hence this is how i did it.

Goto D:\mysql-5.7.18-winx64\bin and in the address bar type cmd and press enter, so command prompt will open. Now if you're using it for the first time type as mysql -u root -ppress enter. Then it will ask for password, again press enter. Thats it you are connected to the mysql server.

Before this make sure wamp or xampp any of the local server is running because i couldn't able to connect to mysql wihthout xampp running. enter image description here

enter image description here

Happy Coding.

How to draw circle by canvas in Android?

If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.

public class CustomView extends View {

    public CustomView(Context context,  AttributeSet attrs) {
        super(context, attrs);
        setupPaint();
    }
}

Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)

private Paint drawPaint;

// Setup paint with color and stroke styles
private void setupPaint() {
    drawPaint = new Paint();
    drawPaint.setColor(Color.BLUE);
    drawPaint.setAntiAlias(true);
    drawPaint.setStrokeWidth(5);
    drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    drawPaint.setStrokeJoin(Paint.Join.ROUND);
    drawPaint.setStrokeCap(Paint.Cap.ROUND);
}

And initialise canvas object

private Canvas canvas;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}

And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw

canvas.invalidate();

For more details on canvas drawing refer https://medium.com/@mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b

Getting one value from a tuple

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

How to use a typescript enum value in an Angular2 ngSwitch statement

This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template

  statusEnum: typeof StatusEnum = StatusEnum;

HTML5 event handling(onfocus and onfocusout) using angular 2

The solution is this:

  <input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
  [matAutocomplete]="auto">
   <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
     <mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of 
      options | async" [value]="option">
      {{option.name | translate}}
     </mat-option>
  </mat-autocomplete>

TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}

Is there a way to force npm to generate package-lock.json?

If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.

Example: Upgrade your current npm to version 6.14.0

npm i -g [email protected]

You could view the latest npm version list by

npm view npm versions

JavaScript variable number of arguments to function

Yes, just like this :

function load()
{
  var var0 = arguments[0];
  var var1 = arguments[1];
}

load(1,2);

How do I get the current date in Cocoa

There is no difference in the location of the asterisk (at in C, which Obj-C is based on, it doesn't matter). It is purely preference (style).

Google Text-To-Speech API

#! /usr/bin/python2
# -*- coding: utf-8 -*-

def run(cmd):
    import os
    import sys
    from subprocess import Popen, PIPE
    print(cmd)
    proc=Popen(cmd, stdin=None, stdout=PIPE, stderr=None, shell=True)
    while True:
        data = proc.stdout.readline()   # Alternatively proc.stdout.read(1024)
        if len(data) == 0:
            print("Finished process")
            break
        sys.stdout.write(data)

import urllib

msg='Hello preety world'
msg=urllib.quote_plus(msg)
# -v verbosity
cmd='curl '+ \
    '--output tts_responsivevoice.mp2 '+ \
    "\""+'https://code.responsivevoice.org/develop/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \
    ' -H '+"\""+'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0'+"\""+ \
    ' -H '+"\""+'Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5'+"\""+ \
    ' -H '+"\""+'Accept-Language: pl,en-US;q=0.7,en;q=0.3'+"\""+ \
    ' -H '+"\""+'Range: bytes=0-'+"\""+ \
    ' -H '+"\""+'Referer: http://code.responsivevoice.org/develop/examples/example2.html'+"\""+ \
    ' -H '+"\""+'Cookie: __cfduid=ac862i73b6a61bf50b66713fdb4d9f62c1454856476; _ga=GA1.2.2126195996.1454856480; _gat=1'+"\""+ \
    ' -H '+"\""+'Connection: keep-alive'+"\""+ \
    ''
print('***************************')
print(cmd)
print('***************************')
run(cmd)

Line:

/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \

is responsible for language.

tl=en-US

There is another preety interesting site with tts engines that can be used in this manner.

substitute o for null iv0na.c0m

have a nice day

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

HashMaps and Null values?

HashMap supports both null keys and values

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

... and permits null values and the null key

So your problem is probably not the map itself.

Getting an option text/value with JavaScript

In jquery you could try this $("#select_id>option:selected").text()

How to pass a PHP variable using the URL

All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)

document.getElementByID is not a function

It's getElementById()

Note the lower-case d in Id.

How to integrate sourcetree for gitlab

It worked for me, but only with ssh key and not with username and password.

After i added the ssh key to sourcetree, i changed the settings under Tools -> Options -> SSH-Client to work with PuTTY/Plink.

I run into trouble after i added the ssh key, because i forgot to restart sourceTree. "this is necessary so that there is an instance of ssh-agent running that SourceTree can talk to with your key loaded." See here: https://answers.atlassian.com/questions/189412/sourcetree-with-gitlab-ssh-not-working

Oracle Differences between NVL and Coalesce

NVL will do an implicit conversion to the datatype of the first parameter, so the following does not error

select nvl('a',sysdate) from dual;

COALESCE expects consistent datatypes.

select coalesce('a',sysdate) from dual;

will throw a 'inconsistent datatype error'

The import com.google.android.gms cannot be resolved

Note that once you have imported the google-play-services_lib project into your IDE, you will also need to add google-play-services.jar to: Project=>Properties=>Java build path=>Libraries=>Add JARs

How to select rows in a DataFrame between two values, in Python Pandas?

Instead of this

df = df[(99 <= df['closing_price'] <= 101)]

You should use this

df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]

We have to use NumPy's bitwise Logic operators |, &, ~, ^ for compounding queries. Also, the parentheses are important for operator precedence.

For more info, you can visit the link :Comparisons, Masks, and Boolean Logic

Undo working copy modifications of one file in Git?

If it is already committed, you can revert the change for the file and commit again, then squash new commit with last commit.

How do you create a daemon in Python?

Current solution

A reference implementation of PEP 3143 (Standard daemon process library) is now available as python-daemon.

Historical answer

Sander Marechal's code sample is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

How to get Maven project version to the bash command line

I kept running into side cases when using some of the other answers here, so here's yet another alternative.

version=$(printf 'VER\t${project.version}' | mvn help:evaluate | grep '^VER' | cut -f2)

"CASE" statement within "WHERE" clause in SQL Server 2008

Try the following:

select * From emp_master 
where emp_last_name= 
case emp_first_name 
 when 'test'    then 'test' 
 when 'Mr name' then 'name'
end

Modifying list while iterating

The general rule of thumb is that you don't modify a collection/array/list while iterating over it.

Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.

how to find my angular version in my project?

  1. Browser > Inspect > Element >

    <.app-root _nghost-hey-c0="" ng-version="8.2.11">

  2. In terminal

    :> ng version
    :> ng --version
    :> ng -v

Loop through all the resources in a .resx file

  // Create a ResXResourceReader for the file items.resx.
  ResXResourceReader rsxr = new ResXResourceReader("items.resx");

  // Create an IDictionaryEnumerator to iterate through the resources.
  IDictionaryEnumerator id = rsxr.GetEnumerator();       

  // Iterate through the resources and display the contents to the console.
  foreach (DictionaryEntry d in rsxr) 
  {
Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
  }

 //Close the reader.
 rsxr.Close();

see link: microsoft example

Downloading a picture via urllib and python

If you need proxy support you can do this:

  if needProxy == False:
    returnCode, urlReturnResponse = urllib.urlretrieve( myUrl, fullJpegPathAndName )
  else:
    proxy_support = urllib2.ProxyHandler({"https":myHttpProxyAddress})
    opener = urllib2.build_opener(proxy_support)
    urllib2.install_opener(opener)
    urlReader = urllib2.urlopen( myUrl ).read() 
    with open( fullJpegPathAndName, "w" ) as f:
      f.write( urlReader )

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

delete all from table

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

TRUNCATE TABLE table_name

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

Two models in one view in ASP MVC 3

Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.

How can I find the first and last date in a month using PHP?

You can use the date function to find how many days in a month there are.

// Get the timestamp for the date/month in question.
$ts = strtotime('April 2010');

echo date('t', $ts); 
// Result: 30, therefore, April 30, 2010 is the last day of that month.

Hope that helps.

EDIT: After reading Luis' answer, it occurred to me you may want it in the right format (YY-mm-dd). It may be obvious, but doesn't hurt to mention:

// After the above code
echo date('Y-m-t', $ts); 

Default keystore file does not exist?

In macOS, open the Terminal and type below command

~/.android

It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)

In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.

keytool -list -v -keystore debug.keystore

You will get the expected output.

How to concat a string to xsl:value-of select="...?

The easiest way to concat a static text string to a selected value is to use element.

<a>
  <xsl:attribute name="href"> 
    <xsl:value-of select="/*/properties/property[@name='report']/@value" />
    <xsl:text>staticIconExample.png</xsl:text>
  </xsl:attribute>
</a>

WAMP shows error 'MSVCR100.dll' is missing when install

When installing Wamperserver 3 on windows 10, it now gives a nice big warning during the install telling you it won't work unless you install many of these packages.

It worked for me after I followed the instructions and then restart the computer and reinstalled.

--- Installation of Wampserver --- BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing. Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 , VC14 and VC15 See --- Visual C++ Packages below.

--- Do not install Wampserver OVER an existing version, follow the advice: - Install a new version of Wampserver: http://forum.wampserver.com/read.php?2,123606 If you install Wampserver over an existing version, not only it will not work, but you risk losing your existing databases.

--- Install Wampserver in a folder at the root of a disk, for example C:\wamp or D:\wamp. Take an installation path that does not include spaces or diacritics; Therefore, no installation in c: \ Program Files\ or C: \ Program Files (x86\ We must BEFORE installing, disable or close some applications: - Close Skype or force not to use port 80 Item No. 04 of the Wampserver TROUBLESHOOTING TIPS:http://forum.wampserver.com/read.php?2,134915 - Disable IIS Item No. 08 of the Wampserver TROUBLESHOOTING TIPS:http://forum.wampserver.com/read.php?2,134915 If these prerequisites are not in place, Press the Cancel button to cancel the installation, then apply the prerequisites and restart the installation. This program requires Administrator privileges to function properly. It will be launched with the "Run as administrator" option. If you do not want a program to have this option, cancel the installation.

--- Visual C++ Packages --- The MSVC runtime libraries VC9, VC10, VC11 are required for Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions with VC11. Runtimes VC13, VC14 is required for PHP 7 and Apache 2.4.17 or more

-- VC9 Packages (Visual C++ 2008 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=5582 http://www.microsoft.com/en-us/download/details.aspx?id=2092

-- VC10 Packages (Visual C++ 2010 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=8328 http://www.microsoft.com/en-us/download/details.aspx?id=13523

-- VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679 -- VC13 Packages Update 5(Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: https://support.microsoft.com/en-us/help/4032938/

-- VC14 Packages (Visual C++ 2015 Update 3) Supersedes by VC15 - VC15 Redistribuable (Visual C++ 2017) https://aka.ms/vs/15/release/VC_redist.x86.exe https://aka.ms/vs/15/release/VC_redist.x64.exe VC2017 (VC15) is backward compatible to VC2015 (VC14). That means, a VC14 module can be used inside a VC15 binary. Because this compatibility the version number of the Redistributable is 14.1x.xx and after you install the Redistributable VC2017, VC2015 is removed but you can still use VC14.

If you have a 64-bit Windows, you must install both 32 and 64bit versions of each VisualC++ package, even if you do not use Wampserver 64 bit To verify that all VC ++ packages are installed and with the latest versions, you can use the tool: http://wampserver.aviatechno.net/files/tools/check_vcredist.exe and you will find all the packages on http://wampserver.aviatechno.net/ in section Visual C++ Redistribuable Packages You must install each package "as an administrator", so right-click the exe file and then run as Administrator. Do not use a previously loaded tool. Make a new download to make sure you are using the correct version.

Warning: Sometimes Microsoft may update the VC ++ package by breaking the download links and without redirect to the new. If the case happens to you, remember that item number 20 below will be updated and the page http://wampserver.aviatechno.net/ section Visual C++ Redistribuable Packages is up to date. This is item number 20 of TROUBLESHOOTING TIPS of Wampserver: http://forum.wampserver.com/read.php?2,134915

How to make a round button?

Round button in Android

You can make a ImageButton with circular background image.

Usage of \b and \r in C

The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line. If you print these characters somewhere else, like a text file, the software may choose. to do something else.

How do I check if a string is unicode or ascii?

Note that on Python 3, it's not really fair to say any of:

  • strs are UTFx for any x (eg. UTF8)

  • strs are Unicode

  • strs are ordered collections of Unicode characters

Python's str type is (normally) a sequence of Unicode code points, some of which map to characters.


Even on Python 3, it's not as simple to answer this question as you might imagine.

An obvious way to test for ASCII-compatible strings is by an attempted encode:

"Hello there!".encode("ascii")
#>>> b'Hello there!'

"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>>   File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)

The error distinguishes the cases.

In Python 3, there are even some strings that contain invalid Unicode code points:

"Hello there!".encode("utf8")
#>>> b'Hello there!'

"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>>   File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed

The same method to distinguish them is used.

Compilation error - missing zlib.h

Maybe you can download zlib.h from https://dev.w3.org/Amaya/libpng/zlib/zlib.h, and put it in the directory to solve the problem.

Difference between two dates in Python

pd.date_range('2019-01-01', '2019-02-01').shape[0]

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Reading a binary file with python

Read the binary file content like this:

with open(fileName, mode='rb') as file: # b is important -> binary
    fileContent = file.read()

then "unpack" binary data using struct.unpack:

The start bytes: struct.unpack("iiiii", fileContent[:20])

The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i' to create the correct format for the unpack method:

struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])

The end byte: struct.unpack("i", fileContent[-4:])

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

How can I get the assembly file version

There are three versions: assembly, file, and product. They are used by different features and take on different default values if you don't explicit specify them.

string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); 
string assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString(); 
string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; 
string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

How to give spacing between buttons using bootstrap

Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.

ImportError: No module named PytQt5

this can be solved under MacOS X by installing pyqt with brew

brew install pyqt

How to increment a pointer address and pointer's value?

The following is an instantiation of the various "just print it" suggestions. I found it instructive.

#include "stdio.h"

int main() {
    static int x = 5;
    static int *p = &x;
    printf("(int) p   => %d\n",(int) p);
    printf("(int) p++ => %d\n",(int) p++);
    x = 5; p = &x;
    printf("(int) ++p => %d\n",(int) ++p);
    x = 5; p = &x;
    printf("++*p      => %d\n",++*p);
    x = 5; p = &x;
    printf("++(*p)    => %d\n",++(*p));
    x = 5; p = &x;
    printf("++*(p)    => %d\n",++*(p));
    x = 5; p = &x;
    printf("*p++      => %d\n",*p++);
    x = 5; p = &x;
    printf("(*p)++    => %d\n",(*p)++);
    x = 5; p = &x;
    printf("*(p)++    => %d\n",*(p)++);
    x = 5; p = &x;
    printf("*++p      => %d\n",*++p);
    x = 5; p = &x;
    printf("*(++p)    => %d\n",*(++p));
    return 0;
}

It returns

(int) p   => 256688152
(int) p++ => 256688152
(int) ++p => 256688156
++*p      => 6
++(*p)    => 6
++*(p)    => 6
*p++      => 5
(*p)++    => 5
*(p)++    => 5
*++p      => 0
*(++p)    => 0

I cast the pointer addresses to ints so they could be easily compared.

I compiled it with GCC.

Cache an HTTP 'Get' service response in AngularJS?

Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.

FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.

(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)

How to stop IIS asking authentication for default website on localhost

It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.

I did it and my problem solved.

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I wanted to install SQL server 2014 and same story happened. I had installed both VS2010 and VS2015 before. I tried all solutions where provided nothing worked.At last If you have new versions of VS like VS2015 or VS2017, uninstall VS2010 (if you really don't need it ).

If you want to have VS2010 on your system, install SQL server first and then install VS2010.When SQL server is installing it uses an instance of VS2010, if you have installed VS2010 before and that is an old version this error happens.

What is an MvcHtmlString and when should I use it?

A nice practical use of this is if you want to make your own HtmlHelper extensions. For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

Can the Android drawable directory contain subdirectories?

create a folder in main. like: 'res_notification_btn'

and create tree folder in. like 'drawable' or 'layout'

then in 'build.gradle' add this

sourceSets
            {
                main
                {
                    res
                    {
                        srcDirs = ['src/main/res_notification_btn', 'src/main/res']
                      or
                        srcDir 'src/main/res_notification_btn'
                    }
                }
            }

How do I implement basic "Long Polling"?

Why not consider the web sockets instead of long polling? They are much efficient and easy to setup. However they are supported only in modern browsers. Here is a quick reference.

Get git branch name in Jenkins Pipeline/Jenkinsfile

If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.

You can print them with:

pipeline {
    agent any

    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'sqlite'
    }

    stages {
        stage('Build') {
            steps {
                sh 'printenv'
            }
        }
    }
}

However, PR 91 shows that the branch name is only set in certain pipeline configurations:

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

Counting unique values in a column in pandas dataframe like in Qlik?

Or get the number of unique values for each column:

df.nunique()

dID    3
hID    5
mID    3
uID    5
dtype: int64

New in pandas 0.20.0 pd.DataFrame.agg

df.agg(['count', 'size', 'nunique'])

         dID  hID  mID  uID
count      8    8    8    8
size       8    8    8    8
nunique    3    5    3    5

You've always been able to do an agg within a groupby. I used stack at the end because I like the presentation better.

df.groupby('mID').agg(['count', 'size', 'nunique']).stack()


             dID  hID  uID
mID                       
A   count      5    5    5
    size       5    5    5
    nunique    3    5    5
B   count      2    2    2
    size       2    2    2
    nunique    2    2    2
C   count      1    1    1
    size       1    1    1
    nunique    1    1    1

Setting up a JavaScript variable from Spring model by using Thymeleaf

MAKE sure you have thymleaf on page already

//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
 model.addAttribute("showTextFromJavaController","dummy text");
 return "showingTymleafTextInJavaScript";
}


//thymleaf page  javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>

split string in two on given index and return both parts

You can also do it like this.
https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp

var str, result;
str = prompt("Enter Any Number");

var valueSplit = function (value, length) {
    if (length < 7) {
        var index = length - 3;
        return str.slice(0, index) + ',' + str.slice(index);
    }
    else if (length < 10 && length > 6) {
        var index1, index2;
        index1 = length - 6;
        index2 = length - 3;
        return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);
    }
}

result = valueSplit(str, str.length);
alert(result);

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

PHP server on local machine?

PHP 5.4 and later have a built-in web server these days.

You simply run the command from the terminal:

cd path/to/your/app
php -S 127.0.0.1:8000

Then in your browser go to http://127.0.0.1:8000 and boom, your system should be up and running. (There must be an index.php or index.html file for this to work.)

You could also add a simple Router

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    require_once('resolver.php');
}
?>

And then run the command

php -S 127.0.0.1:8000 router.php

References:

How do I configure different environments in Angular.js?

I'm a little late to the thread, but if you're using Grunt I've had great success with grunt-ng-constant.

The config section for ngconstant in my Gruntfile.js looks like

ngconstant: {
  options: {
    name: 'config',
    wrap: '"use strict";\n\n{%= __ngModule %}',
    space: '  '
  },
  development: {
    options: {
      dest: '<%= yeoman.app %>/scripts/config.js'
    },
    constants: {
      ENV: 'development'
    }
  },
  production: {
    options: {
      dest: '<%= yeoman.dist %>/scripts/config.js'
    },
    constants: {
      ENV: 'production'
    }
  }
}

The tasks that use ngconstant look like

grunt.registerTask('server', function (target) {
  if (target === 'dist') {
    return grunt.task.run([
      'build',
      'open',
      'connect:dist:keepalive'
    ]);
  }

  grunt.task.run([
    'clean:server',
    'ngconstant:development',
    'concurrent:server',
    'connect:livereload',
    'open',
    'watch'
  ]);
});

grunt.registerTask('build', [
  'clean:dist',
  'ngconstant:production',
  'useminPrepare',
  'concurrent:dist',
  'concat',
  'copy',
  'cdnify',
  'ngmin',
  'cssmin',
  'uglify',
  'rev',
  'usemin'
]);

So running grunt server will generate a config.js file in app/scripts/ that looks like

"use strict";
angular.module("config", []).constant("ENV", "development");

Finally, I declare the dependency on whatever modules need it:

// the 'config' dependency is generated via grunt
var app = angular.module('myApp', [ 'config' ]);

Now my constants can be dependency injected where needed. E.g.,

app.controller('MyController', ['ENV', function( ENV ) {
  if( ENV === 'production' ) {
    ...
  }
}]);

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Unable to import path from django.urls

How to use url both app(pages) and in the project.

entire project url configuration root/urls.py

 from django.conf.urls import url, include
 from django.contrib import admin
 urlpatterns = [
     url(r'^admin/', admin.site.urls),
     url('', include('pages.urls')),
   ]

app pages url configuration root/pages/urls.py

# pages/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url('', views.homePageView, name='home')
]

how to increase java heap memory permanently?

The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:

under Windows:

SET _JAVA_OPTIONS = -Xms512m -Xmx1024m

under Linux:

export _JAVA_OPTIONS="-Xms512m -Xmx1024m"

It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.

public class GetHeapSize {
    public static void main(String[]args){

        //Get the jvm heap size.
        long heapSize = Runtime.getRuntime().totalMemory();

        //Print the jvm heap size.
        System.out.println("Heap Size = " + heapSize);
    }
}

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

There is a slight difference between the top answers, namely SUM(case when kind = 1 then 1 else 0 end) and SUM(kind=1).

When all values in column kind happen to be NULL, the result of SUM(case when kind = 1 then 1 else 0 end) is 0, whereas the result of SUM(kind=1) is NULL.

An example (http://sqlfiddle.com/#!9/b23807/2):

Schema:

CREATE TABLE Table1
(`first_col` int, `second_col` int)
;

INSERT INTO Table1
    (`first_col`, `second_col`)
VALUES
       (1, NULL),
       (1, NULL),
       (NULL, NULL)
;

Query results:

SELECT SUM(first_col=1) FROM Table1;
-- Result: 2
SELECT SUM(first_col=2) FROM Table1;
-- Result: 0
SELECT SUM(second_col=1) FROM Table1;
-- Result: NULL
SELECT SUM(CASE WHEN second_col=1 THEN 1 ELSE 0 END) FROM Table1;
-- Result: 0

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

As a companion to the answers explaining cleanup and install via homebrew, I found that homebrew itself provided clear indications of the symlink clashes.

Unfortunately it provides these one by one as it encounters them, so it is a little laborious, but it does seem to find all the clashes and was the only way I could get a clean install with homebrew.

Essentially, the process is:

  1. use homebrew to uninstall node
  2. clean homebrew
  3. use homebrew to install node and note any flagged clashing file
  4. delete the flag clashing file (or whole directory if it is a 'node' directory)
  5. goto step 1 until you get a clean install

Diagrammatically:

Here is a screen output from the last steps of my install - you can see it results in a clean install (eventually...):

computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/systemtap/tapset/node.stp
Target /usr/local/share/systemtap/tapset/node.stp
already exists. You may want to remove it:
  rm '/usr/local/share/systemtap/tapset/node.stp'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/share/systemtap/tapset/node.stp
/usr/local/lib/dtrace/node.d
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ rm '/usr/local/share/systemtap/tapset/node.stp'
computer1:DevResources user1$ brew uninstall node
Uninstalling /usr/local/Cellar/node/13.1.0... (4,591 files, 54.2MB)
computer1:DevResources user1$ brew cleanup
computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink lib/dtrace/node.d
Target /usr/local/lib/dtrace/node.d
already exists. You may want to remove it:
  rm '/usr/local/lib/dtrace/node.d'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/lib/dtrace/node.d
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ rm '/usr/local/lib/dtrace/node.d'
computer1:DevResources user1$ 
computer1:DevResources user1$ brew uninstall node
Uninstalling /usr/local/Cellar/node/13.1.0... (4,591 files, 54.2MB)
computer1:DevResources user1$ brew cleanup
computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ node -v
v13.1.0

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

You can get the same error in Asp.net MVC5 if you have a class name and a folder with a matching name Example : If you have class lands where when you want to see view/lands/index.cshtml file, if you also have a folder with name 'lands' you get the error as it first try the lands folder

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

In my case there was no space left in my machine and I faced the same issue. Some times it could be the space issue. Check the space in your Linux/Unix environment and make sure your machine have enough space.

Stop setInterval

we can easily stop the set interval by calling clear interval

var count = 0 , i = 5;
var vary = function intervalFunc() {
  count++;
      console.log(count);
    console.log('hello boy');  
    if (count == 10) {
      clearInterval(this);
    }
}

  setInterval(vary, 1500);

How to access static resources when mapping a global front controller servlet on /*

Add the folders which you don't want to trigger servlet processing to the <static-files> section of your appengine-web.xml file.

I just did this and looks like things are starting to work ok. Here's my structure:

/

/pages/<.jsp files>

/css

I added "/pages/**" and "/css/**" to the <static-files> section and I can now forward to a .jsp file from inside a servlet doGet without causing an infinite loop.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

jQuery toggle CSS?

The best option would be to set a class style in CSS like .showMenu and .hideMenu with the various styles inside. Then you can do something like

$("#user_button").addClass("showMenu"); 

How do I fix the multiple-step OLE DB operation errors in SSIS?

This error is common when the source table contains a TEXT column and the target is anything other than a TEXT column. It can be a real time-eater if you have not encountered (or forgot!) this before.

Convert the text column to string and set the error condition on truncation to ignore. this will usually serve as a solution for this error.

Laravel: getting a a single value from a MySQL query

As of Laravel >= 5.3, best way is to use value:

$groupName = \App\User::where('username',$username)->value('groupName');

or

use App\User;//at top of controller
$groupName = User::where('username',$username)->value('groupName');//inside controller function

Of course you have to create a model User for users table which is most efficient way to interact with database tables in Laravel.

How to write a switch statement in Ruby

You can use regular expressions, such as finding a type of string:

case foo
when /^(true|false)$/
   puts "Given string is boolean"
when /^[0-9]+$/ 
   puts "Given string is integer"
when /^[0-9\.]+$/
   puts "Given string is float"
else
   puts "Given string is probably string"
end

Ruby's case will use the equality operand === for this (thanks @JimDeville). Additional information is available at "Ruby Operators". This also can be done using @mmdemirbas example (without parameter), only this approach is cleaner for these types of cases.

ng-repeat: access key and value for each object in array of objects

A repeater inside a repeater

<div ng-repeat="step in steps">
    <div ng-repeat="(key, value) in step">
        {{key}} : {{value}}
    </div>
</div>

No suitable records were found verify your bundle identifier is correct

if your app transfer other account. You should rearrange Signing section for the corrcet team(new team)

Best way to alphanumeric check in JavaScript

Check it with a regex.

Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

if (!input_string.match(/^[0-9a-z]+$/))
  show_error_or_something()

Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.

More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

CSS3 Transform Skew One Side

You try with the :before was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/

Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/

NodeJs : TypeError: require(...) is not a function

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

Usage of sys.stdout.flush() method

Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

javascript windows alert with redirect function

You could do this:

echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";

Proxy Basic Authentication in C#: HTTP 407 error

This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.

Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.

request.Proxy.Credentials = CredentialCache.DefaultCredentials;

TypeScript sorting an array

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

How can I access Oracle from Python?

You can use any of the following way based on Service Name or SID whatever you have.

With SID:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', 'sid')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

OR

With Service Name:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

Catch KeyError in Python

I dont think python has a catch :)

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e

How to search a specific value in all tables (PostgreSQL)?

There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml() function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:

To search for the string foo across all tables in a schema, the following can be used:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

Note that the use of xmltable requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

The common table expression (WITH ...) is only used for convenience. It loops through all tables in the public schema. For each table the following query is run through the query_to_xml() function:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

The conversion of the complete row to jsonb is done, so that in the result one could see which value belongs to which column.

The above might return something like this:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Online example for Postgres 10+

Online example for older Postgres versions

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How to parse unix timestamp to time.Time

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

Playground: http://play.golang.org/p/v_j6UIro7a

Edit:

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

Can I mask an input text in a bat file?

Yes - I am 4 years late.

But I found a way to do this in one line without having to create an external script; by calling powershell commands from a batch file.

Thanks to TessellatingHeckler - without outputting to a text file (I set the powershell command in a variable, because it's pretty messy in one long line inside a for loop).

@echo off
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
echo %password%

Originally I wrote it to output to a text file, then read from that text file. But the above method is better. In one extremely long, near incomprehensible line:

@echo off
powershell -Command $pword = read-host "Enter password" -AsSecureString ; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password=<.tmp.txt & del .tmp.txt
echo %password%

I'll break this down - you can split it up over a few lines using caret ^, which is much nicer...

@echo off
powershell -Command $pword = read-host "Enter password" -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt 
set /p password=<.tmp.txt & del .tmp.txt
echo %password%

This article explains what the powershell commands are doing; essentially it gets input using Read-Host -AsSecureString - the following two lines convert that secure string back into plain text, the output (plaintext password) is then sent to a text file using >.tmp.txt. That file is then read into a variable and deleted.

Executing a batch script on Windows shutdown

For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:

mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown

It's just that GP needs those directories to exist for:

Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)

to function properly.

Google Chrome "window.open" workaround?

Why is this still so complicated in 2021? For me I wanted to open in a new chrome window fullscreen so I used the below:

window.open("http://my.url.com", "", "fullscreen=yes");

This worked as exepected opening a new chrome window. Without the options at the end it will only open a new tab

How to initialize an array in Java?

You cannot initialize an array like that. In addition to what others have suggested, you can do :

data[0] = 10;
data[1] = 20;
...
data[9] = 91;

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

Pandas "Can only compare identically-labeled DataFrame objects" error

Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

One solution is to sort the index first (Note: some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

Note: == is also sensitive to the order of columns, so you may have to use sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

Note: This can still raise (if the index/columns aren't identically labelled after sorting).

Style bottom Line in Android

it is completely transparent Edittext with transparent background.

<item>
    <shape android:shape="rectangle" >
        <solid android:color="@color/transparent" />
    </shape>
</item>

<item android:top="-3dp" android:right="-3dp" android:left="-3dp">
    <shape>
        <solid android:color="@android:color/transparent" />
        <stroke

            android:width="2dp"
            android:color="@color/bottomline" />
    </shape>
</item>

What does the "__block" keyword mean?

__block is a storage qualifier that can be used in two ways:

  1. Marks that a variable lives in a storage that is shared between the lexical scope of the original variable and any blocks declared within that scope. And clang will generate a struct to represent this variable, and use this struct by reference(not by value).

  2. In MRC, __block can be used to avoid retain object variables a block captures. Careful that this doesn't work for ARC. In ARC, you should use __weak instead.

You can refer to apple doc for detailed information.

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

Oracle DateTime in Where Clause?

Yes: TIME_CREATED contains a date and a time. Use TRUNC to strip the time:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') 
      AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1

Are there such things as variables within an Excel formula?

You could define a name for the VLOOKUP part of the formula.

  1. Highlight the cell that contains this formula
  2. On the Insert menu, go Name, and click Define
  3. Enter a name for your variable (e.g. 'Value')
  4. In the Refers To box, enter your VLOOKUP formula: =VLOOKUP(A1,B:B, 1, 0)
  5. Click Add, and close the dialog
  6. In your original formula, replace the VLOOKUP parts with the name you just defined: =IF( Value > 10, Value - 10, Value )

Step (1) is important here: I guess on the second row, you want Excel to use VLOOKUP(A2,B:B, 1, 0), the third row VLOOKUP(A3,B:B, 1, 0), etc. Step (4) achieves this by using relative references (A1 and B:B), not absolute references ($A$1 and $B:$B).

Note:

  1. For newer Excel versions with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)

  2. Shortened steps: 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)

Simulating Slow Internet Connection

You can try Dummynet, it can simulates queue and bandwidth limitations, delays, packet losses, and multipath effects

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

from pip.req import parse_requirements did not work for me and I think it's for the blank lines in my requirements.txt, but this function does work

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

Eclipse JPA Project Change Event Handler (waiting)

The solution for eclipse photon seems to be:

  1. open ./eclipse/configuration/org.eclipse.equinox.simpleconfigurator/bundles.info
  2. delete the lines starting with org.eclipse.jpt (might work to only remove org.eclipse.jpt.jpa)

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))