Programs & Examples On #Nvcc

nvcc is NVIDIA's LLVM-based C/C++ compiler for targeting GPUs with CUDA.

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

Testing HTML email rendering

If you don't want to use a submission service like Litmus (Litmus is the best, BTW) then you're just going to have to run Outlook 2007 to test your email.

It sounds like you want something a little more automatic (though I'm not sure why), but fortunately Outlook is easy to automate using Visual Basic for Applications (VBA).

You can write a VBA tool that runs from the command line to generate an email, load the email up in Outlook, and even capture a screenshot if you wish. (Presumably this is what the Litmus team does on the backend.)

(BTW, do not attempt to use MS Word to test mail; the renderer is similar but subtle differences in page layout can affect the rendering of your email.)

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Change URL parameters

Using javascript URL:

var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;

PHP order array by date?

You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.

$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);

What is the correct syntax of ng-include?

    <ng-include src="'views/sidepanel.html'"></ng-include>

OR

    <div ng-include="'views/sidepanel.html'"></div>

OR

    <div ng-include src="'views/sidepanel.html'"></div>

Points To Remember:

--> No spaces in src

--> Remember to use single quotation in double quotation for src

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

Parsing query strings on Android

I have methods to achieve this:

1):

public static String getQueryString(String url, String tag) {
    String[] params = url.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String param : params) {
        String name = param.split("=")[0];
        String value = param.split("=")[1];
        map.put(name, value);
    }

    Set<String> keys = map.keySet();
    for (String key : keys) {
        if(key.equals(tag)){
         return map.get(key);
        }
        System.out.println("Name=" + key);
        System.out.println("Value=" + map.get(key));
    }
    return "";
}

2) and the easiest way to do this Using Uri class:

public static String getQueryString(String url, String tag) {
    try {
        Uri uri=Uri.parse(url);
        return uri.getQueryParameter(tag);
    }catch(Exception e){
        Log.e(TAG,"getQueryString() " + e.getMessage());
    }
    return "";
}

and this is an example of how to use either of two methods:

String url = "http://www.jorgesys.com/advertisements/publicidadmobile.htm?position=x46&site=reform&awidth=800&aheight=120";      
String tagValue = getQueryString(url,"awidth");

the value of tagValue is 800

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

List files with certain extensions with ls and grep

In case you are still looking for an alternate solution:

ls | grep -i -e '\\.tcl$' -e '\\.exe$' -e '\\.mp4$'

Feel free to add more -e flags if needed.

Formatting code snippets for blogging on Blogger

1. First, take backup of your blogger template
2. After that open your blogger template (In Edit HTML mode) & copy the all css given in this link before </b:skin> tag
3. Paste the followig code before </head> tag

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

4. Paste the following code before </body> tag.

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

5. Save Blogger Template.
6. Now syntax highlighting is ready to use you can use it with <pre></pre> tag.

<pre name="code">
...Your html-escaped code goes here...
</pre>

<pre name="code" class="php">
    echo "I like PHP";
</pre>

7. You can Escape your code here.
8. Here is list of supported language for <class> attribute.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Go to pom.xml

Add this Dependency :

   <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>

using command prompt, find your folder: - mvn clean

Angular: Can't find Promise, Map, Set and Iterator

Angular 2 Final

- es5 support (Works perfectly with TS 2.0.0 +)

Per update es6-shim isn't supported now, if you have both typings installed together es6-shim & core-js together. Remove es6-shim typing by mentioning in tsconfig.json. You could now refer below core-js typing for es5 support inside main.ts

///<reference path="./../typings/globals/core-js/index.d.ts"/>

tsconfig.json

exclude: [
   "node_modules", //<-- this would be needed in case of VS2015
   "node_modules/@typings",
   "typings"
]

- es6 suppport

You just need to set "target" property to es6, then all will error go away. And the transpiled code will be in es6 format.

How to trigger jQuery change event in code

$(selector).change()

.change()


.trigger("change")

Longer slower alternative, better for abstraction.

.trigger("change")

$(selector).trigger("change")

Remove Duplicate objects from JSON Array

The following works for me:

_.uniq(standardsList, JSON.stringify)

This would probably be slow for very long lists, however.

Catch multiple exceptions in one line (except block)

One of the way to do this is..

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

How to replace blank (null ) values with 0 for all records?

I would change the SQL statement above to be more generic. Using wildcards is never a bad idea when it comes to mass population to avoid nulls.

Try this:

Update Table Set * = 0 Where * Is Null; 

Angularjs prevent form submission when input validation fails

You can do:

<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">

No need for controller checks.

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.

Directory-tree listing in Python

Here is another option.

os.scandir(path='.')

It returns an iterator of os.DirEntry objects corresponding to the entries (along with file attribute information) in the directory given by path.

Example:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

Python Docs

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

Python 3 print without parenthesis

Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.

However, print without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:

Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: var = 'Hello world'

In [2]: /print var
Hello world

And if you turn on autocall, you won't even need to type the slash:

In [3]: %autocall
Automatic calling is: Smart

In [4]: print var
------> print(var)
Hello world

Rownum in postgresql

Postgresql have limit.

Oracle's code:

select *
from
  tbl
where rownum <= 1000;

same in Postgresql's code:

select *
from
  tbl
limit 1000

XAMPP - Apache could not start - Attempting to start Apache service

when i run xampp control panel normal:

enter image description here

I had been run

I can’t start apache So, I will run it with administrator:

enter image description here

I can run apache

Loop through all the files with a specific extension

I found this solution to be quite handy. It uses the -or option in find:

find . -name \*.tex -or -name "*.png" -or -name "*.pdf"

It will find the files with extension tex, png, and pdf.

How do you clone an Array of Objects in Javascript?

Map will create new array from the old one (without reference to old one) and inside the map you create new object and iterate over properties (keys) and assign values from old Array object to coresponding properties to the new object.

This will create exactly the same array of objects.

let newArray = oldArray.map(a => {
               let newObject = {};
               Object.keys(a).forEach(propertyKey => {
                    newObject[propertyKey] = a[propertyKey];
               });
               return newObject ;
});

Is there a no-duplicate List implementation out there?

I just made my own UniqueList in my own little library like this:

package com.bprog.collections;//my own little set of useful utilities and classes

import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Jonathan
*/
public class UniqueList {

private HashSet masterSet = new HashSet();
private ArrayList growableUniques;
private Object[] returnable;

public UniqueList() {
    growableUniques = new ArrayList();
}

public UniqueList(int size) {
    growableUniques = new ArrayList(size);
}

public void add(Object thing) {
    if (!masterSet.contains(thing)) {
        masterSet.add(thing);
        growableUniques.add(thing);
    }
}

/**
 * Casts to an ArrayList of unique values
 * @return 
 */
public List getList(){
    return growableUniques;
}

public Object get(int index) {
    return growableUniques.get(index);
}

public Object[] toObjectArray() {
    int size = growableUniques.size();
    returnable = new Object[size];
    for (int i = 0; i < size; i++) {
        returnable[i] = growableUniques.get(i);
    }
    return returnable;
    }
}

I have a TestCollections class that looks like this:

package com.bprog.collections;
import com.bprog.out.Out;
/**
*
* @author Jonathan
*/
public class TestCollections {
    public static void main(String[] args){
        UniqueList ul = new UniqueList();
        ul.add("Test");
        ul.add("Test");
        ul.add("Not a copy");
        ul.add("Test"); 
        //should only contain two things
        Object[] content = ul.toObjectArray();
        Out.pl("Array Content",content);
    }
}

Works fine. All it does is it adds to a set if it does not have it already and there's an Arraylist that is returnable, as well as an object array.

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

How to extract base URL from a string in JavaScript?

You can do it using a regex :

/(http:\/\/)?(www)[^\/]+\//i

does it fit ?

Error handling in getJSON calls

Here's my addition.

From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source

"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

I did that and here is Luciano's updated code snippet:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

And with error description plus showing all json data as a string:

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

If you don't like alerts, substitute them with console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

Java SSL: how to disable hostname verification

I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:

public class Test {
    //Bypassing the SSL verification to execute our code successfully 
    static {
        disableSSLVerification();
    }

    public static void main(String[] args) {    
        //Access HTTPS URL and do something    
    }
    //Method used for bypassing SSL verification
    public static void disableSSLVerification() {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }

        } };

        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };      
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);           
    }
}

It worked for me. try it!!

SQL - How do I get only the numbers after the decimal?

More generalized approach may be to merge PARSENAME and % operator. (as answered in two of the answers above)

Results as per 1st approach above by SQLMenace

select PARSENAME(0.001,1) 

Result: 001

select PARSENAME(0.0010,1) 

Result: 0010

select PARSENAME(-0.001,1)

Result: 001

select PARSENAME(-1,1)

Result: -1 --> Should not return integer part

select PARSENAME(0,1)

Result: 0

select PARSENAME(1,1)

Result: 1 --> Should not return integer part

select PARSENAME(100.00,1)

Result: 00

Results as per 1st approach above by Pavel Morshenyuk "0." is part of result in this case.

SELECT (100.0001 % 1)

Result: 0.0001

SELECT (100.0010 % 1)

Result: 0.0010

SELECT (0.0001 % 1)

Result: 0.0001

SELECT (0001 % 1)

Result: 0

SELECT (1 % 1)

Result: 0

SELECT (100 % 1)

Result: 0

Combining both:

SELECT PARSENAME((100.0001 % 1),1)

Result: 0001

SELECT PARSENAME((100.0010 % 1),1)

Result: 0010

SELECT PARSENAME((0.0001 % 1),1)

Result: 0001

SELECT PARSENAME((0001 % 1),1)

Result: 0

SELECT PARSENAME((1 % 1),1)

Result: 0

SELECT PARSENAME((100 % 1),1)

Result: 0

But still one issue which remains is the zero after the non zero numbers are part of the result (Example: 0.0010 -> 0010). May be one have to apply some other logic to remove that.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

How to link to apps on the app store

This worked for me perfectly using only APP ID:

 NSString *urlString = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@",YOUR_APP_ID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

The number of redirects is ZERO.

Creating a folder if it does not exists - "Item already exists"

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

OpenSSL and error in reading openssl.conf file

I was also facing same issue. Below are the steps to resolve it.

  1. check your openssl version

openssl version

  1. If your version is below

OpenSSL 1.1.1h 22 Sep 2020

  1. go to below link and download latest full version of openssl. openssl windows installer
  2. After installation add openssl path at the top of 'PATH' variable in system path.
  3. confirm your version is latest by opening new command prompt and running command in step 1
  4. Now you're ready to run the command again and this time it will work.

How to set value of input text using jQuery

Here is another variation for a file upload that has a nicer looking bootstrap button than the default file upload browse button. This is the html:

<div class="form-group">
        @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "col-md-2  control-label" })
        <div class="col-md-1 btn btn-sn btn-primary" id="browseButton" onclick="$(this).parent().find('input[type=file]').click();">browse</div>
        <div class="col-md-7">
            <input id="fileSpace" name="uploaded_file"  type="file" style="display: none;">   @*style="display: none;"*@
            @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control", @id = "modelField"} })
            @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
        </div>
    </div>

Here is the script:

        $('#fileSpace').on("change", function () {
        $("#modelField").val($('input[name="uploaded_file"]').val());

Email & Phone Validation in Swift

another solution for variety sake..

public extension String {
    public var validPhoneNumber:Bool {
        let types:NSTextCheckingType = [.PhoneNumber]
        guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }

        if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber {
            return match == self
        }else{
            return false
        }
    }
}

//and use like so:
if "16465551212".validPhoneNumber {
    print("valid phone number")
}

What's a .sh file?

If you open your second link in a browser you'll see the source code:

#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov

[...]

# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4 
for year in {2002..2003}
do
   for tile in {1159..1160}
        do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
        # An example using curl instead of wget
    #do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
     done
done

So it's a bash script. Got Linux?


In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.

How to add a filter class in Spring Boot?

Here is an example of one method of including a custom filter in a Spring Boot MVC application. Be sure to include the package in a component scan:

package com.dearheart.gtsc.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
public class XClacksOverhead implements Filter {

  public static final String X_CLACKS_OVERHEAD = "X-Clacks-Overhead";

  @Override
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {

    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader(X_CLACKS_OVERHEAD, "GNU Terry Pratchett");
    chain.doFilter(req, res);
  }

  @Override
  public void destroy() {}

  @Override
  public void init(FilterConfig arg0) throws ServletException {}

}

Accessing session from TWIG template

A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :

public function getGlobals() {
    return array(
        'session'   => $_SESSION,
    ) ;
}

Then, you'll be able to acces any session variable as :

{{ session.username }}

if you want to access to

$_SESSION['username']

Find a string between 2 known values

For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.

    public static string[] GetStringInBetween(string strBegin,
        string strEnd, string strSource,
        bool includeBegin, bool includeEnd)           
    {
        string[] result ={ "", "" };
        int iIndexOfBegin = strSource.IndexOf(strBegin);
        if (iIndexOfBegin != -1)
        {
            // include the Begin string if desired
            if (includeBegin)
                iIndexOfBegin -= strBegin.Length;
            strSource = strSource.Substring(iIndexOfBegin
                + strBegin.Length);
            int iEnd = strSource.IndexOf(strEnd);
            if (iEnd != -1)
            {
                // include the End string if desired
                if (includeEnd)
                    iEnd += strEnd.Length;
                result[0] = strSource.Substring(0, iEnd);
                // advance beyond this segment
                if (iEnd + strEnd.Length < strSource.Length)
                    result[1] = strSource.Substring(iEnd
                        + strEnd.Length);
            }
        }
        else
            // stay where we are
            result[1] = strSource;
        return result;
    }

How to get selenium to wait for ajax response?

In my case the issue seemed due to ajax delays but was related to internal iframes inside the main page. In seleminum it is possible to switch to internal frames with:

    driver.switchTo().frame("body");
    driver.switchTo().frame("bodytab");

I use java. After that I was able to locate the element

    driver.findElement(By.id("e_46")).click();

Label on the left side instead above an input field

It seems adding style="width:inherit;" to the inputs works fine. jsfiddle demo

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing

  • ENU\x64\SharedManagementObjects.msi for X64 OS or

  • ENU\x86\SharedManagementObjects.msi for X86 OS

  • ENU\x64\SQLSysClrTypes.msi

  • Reinstalling Sql Server 2014

What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

Release generating .pdb files, why?

Why are you so sure you will not debug release builds? Sometimes (hopefully rarely but happens) you may get a defect report from a customer that is not reproducible in the debug version for some reason (different timings, small different behaviour or whatever). If that issue appears to be reproducible in the release build you'll be happy to have the matching pdb.

Timing a command's execution in PowerShell

Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.

Sjoemelsoftware

'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".

Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.

As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.

The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!

Let presume that you dot-source your . .\Dosomething.ps1 command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command):

$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}

(Measure-Command {
    $PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237

(Measure-Command {
    $Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949

The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...

Let's display the results:

PS C:\> $PowerShell

Index  Property
-----  --------
12345 104123841

PS C:\> $Linq

Index  Property
-----  --------
12345 104123841

As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq results then the $PowerShell results.
Let's specifically measure that by just retrieving a property of the resulted object:

PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435

It took about a factor 90 longer to retrieve a property of the $Linq object then the $PowerShell object and that was just a single object!

Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.

Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.

(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle

How to find Max Date in List<Object>?

troubleshooting-friendly style

You should not call .get() directly. Optional<>, that Stream::max returns, was designed to benefit from .orElse... inline handling.

If you are sure your arguments have their size of 2+:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));

If you support empty lists, then return some default value, for example:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElse(new Date(Long.MIN_VALUE));

CREDITS to: @JimmyGeers, @assylias from the accepted answer.

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

Set session variable in laravel

The correct syntax for this is...

Session::set('variableName', $value);

For Laravel 5.4 and later, the correct method to use is put.

Session::put('variableName', $value);

To get the variable, you'd use...

Session::get('variableName');

If you need to set it once, I'd figure out when exactly you want it set and use Events to do it. For example, if you want to set it when someone logs in, you'd use...

Event::listen('auth.login', function()
{
    Session::set('variableName', $value);
});

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

How can I have grep not print out 'No such file or directory' errors?

If you are grepping through a git repository, I'd recommend you use git grep. You don't need to pass in -R or the path.

git grep pattern

That will show all matches from your current directory down.

How to install an apk on the emulator in Android Studio?

Drag and drop apk if the emulator is launched from Android Studio. If the emulator is started from command line, drag and drop doesn't work, but @Tarek K. Ajaj instructions (above) work.

Note: Installed app won't automatically appear on the home screen, it is in the apps container - the dotted grid icon. It can be dragged from there to the home screen.

How to publish a website made by Node.js to Github Pages?

GitHub pages host only static HTML pages. No server side technology is supported, so Node.js applications won't run on GitHub pages. There are lots of hosting providers, as listed on the Node.js wiki.

App fog seems to be the most economical as it provides free hosting for projects with 2GB of RAM (which is pretty good if you ask me).
As stated here, AppFog removed their free plan for new users.

If you want to host static pages on GitHub, then read this guide. If you plan on using Jekyll, then this guide will be very helpful.

How to display binary data as image - extjs 4

Need to convert it in base64.

JS have btoa() function for it.

For example:

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);

But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.

Update:

Need to write simple hex to base64 converter:

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

And use it:

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');

See working example with your hex data on jsfiddle

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help.

img.save("tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

PHP Call to undefined function

Many times the problem comes because php does not support short open tags in php.ini file, i.e:

<?
   phpinfo();
?>

You must use:

<?php
   phpinfo();
?>

Visual Studio can't build due to rc.exe

This might be a little outdated. But if copying the rc.exe and exdll.dll did not work, there is a chance that the windows sdk is not installed properly even if the windows sdk folder exists. You can update the sdk for win 8 in the following page: http://msdn.microsoft.com/en-US/windows/hardware/hh852363 After re-installing the sdk, the problem would get solved. Also make sure that platform toolset is set properly.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Instead of using window.open you can use a link with the onclick event.
And you can put the html table into the uri and set the file name to be downloaded.

Live demo :

_x000D_
_x000D_
function exportF(elem) {_x000D_
  var table = document.getElementById("table");_x000D_
  var html = table.outerHTML;_x000D_
  var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url _x000D_
  elem.setAttribute("href", url);_x000D_
  elem.setAttribute("download", "export.xls"); // Choose the file name_x000D_
  return false;_x000D_
}
_x000D_
<table id="table" border="1">_x000D_
  <tr>_x000D_
    <td>_x000D_
      Foo_x000D_
    </td>_x000D_
    <td>_x000D_
      Bar_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>
_x000D_
_x000D_
_x000D_

php & mysql query not echoing in html with tags?

You need to append your variables to the echoed string. For example:

echo 'This is a string '.$PHPvariable.' and this is more string'; 

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had this issue with an MVC project and here is how I fixed it.

  1. Open BundleConfig.cs
  2. Find :

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));

    Change to:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
    

This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.

Check if an element contains a class in JavaScript?

Element.matches()

element.matches(selectorString)

According to MDN Web Docs:

The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

Therefore, you can use Element.matches() to determine if an element contains a class.

_x000D_
_x000D_
const element = document.querySelector('#example');

console.log(element.matches('.foo')); // true
_x000D_
<div id="example" class="foo bar"></div>
_x000D_
_x000D_
_x000D_

View Browser Compatibility

How to print matched regex pattern using awk?

If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

For example, given a file with the following contents, (called asdf.txt)

xxx yyy zzz

to only print the second column if it matches the pattern "yyy", you could do something like this:

awk '$2 ~ /yyy/ {print $2}' asdf.txt

Note that this will also match basically any line where the second column has a "yyy" in it, like these:

xxx yyyz zzz
xxx zyyyz

Memcache Vs. Memcached

They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE in cache. Value FALSE returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode that will tell you whether key was found.

Because of this limitation I switched to storing empty arrays instead of FALSE in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

AppStore - App status is ready for sale, but not in app store

After 48 hours of the still not being updated I removed the app from sale on Pricing and Availability.

Then I waited 1 hour.

Then I ticked All Territories Selected again.

After the app came available for download again the version number was updated.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

How can I use interface as a C# generic type constraint?

I tried to do something similar and used a workaround solution: I thought about implicit and explicit operator on structure: The idea is to wrap the Type in a structure that can be converted into Type implicitly.

Here is such a structure:

public struct InterfaceType { private Type _type;

public InterfaceType(Type type)
{
    CheckType(type);
    _type = type;
}

public static explicit operator Type(InterfaceType value)
{
    return value._type;
}

public static implicit operator InterfaceType(Type type)
{
    return new InterfaceType(type);
}

private static void CheckType(Type type)
{
    if (type == null) throw new NullReferenceException("The type cannot be null");
    if (!type.IsInterface) throw new NotSupportedException(string.Format("The given type {0} is not an interface, thus is not supported", type.Name));
}

}

basic usage:

// OK
InterfaceType type1 = typeof(System.ComponentModel.INotifyPropertyChanged);

// Throws an exception
InterfaceType type2 = typeof(WeakReference);

You have to imagine your own mecanism around this, but an example could be a method taken a InterfaceType in parameter instead of a type

this.MyMethod(typeof(IMyType)) // works
this.MyMethod(typeof(MyType)) // throws exception

A method to override that should returns interface types:

public virtual IEnumerable<InterfaceType> GetInterfaces()

There are maybe things to do with generics also, but I didn't tried

Hope this can help or gives ideas :-)

Reload an iframe with jQuery

you can also use jquery. This is the same what Alex proposed just using JQuery:

 $('#currentElement').attr("src", $('#currentElement').attr("src"));

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

How to completely uninstall Android Studio from windows(v10)?

.android  

check this folder in

C:\Users\user

its have an issue and fix it then restart android studio.

remove space between paragraph and unordered list

You can (A) change the markup to not use paragraphs

<span>Text</span>
<br>
<ul>
  <li>One</li>
</ul>
<span>Text 2</span>

Or (B) change the css

p{margin:0px;}

Demos here: http://jsfiddle.net/ZnpVu/1

Change the background color of a row in a JTable

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

In this example, clicking on the button changes the background color for a row and then calls repaint.

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

MessageBox Buttons?

if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
         //do stuff if yess
}
else
{
         //do stuff if No
}

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Haversine Formula in Python (Bearing and Distance between two GPS points)

There is also a vectorized implementation, which allows to use 4 numpy arrays instead of scalar values for coordinates:

def distance(s_lat, s_lng, e_lat, e_lng):

   # approximate radius of earth in km
   R = 6373.0

   s_lat = s_lat*np.pi/180.0                      
   s_lng = np.deg2rad(s_lng)     
   e_lat = np.deg2rad(e_lat)                       
   e_lng = np.deg2rad(e_lng)  

   d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2

   return 2 * R * np.arcsin(np.sqrt(d))

How do I put the image on the right side of the text in a UIButton?

Being that the transform solution doesn't work in iOS 11 I decided to write a new approach.

Adjusting the buttons semanticContentAttribute gives us the image nicely to the right without having to relayout if the text changes. Because of this it's the ideal solution. However I still need RTL support. The fact that an app can not change it's layout direction in the same session resolves this issue easily.

With that said, it's pretty straight forward.

extension UIButton {
    func alignImageRight() {
        if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
            semanticContentAttribute = .forceRightToLeft
        }
        else {
            semanticContentAttribute = .forceLeftToRight
        }
    }
}

How to check if string contains Latin characters only?

Ahh, found the answer myself:

if (/[a-zA-Z]/.test(num)) {
  alert('Letter Found')
}

How to make child element higher z-index than parent?

Use non-static position along with greater z-index in child element:

.parent {
    position: absolute
    z-index: 100;
}

.child {
    position: relative;
    z-index: 101;
}

Angular - "has no exported member 'Observable'"

use return Observable.of(HEROES);

How to align an indented line in a span that wraps into multiple lines?

<!DOCTYPE html>
<html>
<body>

<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>

</body>
</html>

Switching from zsh to bash on OSX, and back again?

you can just type bash or if you always want to use bash:

on "iTerm2"

  • Go to preferences > Profiles > Command
  • Select "Command" from the dropdown
  • Type bash

Test by closing iTerm and open it again

Difference between decimal, float and double in .NET?

The problem with all these types is that a certain imprecision subsists AND that this problem can occur with small decimal numbers like in the following example

Dim fMean as Double = 1.18
Dim fDelta as Double = 0.08
Dim fLimit as Double = 1.1

If fMean - fDelta < fLimit Then
    bLower = True
Else
    bLower = False
End If

Question: Which value does bLower variable contain ?

Answer: On a 32 bit machine bLower contains TRUE !!!

If I replace Double by Decimal, bLower contains FALSE which is the good answer.

In double, the problem is that fMean-fDelta = 1.09999999999 that is lower that 1.1.

Caution: I think that same problem can certainly exists for other number because Decimal is only a double with higher precision and the precision has always a limit.

In fact, Double, Float and Decimal correspond to BINARY decimal in COBOL !

It is regrettable that other numeric types implemented in COBOL don't exist in .Net. For those that don't know COBOL, there exist in COBOL following numeric type

BINARY or COMP like float or double or decimal
PACKED-DECIMAL or COMP-3 (2 digit in 1 byte)
ZONED-DECIMAL (1 digit in 1 byte) 

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

Background image jumps when address bar hides iOS/Android/Mobile Chrome

For those who would like to listen to the actual inner height and vertical scroll of the window while the Chrome mobile browser is transition the URL bar from shown to hidden and vice versa, the only solution that I found is to set an interval function, and measure the discrepancy of the window.innerHeight with its previous value.

This introduces this code:

_x000D_
_x000D_
var innerHeight = window.innerHeight;_x000D_
window.setInterval(function ()_x000D_
{_x000D_
  var newInnerHeight = window.innerHeight;_x000D_
  if (newInnerHeight !== innerHeight)_x000D_
  {_x000D_
    var newScrollY = window.scrollY + newInnerHeight - innerHeight;_x000D_
    // ... do whatever you want with this new scrollY_x000D_
    innerHeight = newInnerHeight;_x000D_
  }_x000D_
}, 1000 / 60);
_x000D_
_x000D_
_x000D_

I hope that this will be handy. Does anyone knows a better solution?

delete map[key] in go?

Use make (chan int) instead of nil. The first value has to be the same type that your map holds.

package main

import "fmt"

func main() {

    var sessions = map[string] chan int{}
    sessions["somekey"] = make(chan int)

    fmt.Printf ("%d\n", len(sessions)) // 1

    // Remove somekey's value from sessions
    delete(sessions, "somekey")

    fmt.Printf ("%d\n", len(sessions)) // 0
}

UPDATE: Corrected my answer.

How to make an executable JAR file?

Here it is in one line:

jar cvfe myjar.jar package.MainClass *.class

where MainClass is the class with your main method, and package is MainClass's package.

Note you have to compile your .java files to .class files before doing this.

c  create new archive
v  generate verbose output on standard output
f  specify archive file name
e  specify application entry point for stand-alone application bundled into an executable jar file

This answer inspired by Powerslave's comment on another answer.

ASP.NET GridView RowIndex As CommandArgument

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

Does Hibernate create tables in the database automatically

Hibernate can create a table, hibernate sequence and tables used for many-to-many mapping on your behalf but you have to explicitly configure it by calling setProperty("hibernate.hbm2ddl.auto", "create") of the Configuration object. By Default, it just validates the schema with DB and fails if anything not already exists by giving error "ORA-00942: table or view does not exist".

If you do above configuration then order of performed actions will be:- a) Drop all tables and sequence and do not give an error if they are not already present. b) create all table and sequence c) alter tables with constraints d) insert data into it.

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

Convert char array to a int number in C

So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

OSError: [Errno 8] Exec format error

Have you tried this?

Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

Edited per the apt comment from @J.F.Sebastian

Node.js/Express.js App Only Works on Port 3000

The following works if you have something like this in your app.js:

http.createServer(app).listen(app.get('port'),
  function(){
    console.log("Express server listening on port " + app.get('port'));
});

Either explicitly hardcode your code to use the port you want, like:

app.set('port', process.env.PORT || 3000);

This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.

Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.

$ PORT=8080 node app.js

In reference to your code example, you want something like this:

var express = require("express");
var app = express();

// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);

app.get('/', function(req, res){
    res.send('hello world');
});

// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));

How to get Activity's content view?

How about

View view = Activity.getCurrentFocus();

Sql server - log is full due to ACTIVE_TRANSACTION

Here is what I ended up doing to work around the error.

First, I set up the database recovery model as SIMPLE. More information here.

Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.

I reran the DELETE statement sucessfully without any warning.

I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:

DBCC SHRINKDATABASE (MyDb, 0);
GO

More information about that command here.

Send values from one form to another form

How to pass the values from form to another form

1.) Goto Form2 then Double click it. At the code type this.

public Form2(string v)
{
  InitializeComponent();
  textBox1.Text = v;
}

2.) Goto Form1 then Double click it. At the code type this. //At your command button in Form1

private void button1_Click(object sender, EventArgs e)
{
   Form2 F2 = new Form2(textBox1.Text);
   F2.Show();
}

Composer: Command Not Found

Your composer.phar command lacks the flag for executable, or it is not inside the path.

The first problem can be fixed with chmod +x composer.phar, the second by calling it as ./composer.phar -v.

You have to prefix executables that are not in the path with an explicit reference to the current path in Unix, in order to avoid going into a directory that has an executable file with an innocent name that looks like a regular command, but is not. Just think of a cat in the current directory that does not list files, but deletes them.

The alternative, and better, fix for the second problem would be to put the composer.phar file into a location that is mentioned in the path

How to change the foreign key referential action? (behavior)

Remember that MySQL keeps a simple index on a column after deleting foreign key. So, if you need to change 'references' column you should do it in 3 steps

  • drop original FK
  • drop an index (names as previous fk, using drop index clause)
  • create new FK

How to search and replace text in a file?

As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

Unless you've got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The number of binary trees can be calculated using the catalan number.

The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of Left binary search sub-trees) * (Number of Right binary search sub-trees) * (Ways to choose the root)

In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are 1, 2, 3, 4, ...., n. Also, let the number of BST be represented by f(n) for n elements.

Now we have the multiple cases for choosing the root.

  1. choose 1 as root, no element can be inserted on the left sub-tree. n-1 elements will be inserted on the right sub-tree.
  2. Choose 2 as root, 1 element can be inserted on the left sub-tree. n-2 elements can be inserted on the right sub-tree.
  3. Choose 3 as root, 2 element can be inserted on the left sub-tree. n-3 elements can be inserted on the right sub-tree.

...... Similarly, for i-th element as the root, i-1 elements can be on the left and n-i on the right.

These sub-trees are itself BST, thus, we can summarize the formula as:

f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)

Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.

Final Formula

How to stop INFO messages displaying on spark console?

Use below command to change log level while submitting application using spark-submit or spark-sql:

spark-submit \
--conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml" \
--conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml"

Note: replace <file path> where log4j config file is stored.

Log4j.properties:

log4j.rootLogger=ERROR, console

# set the log level for these components
log4j.logger.com.test=DEBUG
log4j.logger.org=ERROR
log4j.logger.org.apache.spark=ERROR
log4j.logger.org.spark-project=ERROR
log4j.logger.org.apache.hadoop=ERROR
log4j.logger.io.netty=ERROR
log4j.logger.org.apache.zookeeper=ERROR

# add a ConsoleAppender to the logger stdout to write to the console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# use a simple message format
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

log4j.xml

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8" ?>_x000D_
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">_x000D_
_x000D_
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">_x000D_
   <appender name="console" class="org.apache.log4j.ConsoleAppender">_x000D_
    <param name="Target" value="System.out"/>_x000D_
    <layout class="org.apache.log4j.PatternLayout">_x000D_
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />_x000D_
    </layout>_x000D_
  </appender>_x000D_
    <logger name="org.apache.spark">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.spark-project">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.apache.hadoop">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="io.netty">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.apache.zookeeper">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
   <logger name="org">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <root>_x000D_
        <priority value ="ERROR" />_x000D_
        <appender-ref ref="console" />_x000D_
    </root>_x000D_
</log4j:configuration>
_x000D_
_x000D_
_x000D_

Switch to FileAppender in log4j.xml if you want to write logs to file instead of console. LOG_DIR is a variable for logs directory which you can supply using spark-submit --conf "spark.driver.extraJavaOptions=-D.

_x000D_
_x000D_
<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">_x000D_
        <param name="file" value="${LOG_DIR}"/>_x000D_
        <param name="datePattern" value="'.'yyyy-MM-dd"/>_x000D_
        <layout class="org.apache.log4j.PatternLayout">_x000D_
            <param name="ConversionPattern" value="%d [%t] %-5p %c %x - %m%n"/>_x000D_
        </layout>_x000D_
    </appender>
_x000D_
_x000D_
_x000D_

Another important thing to understand here is, when job is launched in distributed mode ( deploy-mode cluster and master as yarn or mesos) the log4j configuration file should exist on driver and worker nodes (log4j.configuration=file:<file path>/log4j.xml) else log4j init will complain-

log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (No such file or directory)

Hint on solving this problem-

Keep log4j config file in distributed file system(HDFS or mesos) and add external configuration using log4j PropertyConfigurator. or use sparkContext addFile to make it available on each node then use log4j PropertyConfigurator to reload configuration.

Allowing Untrusted SSL Certificates with HttpClient

Most answers here suggest to use the typical pattern:

using (var httpClient = new HttpClient())
{
 // do something
}

because of the IDisposable interface. Please don't!

Microsoft tells you why:

And here you can find a detailed analysis whats going on behind the scenes: You're using HttpClient wrong and it is destabilizing your software

Regarding your SSL question and based on Improper Instantiation antipattern # How to fix the problem

Here is your pattern:

class HttpInterface
{
 // https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
 // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
 private static readonly HttpClient client;

 // static initialize
 static HttpInterface()
 {
  // choose one of these depending on your framework
  
  // HttpClientHandler is an HttpMessageHandler with a common set of properties
  var handler = new HttpClientHandler()
  {
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };
  // derives from HttpClientHandler but adds properties that generally only are available on full .NET
  var handler = new WebRequestHandler()
  {
      ServerCertificateValidationCallback = delegate { return true; },
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };

  client = new HttpClient(handler);
 }
 
 .....
 
 // in your code use the static client to do your stuff
 var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");

 // here in sync
 using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
 {
  using (HttpContent respContent = resultMsg.Content)
  {
   return respContent.ReadAsStringAsync().Result;
  }
 }
}

Converting NSString to NSDate (and back again)

Date to NSString

NSString *dateString = [NSString stringWithFormat:@"%@",[NSDate date]];
NSLog(@"string: %@",dateString ); //2015-03-24 12:28:49 +0000

NSString to NSDate

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date); //015-03-24 12:28:49 +0000

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

Django - "no module named django.core.management"

I had the same issue and the reason I was getting this message was because I was doing "manage.py runserver" whereas doing "python manage.py runserver" fixed it.

Change the location of an object programmatically

Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:

this.balancePanel.Location = new Point(
    this.optionsPanel.Location.X,
    this.balancePanel.Location.Y);

Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;

var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;

Although I don't recommend the above, since structs should ideally be immutable.

What does it mean "No Launcher activity found!"

Here's an example from AndroidManifest.xml. You need to specify the MAIN and LAUNCHER in the intent filter for the activity you want to start on launch

<application android:label="@string/app_name" android:icon="@drawable/icon">
    <activity android:name="ExampleActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Node.js create folder or use existing

I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

LAST UPDATE :

In v10.12.0, NodeJS impletement recursive options :

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

UPDATE :

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create 
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

Preloading images with JavaScript

You can move this code to index.html for preload images from any url

<link rel="preload" href="https://via.placeholder.com/160" as="image">

RegExp matching string not starting with my

You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:

^(.?$|[^m].+|m[^y].*)

This matches strings that are either zero or one characters long (^.?$) and thus can not be my. Or strings with two or more characters where when the first character is not an m any more characters may follow (^[^m].+); or if the first character is a m it must not be followed by a y (^m[^y]).

Get The Current Domain Name With Javascript (Not the path, etc.)

If you want the country domain name - for example to extract  .com  from  stackoverflow.com :

(ES6):

const getCountryDomainName = () => {
  let hostName = window.location.hostname;
  let lastDotIndex = hostName.lastIndexOf('.');
  let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
  return countryDomainName;
}

(ES5):

function getCountryDomainName() {
  let hostName = window.location.hostname;
  let lastDotIndex = hostName.lastIndexOf('.');
  let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
  return countryDomainName;
}

Then, just use the function to assign the value to a var:

const countryDomainName = getCountryDomainName();

What's the whole point of "localhost", hosts and ports at all?

Everyone seems to focus on the host part of your questions. Ports are used to be able to run several servers (for example for different purposes such as file sharing, web serving, printing, etc) from the same machine (one single IP address).

How to vertically align an image inside a div

Try this solution with pure CSS http://jsfiddle.net/sandeep/4RPFa/72/

Maybe it is the main problem with your HTML. You're not using quotes when you define class & image height in your HTML.

CSS:

.frame {
    height: 25px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    position: relative;
    margin: 1em 0;
    top: 50%;
    text-align: center;
    line-height: 24px;
    margin-bottom: 20px;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    line-height: 0;
    margin: 0 auto;
    max-height: 25px;
}

When I work around with the img tag it's leaving 3 pixels to 2 pixels space from top. Now I decrease line-height, and it's working.

CSS:

    .frame {
        height: 25px;      /* Equals maximum image height */
        width: 160px;
        border: 1px solid red;
        margin: 1em 0;
        text-align: center;
        line-height: 22px;
        *:first-child+html line-height:24px; /* For Internet Explorer 7 */
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
        line-height: 0;    
        max-height: 25px;
        max-width: 160px;
    }
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .frame {
        line-height:20px; /* WebKit browsers */
    }

The line-height property is rendered differently in different browsers. So, we have to define different line-height property browsers.

Check this example: http://jsfiddle.net/sandeep/4be8t/11/

Check this example about line-height different in different browsers: input height differences in Firefox and Chrome

How to export a table dataframe in PySpark to csv?

You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,

df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')

Read more about the repartition function Read more about the save function

However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.

Read more on repartition vs coalesce functions.

How to fit a smooth curve to my data in R?

the qplot() function in the ggplot2 package is very simple to use and provides an elegant solution that includes confidence bands. For instance,

qplot(x,y, geom='smooth', span =0.5)

produces enter image description here

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Where is SQL Server Management Studio 2012?

I just ran into this problem. I had to open back the installation for SQL Server and click Installation -> New SQL server installation or add features to existing installation. Then when we follow the instruction until we reach feature selection, just check the SQL Management tools checkbox and continue.

I have no idea why this software is considered a feature and hidden like this. It should be a stand-alone software installation.

Tool for comparing 2 binary files in Windows

Total Commander also has a binary compare option: go to: File \\Compare by content

ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.

Conveniently map between enum and int / String

I'm not sure if it's the same in Java, but enum types in C are automatically mapped to integers as well so you can use either the type or integer to access it. Have you tried simply accessing it with integer yet?

How do I combine two lists into a dictionary in Python?

If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:

i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
    if x in d:
        d[x] = d[x] + y #or whatever your function needs to be to combine them
    else:
        d[x] = y

In that example, d == {'a': 3, 'c': 4, 'b': 8}

Android Studio doesn't see device

I'm sure this might be useful for someone out there. In my case I am running Android Studio in a mac and also trying Visual Studio Xamarin. Having both of them opened at the same time was creating this conflict. So closing Visual was enough.

div background color, to change onhover

There is no need to put anchor. To change style of div on hover then Change background color of div on hover.

<div class="div_hover"> Change div background color on hover</div>

In .css page

.div_hover { background-color: #FFFFFF; }

.div_hover:hover { background-color: #000000; }

How to subtract date/time in JavaScript?

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Test


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

Diff minutes or seconds is in same fashion.

javascript if number greater than number

Do this.

var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

cURL equivalent in Node.js?

Since looks like node-curl is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.

node-libcurl

Usage example:

var Curl = require( 'node-libcurl' ).Curl;

var curl = new Curl();

curl.setOpt( Curl.option.URL, 'www.google.com' );
curl.setOpt( 'FOLLOWLOCATION', true );

curl.on( 'end', function( statusCode, body, headers ) {

    console.info( statusCode );
    console.info( '---' );
    console.info( body.length );
    console.info( '---' );
    console.info( headers );
    console.info( '---' );
    console.info( this.getInfo( Curl.info.TOTAL_TIME ) );

    this.close();
});

curl.on( 'error', function( err, curlErrorCode ) {

    console.error( err.message );
    console.error( '---' );
    console.error( curlErrorCode );

    this.close();

});

curl.perform();

Perform is async, and there is no way to use it synchronous currently (and probably will never have).

It's still in alpha, but this is going to change soon, and help is appreciated.

Now it's possible to use Easy handle directly for sync requests, example:

var Easy = require( 'node-libcurl' ).Easy,
    Curl = require( 'node-libcurl' ).Curl,
    url = process.argv[2] || 'http://www.google.com',
    ret, ch;

ch = new Easy();

ch.setOpt( Curl.option.URL, url );

ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {

    console.log( buf );

    return size * nmemb;
});

ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {

    console.log( arguments );

    return size * nmemb;
});

// this call is sync!
ret = ch.perform();

ch.close();

console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );

Also, the project is stable now!

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

add a string prefix to each value in a string column using Pandas

df['col'] = 'str' + df['col'].astype(str)

Example:

>>> df = pd.DataFrame({'col':['a',0]})
>>> df
  col
0   a
1   0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
    col
0  stra
1  str0

How to get min, seconds and milliseconds from datetime.now() in python?

import datetime from datetime

now = datetime.now()

print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)

You can do the same with day & month etc.

Proper way to catch exception from JSON.parse

We can check error & 404 statusCode, and use try {} catch (err) {}.

You can try this :

_x000D_
_x000D_
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
    if (req.status == 404) {_x000D_
        console.log("404");_x000D_
        return false;_x000D_
    }_x000D_
_x000D_
    if (!(req.readyState == 4 && req.status == 200))_x000D_
        return false;_x000D_
_x000D_
    const json = (function(raw) {_x000D_
        try {_x000D_
            return JSON.parse(raw);_x000D_
        } catch (err) {_x000D_
            return false;_x000D_
        }_x000D_
    })(req.responseText);_x000D_
_x000D_
    if (!json)_x000D_
        return false;_x000D_
_x000D_
    document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
_x000D_
_x000D_

Read more :

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

How to make a <div> appear in front of regular text/tables

z-index only works on absolute or relatively positioned elements. I would use an outer div set to position relative. Set the div on top to position absolute to remove it from the flow of the document.

_x000D_
_x000D_
.wrapper {position:relative;width:500px;}_x000D_
_x000D_
.front {_x000D_
  border:3px solid #c00;_x000D_
  background-color:#fff;_x000D_
  width:300px;_x000D_
  position:absolute;_x000D_
  z-index:10;_x000D_
  top:30px;_x000D_
  left:50px;_x000D_
 }_x000D_
  _x000D_
.behind {background-color:#ccc;}
_x000D_
<div class="wrapper">_x000D_
    <p class="front">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>_x000D_
    <div class="behind">_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
        <table>_x000D_
            <thead>_x000D_
                <tr>_x000D_
                    <th>aaa</th>_x000D_
                    <th>bbb</th>_x000D_
                    <th>ccc</th>_x000D_
                    <th>ddd</th>_x000D_
                </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
                <tr>_x000D_
                    <td>111</td>_x000D_
                    <td>222</td>_x000D_
                    <td>333</td>_x000D_
                    <td>444</td>_x000D_
                </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
    </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

How to fill OpenCV image with one solid color?

Using the OpenCV C API with IplImage* img:

Use cvSet(): cvSet(img, CV_RGB(redVal,greenVal,blueVal));

Using the OpenCV C++ API with cv::Mat img, then use either:

cv::Mat::operator=(const Scalar& s) as in:

img = cv::Scalar(redVal,greenVal,blueVal);

or the more general, mask supporting, cv::Mat::setTo():

img.setTo(cv::Scalar(redVal,greenVal,blueVal));

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

How do I create variable variables?

Use globals()

You can actually assign variables to global scope dynamically, for instance, if you want 10 variables that can be accessed on a global scope i_1, i_2 ... i_10:

for i in range(10):
    globals()['i_{}'.format(i)] = 'a'

This will assign 'a' to all of these 10 variables, of course you can change the value dynamically as well. All of these variables can be accessed now like other globally declared variable:

>>> i_5
'a'

Aesthetics must either be length one, or the same length as the dataProblems

It is better to not subset the variables inside aes(), and instead transform your data:

df1 <- unstack(df,form = price~product)
df1$skew <- rep(letters[2:1],each = 4)

p1 <- ggplot(df1, aes(x=p1, y=p3, colour=factor(skew))) + 
        geom_point(size=2, shape=19)
p1

changing textbox border colour using javascript

Add an onchange event to your input element:

<input type="text" id="fName" value="" onchange="fName_Changed(this)" />

Javascript:

function fName_Changed(fName)
{
    fName.style.borderColor = (fName.value != 'correct text') ? "#FF0000"; : fName.style.borderColor="";
}

What are WSDL, SOAP and REST?

Example: In a simple terms if you have a web service of calculator.

WSDL: WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on.

SOAP: Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Why we use SOAP and WSDL: For platform independent data exchange.

EDIT: In a normal day to day life example:

WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL's.

Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.

SOAP: Then when we actually order the food based on the Menu's: Meaning we use proxy classes to call upon the service methods which is done using SOAP. :)

Most efficient way to append arrays in C#?

You might not need to concatenate end result into contiguous array. Instead, keep appending to the list as suggested by Jon. In the end you'll have a jagged array (well, almost rectangular in fact). When you need to access an element by index, use following indexing scheme:

double x = list[i / sampleSize][i % sampleSize];

Iteration over jagged array is also straightforward:

for (int iRow = 0; iRow < list.Length; ++iRow) {
  double[] row = list[iRow];
  for (int iCol = 0; iCol < row.Length; ++iCol) {
    double x = row[iCol];
  }
}

This saves you memory allocation and copying at expense of slightly slower element access. Whether this will be a net performance gain depends on size of your data, data access patterns and memory constraints.

How to convert LINQ query result to List?

You need to use the select new LINQ keyword to explicitly convert your tbcourseentity into the custom type course. Example of select new:

var q = from o in db.Orders
        where o.Products.ProductName.StartsWith("Asset") && 
              o.PaymentApproved == true
        select new { name   = o.Contacts.FirstName + " " +
                              o.Contacts.LastName, 
                     product = o.Products.ProductName, 
                     version = o.Products.Version + 
                              (o.Products.SubVersion * 0.1)
                   };

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

Why can't I define a static method in a Java interface?

To solve this : error: missing method body, or declare abstract static void main(String[] args);

interface I
{
    int x=20;
    void getValue();
    static void main(String[] args){};//Put curly braces 
}
class InterDemo implements I
{
    public void getValue()
    {
    System.out.println(x);
    }
    public static void main(String[] args)
    {
    InterDemo i=new InterDemo();
    i.getValue();   
    }

}

output : 20

Now we can use static method in interface

What is the syntax meaning of RAISERROR()

according to MSDN

RAISERROR ( { msg_id | msg_str | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]

16 would be the severity.
1 would be the state.

The error you get is because you have not properly supplied the required parameters for the RAISEERROR function.

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

Docker: Copying files from Docker container to host

In order to copy a file from a container to the host, you can use the command

docker cp <containerId>:/file/path/within/container /host/path/target

Here's an example:

$ sudo docker cp goofy_roentgen:/out_read.jpg .

Here goofy_roentgen is the container name I got from the following command:

$ sudo docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                            NAMES
1b4ad9311e93        bamos/openface      "/bin/bash"         33 minutes ago      Up 33 minutes       0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->9000/tcp   goofy_roentgen

You can also use (part of) the Container ID. The following command is equivalent to the first

$ sudo docker cp 1b4a:/out_read.jpg .

Parse JSON String into List<string>

Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();

var firstNames = list.Select(p => p.FirstName).ToList();
var lastNames = list.Select(p => p.LastName).ToList();

Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

CSS: background image on background color

Based on MDN Web Docs you can set multiple background using shorthand background property or individual properties except for background-color. In your case, you can do a trick using linear-gradient like this:

background-image: url('images/checked.png'), linear-gradient(to right, #6DB3F2, #6DB3F2);

The first item (image) in the parameter will be put on top. The second item (color background) will be put underneath the first. You can also set other properties individually. For example, to set the image size and position.

background-size: 30px 30px;
background-position: bottom right;
background-repeat: no-repeat;

Benefit of this method is you can implement it for other cases easily, for example, you want to make the blue color overlaying the image with certain opacity.

background-image: linear-gradient(to right, rgba(109, 179, 242, .6), rgba(109, 179, 242, .6)), url('images/checked.png');
background-size: cover, contain;
background-position: center, right bottom;
background-repeat: no-repeat, no-repeat;

Individual property parameters are set respectively. Because the image is put underneath the color overlay, its property parameters are also placed after color overlay parameters.

Mapping object to dictionary and vice versa

Using some reflection and generics in two extension methods you can achieve that.

Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:

public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
        where T : class, new()
    {
            var someObject = new T();
            var someObjectType = someObject.GetType();

            foreach (var item in source)
            {
                someObjectType
                         .GetProperty(item.Key)
                         .SetValue(someObject, item.Value, null);
            }

            return someObject;
    }

    public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

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

    public int Prop2
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        dictionary.Add("Prop1", "hello world!");
        dictionary.Add("Prop2", 3893);
        A someObject = dictionary.ToObject<A>();

        IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
    }
}

SQL Server add auto increment primary key to existing table

No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

and then you can make it the primary key:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

or if you prefer to do all in one step:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

Save attachments to a folder and rename them

Public Sub Extract_Outlook_Email_Attachments()

Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String


saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO

If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
    Set outApp = New Outlook.Application
    OutlookOpened = True
End If
On Error GoTo 0

If outApp Is Nothing Then
    MsgBox "Cannot start Outlook.", vbExclamation
    Exit Sub
End If

Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)

If Not outFolder Is Nothing Then
    For Each outItem In outFolder.Items
        If outItem.Class = Outlook.OlObjectClass.olMail Then
            Set outMailItem = outItem
                If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
                    For Each outAttachment In outMailItem.Attachments
                    outAttachment.SaveAsFile saveFolder & outAttachment.filename

                    Set outAttachment = Nothing

                    Next
                End If
        End If
    Next
End If

If OutlookOpened Then outApp.Quit

Set outApp = Nothing

End Sub

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

How do I determine file encoding in OS X?

In Mac OS X the command file -I (capital i) will give you the proper character set so long as the file you are testing contains characters outside of the basic ASCII range.

For instance if you go into Terminal and use vi to create a file eg. vi test.txt then insert some characters and include an accented character (try ALT-e followed by e) then save the file.

They type file -I text.txt and you should get a result like this:

test.txt: text/plain; charset=utf-8

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

XML parsing of a variable string in JavaScript

Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5

jQuery.parseXML( data ) Returns: XMLDocument

Copy files without overwrite

For %F In ("C:\From\*.*") Do If Not Exist "C:\To\%~nxF" Copy "%F" "C:\To\%~nxF"

How to get element by innerText

Using the most modern syntax available at the moment, it can be done very cleanly like this:

for (const a of document.querySelectorAll("a")) {
  if (a.textContent.includes("your search term")) {
    console.log(a.textContent)
  }
}

Or with a separate filter:

[...document.querySelectorAll("a")]
   .filter(a => a.textContent.includes("your search term"))
   .forEach(a => console.log(a.textContent))

Naturally, legacy browsers won't handle this, but you can use a transpiler if legacy support is needed.

How do I split a string into an array of characters?

A string in Javascript is already a character array.

You can simply access any character in the array as you would any other array.

var s = "overpopulation";
alert(s[0]) // alerts o.

UPDATE

As is pointed out in the comments below, the above method for accessing a character in a string is part of ECMAScript 5 which certain browsers may not conform to.

An alternative method you can use is charAt(index).

var s = "overpopulation";
    alert(s.charAt(0)) // alerts o.

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

The Rand() function will generate the same random number, if used in a table SELECT query. Same applies if you use a seed to the Rand function. An alternative way to do it, is using this:

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [RandomNumber]

Got the information from here, which explains the problem very well.

Rewrite all requests to index.php with nginx

1 unless file exists will rewrite to index.php

Add the following to your location ~ \.php$

try_files = $uri @missing;

this will first try to serve the file and if it's not found it will move to the @missing part. so also add the following to your config (outside the location block), this will redirect to your index page

location @missing {
    rewrite ^ $scheme://$host/index.php permanent;
}

2 on the urls you never see the file extension (.php)

to remove the php extension read the following: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension/

and the example configuration from the link:

location / {
    set $page_to_view "/index.php";
    try_files $uri $uri/ @rewrites;
    root   /var/www/site;
    index  index.php index.html index.htm;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}

# rewrites
location @rewrites {
    if ($uri ~* ^/([a-z]+)$) {
        set $page_to_view "/$1.php";
        rewrite ^/([a-z]+)$ /$1.php last;
    }
}

Fixed height and width for bootstrap carousel

set style="height:300px !important;" and "imgBanner" for img tag.

<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">

then if you want responsive image, so you can use jquery as:

$.(function(){
   $(window).resize(respWhenResize);
   respWhenResize();
 })



respWhenResize(){
 
       if (pagesize < 578) {
         $('.imgBanner').css('height','200px')
        } else if (pagesize > 578 ) {
            $('.imgBanner').css('height','300px')
        }
     }

How can I update the current line in a C# Windows Console App?

The SetCursorPosition method works in multi-threading scenario, where the other two methods don't

How to get JSON from URL in JavaScript?

If you want to do it in plain javascript, you can define a function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
    xhr.send();
};

And use it like this:

getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback',
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your query count: ' + data.query.count);
  }
});

Note that data is an object, so you can access its attributes without having to parse it.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I am facing the same problem. The problem I found that I have a library project, in that project's manifest file, there is no targetSdkVersion property. I have added that property under (uses-sdk) tag. Then clean my project. Now my app runs normally.

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Capture characters from standard input without waiting for enter to be pressed

I always wanted a loop to read my input without pressing return key. this worked for me.

#include<stdio.h>
 main()
 {
   char ch;
    system("stty raw");//seting the terminal in raw mode
    while(1)
     {
     ch=getchar();
      if(ch=='~'){          //terminate or come out of raw mode on "~" pressed
      system("stty cooked");
     //while(1);//you may still run the code 
     exit(0); //or terminate
     }
       printf("you pressed %c\n ",ch);  //write rest code here
      }

    }

How can I completely uninstall nodejs, npm and node in Ubuntu

It is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later this creates problems when we reconfigure another version of NodeJS and its modules.

To remove the files, run the following commands:

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d
rm -rf ~/.npm
rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf /opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

I have posted a step by step guide with commands on my blog: AMCOS IT Support For Windows and Linux: To completely uninstall node js from Ubuntu.

How to add manifest permission to an application?

I am late but i want to complete the answer.

An permission is added in manifest.xml like

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

This is enough for standard permissions where no permission is prompted to the user. However, it is not enough to add permission only to manifest if it is a dangerous permission. See android doc. Like Camera, Storage permissions.

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

You will need to ask permission from user. I use RxPermission library that is widely used library for asking permission. Because it is long code which we have to write to ask permission.

RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity instance // Must be done during an initialization phase like onCreate
rxPermissions
    .request(Manifest.permission.CAMERA)
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });

Add this library to your app

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

Header and footer in CodeIgniter

Yes.

Create a file called template.php in your views folder.

The contents of template.php:

$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');

Then from your controller you can do something like:

$d['v'] = 'body';
$this->load->view('template', $d);

This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:

Consider if you create a view called init.php that contains the single line:

$this->load->view('html');

Now create the view html.php with contents:

<!DOCTYPE html>
<html lang="en">
    <? $this->load->view('head'); ?>
    <? $this->load->view('body'); ?>
</html>

Now create a view head.php with contents:

<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>

And a body.php view with contents:

<body>
    <div id="mainWrap">
        <? $this->load->view('header'); ?>
        <? //FINALLY LOAD THE VIEW!!! ?>
        <? $this->load->view($v); ?>
        <? $this->load->view('footer'); ?>
    </div>
</body>

And create header.php and footer.php views as appropriate.

Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html> and <body> tags, your headers and footers will be loaded in.

$d['v'] = 'fooview'
$this->load->view('init', $d);

Invalid attempt to read when no data is present

I used the code below and it worked for me.

String email="";
    SqlDataReader reader=cmd.ExecuteReader();
    if(reader.Read()){
        email=reader["Email"].ToString();
    }

String To=email;

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

How to create a file in Ruby

Try

File.open("out.txt", "w") do |f|     
  f.write(data_you_want_to_write)   
end

without using the

File.new "out.txt"

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

Convert alphabet letters to number in Python

You can map the alphabet to a list and return the index of each one as per the below :

import string

alphabet=string.ascii_lowercase
#alphabet='abcdefghijklmnopqrstuvwxyz'

#Get the character index , ex: e  
print(chars.find('e'))
#This will return 4

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

You seems to be missing implementation for interface UserDao. If you look at the exception closely it says

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:

The way @Autowired works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.

Hope that helps.

The type is defined in an assembly that is not referenced, how to find the cause?

one of main reason can be the property of DLL you must before do any thing to check the specific version property if it true make it false

Reason: maybe the source code joined with other (old)version when you build it , but this Library upgraded with new update the version now different in the Assembly Cash and your application forbidden to get new DLL ,and after disable specific version property your applacaten will be free to get the new version of DLL references

How to trigger event in JavaScript?

You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.

Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:

var event; // The custom event that will be created
if(document.createEvent){
    event = document.createEvent("HTMLEvents");
    event.initEvent("dataavailable", true, true);
    event.eventName = "dataavailable";
    element.dispatchEvent(event);
} else {
    event = document.createEventObject();
    event.eventName = "dataavailable";
    event.eventType = "dataavailable";
    element.fireEvent("on" + event.eventType, event);
}

jQuery check if <input> exists and has a value

The input won't have a value if it doesn't exist. Try this...

if($('.input1').val())

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

jQuery Mobile how to check if button is disabled?

To see which options have been set on a jQuery UI button use:

$("#deliveryNext").button('option')

To check if it's disabled you can use:

$("#deliveryNext").button('option', 'disabled')

Unfortunately, if the button hasn't been explicitly enabled or disabled before, the above call will just return the button object itself so you'll need to first check to see if the options object contains the 'disabled' property.

So to determine if a button is disabled you can do it like this:

$("#deliveryNext").button('option').disabled != undefined && $("#deliveryNext").button('option', 'disabled')

How do I use sudo to redirect output to a location I don't have permission to write to?

Someone here has just suggested sudoing tee:

sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null

This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.

Can a class member function template be virtual?

While an older question that has been answered by many I believe a succinct method, not so different from the others posted, is to use a minor macro to help ease the duplication of class declarations.

// abstract.h

// Simply define the types that each concrete class will use
#define IMPL_RENDER() \
    void render(int a, char *b) override { render_internal<char>(a, b); }   \
    void render(int a, short *b) override { render_internal<short>(a, b); } \
    // ...

class Renderable
{
public:
    // Then, once for each on the abstract
    virtual void render(int a, char *a) = 0;
    virtual void render(int a, short *b) = 0;
    // ...
};

So now, to implement our subclass:

class Box : public Renderable
{
public:
    IMPL_RENDER() // Builds the functions we want

private:
    template<typename T>
    void render_internal(int a, T *b); // One spot for our logic
};

The benefit here is that, when adding a newly supported type, it can all be done from the abstract header and forego possibly rectifying it in multiple source/header files.

Display SQL query results in php

You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.

For getting the result you have to add a lil things in your script like

require_once('db.php');  
 $sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) ORDER BY idM1O LIMIT 1";

 $result = mysql_query($sql);
 //echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
}

This will give you result;

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

In practice, you will often want to act differently depending on whether a variable is an Array or a Hash, not just mere tell. In this situation, an elegant idiom is the following:

case item
  when Array
   #do something
  when Hash
   #do something else
end

Note that you don't call the .class method on item.

Is there a way to create and run javascript in Chrome?

How to create a Javascript Bookmark in Chrome:

You can use a Javascript bookmark: https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/. Just create a bookmark to look like this:

Ex:

Name:

Test javascript bookmark in Chrome

URL:

javascript:alert('Hello world!');

Just precede the URL with javascript:, followed by your Javascript code. No space after the colon is required.

Here's how it looks as I'm typing it in:

enter image description here

Now save and then click on your newly-created Javascript bookmark, and you'll see this:

enter image description here

You can do multi-line scripts too. If you include any comments, however, be sure to use the C-style multi-line comments ONLY (/* comment */), and NOT the C++-style single-line comments (// comment), as they will interfere. Here's an example:

URL:

javascript:

/* This is my javascript demo */

function multiply(a, b) 
{
    return a * b;
}

var a = 1.4108;
var b = 3.7654;
var result = multiply(a, b);
alert('The result of ' + a + ' x ' + b + ' = ' + result.toFixed(4));

And here's what it looks like as you edit the bookmark, after copying and pasting the above multi-line script into the URL field for the bookmark:

enter image description here.

And here's the output when you click on it:

enter image description here

References:

  1. https://superuser.com/questions/192437/case-sensitive-searches-in-google-chrome/582280#582280
  2. https://gist.github.com/borisdiakur/9f9d751b4c9cf5acafa2
  3. Google search for "chrome javascript() in bookmark"
  4. https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
  5. https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
  6. https://javascript.info/hello-world
  7. JavaScript equivalent to printf/String.Format

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

For me Fake Sendmail works.

What to do:

1) Edit C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

2) Edit php.ini and set sendmail_path

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

That's it. Now you can test a mail.

ITextSharp HTML to PDF?

I would one-up'd mightymada's answer if I had the reputation - I just implemented an asp.net HTML to PDF solution using Pechkin. results are wonderful.

There is a nuget package for Pechkin, but as the above poster mentions in his blog (http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - I hope she doesn't mind me reposting it), there's a memory leak that's been fixed in this branch:

https://github.com/tuespetre/Pechkin

The above blog has specific instructions for how to include this package (it's a 32 bit dll and requires .net4). here is my code. The incoming HTML is actually assembled via HTML Agility pack (I'm automating invoice generations):

public static byte[] PechkinPdf(string html)
{
  //Transform the HTML into PDF
  var pechkin = Factory.Create(new GlobalConfig());
  var pdf = pechkin.Convert(new ObjectConfig()
                          .SetLoadImages(true).SetZoomFactor(1.5)
                          .SetPrintBackground(true)
                          .SetScreenMediaType(true)
                          .SetCreateExternalLinks(true), html);

  //Return the PDF file
  return pdf;
}

again, thank you mightymada - your answer is fantastic.

how to implement a pop up dialog box in iOS

Here is C# version in Xamarin.iOS

var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.