Programs & Examples On #Activemq cpp

Apache ActiveMQ-CPP provides a rich C++ client for Apache ActiveMQ the most popular and powerful open source message broker

How can I convert an integer to a hexadecimal string in C?

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

char* dechex (int dec);

This will use calloc() to to return a pointer to an hexadecimal string, this way the quantity of memory used is optimized, so don't forget to use free()

Here the link on github : https://github.com/kevmuret/libhex/

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

Setting Margin Properties in code

One would guess that (and my WPF is a little rusty right now) that Margin takes an object and cannot be directly changed.

e.g

MyControl.Margin = new Margin(10,0,0,0);

Can't import javax.servlet.annotation.WebServlet

Go to

window->Preference->server->runtime environment

then choose your tomcat server. If the error is still there, then

right click project->properties>Targeted Runtimes

then check the server

How can a web application send push notifications to iOS devices?

Google Chrome now supports the W3C standard for push notifications.

http://www.w3.org/TR/push-api/

jQuery get the id/value of <li> element after click function

you can get the value of the respective li by using this method after click

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>show the value of li</title>
    <link rel="stylesheet"  href="pathnameofcss">
</head>
<body>

    <div id="user"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul id="pageno">
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjs" type="text/javascript"></script>
</body>
</html>

JS:-

$("li").click(function ()
{       
var a = $(this).attr("value");

$("#user").html(a);//here the clicked value is showing in the div name user
console.log(a);//here the clicked value is showing in the console
});

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

detect back button click in browser

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

lvalue required as left operand of assignment error when using C++

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

You cannot use:

10 = 20;

since 10 does not evaluate to an lvalue.

You can use:

int i;
i = 20;

since i does evaluate to an lvalue.

You cannot use:

int i;
i + 1 = 20;

since i + 1 does not evaluate to an lvalue.

In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

p + 1 = p;

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

How to update the value stored in Dictionary in C#?

Use LINQ: Access to dictionary for the key and change the value

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

Auto height of div

make sure the content inside your div ended with clear:both style

Trying to embed newline in a variable in bash

sed solution:

echo "a b c" | sed 's/ \+/\n/g'

Result:

a
b
c

Process all arguments except the first one (in a bash script)

Working in bash 4 or higher version:

#!/bin/bash
echo "$0";         #"bash"
bash --version;    #"GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)"

In function:

echo $@;              #"p1" "p2" "p3" "p4" "p5"
echo ${@: 0};  #"bash" "p1" "p2" "p3" "p4" "p5"
echo ${@: 1};         #"p1" "p2" "p3" "p4" "p5"
echo ${@: 2};              #"p2" "p3" "p4" "p5"
echo ${@: 2:1};            #"p2"
echo ${@: 2:2};            #"p2" "p3"
echo ${@: -2};                       #"p4" "p5"
echo ${@: -2:1};                     #"p4"

Notice the space between ':' and '-', otherwise it means different:

${var:-word} If var is null or unset,
word is substituted for var. The value of var does not change.

${var:+word} If var is set,
word is substituted for var. The value of var does not change.

Which is described in:Unix / Linux - Shell Substitution

Ship an application with a database

I wrote a library to simplify this process.

dataBase = new DataBase.Builder(context, "myDb").
//        setAssetsPath(). // default "databases"
//        setDatabaseErrorHandler().
//        setCursorFactory().
//        setUpgradeCallback()
//        setVersion(). // default 1
build();

It will create a dataBase from assets/databases/myDb.db file. In addition you will get all those functionality:

  • Load database from file
  • Synchronized access to the database
  • Using sqlite-android by requery, Android specific distribution of the latest versions of SQLite.

Clone it from github.

glob exclude pattern

If the position of the character isn't important, that is for example to exclude manifests files (wherever it is found _) with glob and re - regular expression operations, you can use:

import glob
import re
for file in glob.glob('*.txt'):
    if re.match(r'.*\_.*', file):
        continue
    else:
        print(file)

Or with in a more elegant way - list comprehension

filtered = [f for f in glob.glob('*.txt') if not re.match(r'.*\_.*', f)]

for mach in filtered:
    print(mach)

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

Bootstrap: add margin/padding space between columns

For those looking to control the space between a dynamic number of columns, try:

<div class="row no-gutters">
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <!-- etc. -->
</div>

CSS:

.col:not(:last-child) .inner {
  margin: 2px; // Or whatever you want your spacing to be
}

Execute PHP scripts within Node.js web server

You can try to implement direct link node -> fastcgi -> php. In the previous answer, nginx serves php requests using http->fastcgi serialisation->unix socket->php and node requests as http->nginx reverse proxy->node http server.

It seems that node-fastcgi paser is useable at the moment, but only as a node fastcgi backend. You need to adopt it to use as a fastcgi client to php fastcgi server.

grabbing first row in a mysql query only

You can get the total number of rows containing a specific name using:

SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'

Given the count, you can now get the nth row using:

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1

Where 1 <= n <= COUNT(*) from the first query.

Example:

getting the 3rd row

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

regular expression for finding 'href' value of a <a> link

Try this :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var res = Find(html);
        }

        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }

        public struct LinkItem
        {
            public string Href;
            public string Text;

            public override string ToString()
            {
                return Href + "\n\t" + Text;
            }
        }

    }  

Input:

  string html = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> 2.<a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a> "; 

Result:

[0] = {www.aaa.xx/xx.zz?id=xxxx&name=xxxx}
[1] = {http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx}

C# Scraping HTML Links

Scraping HTML extracts important page elements. It has many legal uses for webmasters and ASP.NET developers. With the Regex type and WebClient, we implement screen scraping for HTML.

Edited

Another easy way:you can use a web browser control for getting href from tag a,like this:(see my example)

 public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<a href=\"www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"http://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"https://www.aaa.xx/xx.zz?id=xxxx&name=xxxx\" ....></a><a href=\"www.aaa.xx/xx.zz/xxx\" ....></a>";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            List<string> href = new List<string>();
            foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("a"))
            {
                href.Add(el.GetAttribute("href"));
            }
        }

Shell - How to find directory of some command?

Like this:

which lshw

To see all of the commands that match in your path:

which -a lshw 

Is there a Wikipedia API?

JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia

http://code.google.com/p/jwpl/

When to choose mouseover() and hover() function?

From the offical docs: (http://api.jquery.com/hover/)

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

How to get the current directory in a C program?

Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory() function:

DWORD WINAPI GetCurrentDirectory(
  _In_  DWORD  nBufferLength,
  _Out_ LPTSTR lpBuffer
);

These answers apply to both C and C++ code.

Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.

Deleting all pending tasks in celery / rabbitmq

celery 4+ celery purge command to purge all configured task queues

celery -A *APPNAME* purge

programmatically:

from proj.celery import app
app.control.purge()

all pending task will be purged. Reference: celerydoc

Check line for unprintable characters while reading text file

The answer by @T.J.Crowder is Java 6 - in java 7 the valid answer is the one by @McIntosh - though its use of Charset for name for UTF -8 is discouraged:

List<String> lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
    StandardCharsets.UTF_8);
for(String line: lines){ /* DO */ }

Reminds a lot of the Guava way posted by Skeet above - and of course same caveats apply. That is, for big files (Java 7):

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {}

How to get today's Date?

Code To Get Today's date in any specific Format

You can define the desired format in SimpleDateFormat instance to get the date in that specific formate

 DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        String todaysdate = dateFormat.format(date);
         System.out.println("Today's date : " + todaysdate);

Follow below links to see the valid date format combination.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.

For Example :

Today date : 11/27/2018

xdayFromTodaysDate = 2 to get date as 11/29/2018

xdayFromTodaysDate = -2 to get date as 11/25/2018

  public String getAniversaryDate(int xdayFromTodaysDate ){

        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
        date = cal.getTime();
        String aniversaryDate = dateFormat.format(date);
        LOGGER.info("Today's date : " + todaysdate);
          return aniversaryDate;

    }

CODE : To get x days ahead or Previous from a Given date

  public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){


        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        try {
            Date date = dateFormat.parse(givendate);
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
            date = cal.getTime();
            String aniversaryDate = dateFormat.format(date);
            LOGGER.info("aniversaryDate : " + aniversaryDate);
            return aniversaryDate;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }

jQuery ajax request being block because Cross-Origin

There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.

The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.

Javascript swap array elements

Flow

not inplace solution

let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);

_x000D_
_x000D_
let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];
let b= swap(a,3,5);

console.log(a,"\n", b);
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
_x000D_
_x000D_
_x000D_

and inplace solution

_x000D_
_x000D_
let swap= (arr,i,j)=> {let t=arr[i]; arr[i]=arr[j]; arr[j]=t; return arr}


// test index: 3<->5 (= 'f'<->'d')
let a= ["a","b","c","d","e","f","g"];

console.log( swap(a,3,5) )
console.log('Example Flow:', swap(a,3,5).reverse().join('-') );
_x000D_
_x000D_
_x000D_

In this solutions we use "flow pattern" which means that swap function returns array as result - this allow to easily continue processing using dot . (like reverse and join in snippets)

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

How to catch and print the full exception traceback without halting/exiting the program?

How to print the full traceback without halting the program?

When you don't want to halt your program on an error, you need to handle that error with a try/except:

try:
    do_something_that_might_error()
except Exception as error:
    handle_the_error(error)

To extract the full traceback, we'll use the traceback module from the standard library:

import traceback

And to create a decently complicated stacktrace to demonstrate that we get the full stacktrace:

def raise_error():
    raise RuntimeError('something bad happened!')

def do_something_that_might_error():
    raise_error()

Printing

To print the full traceback, use the traceback.print_exc method:

try:
    do_something_that_might_error()
except Exception as error:
    traceback.print_exc()

Which prints:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Better than printing, logging:

However, a best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

In which case, you'll want the logger.exception function instead:

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

Which logs:

ERROR:__main__:something bad happened!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Or perhaps you just want the string, in which case, you'll want the traceback.format_exc function instead:

try:
    do_something_that_might_error()
except Exception as error:
    logger.debug(traceback.format_exc())

Which logs:

DEBUG:__main__:Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Conclusion

And for all three options, we see we get the same output as when we have an error:

>>> do_something_that_might_error()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Which to use

Performance concerns aren't important here as IO usually dominates. I'd prefer, since it does precisely what's being requested in a forward compatible way:

logger.exception(error)

Logging levels and outputs can be adjusted, making it easy to turn off without touching the code. And usually doing what's directly needed is the most efficient way to do it.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Use this method it under your email service it can attach any email body and attachments to Microsoft outlook

using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later

 try {
                    var officeType = Type.GetTypeFromProgID("Outlook.Application");
    
                    if(officeType == null) {//outlook is not installed
                        return new PdfErrorResponse {
                            ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                        };
                    } else {
                        // Outlook is installed.    
                        // Continue your work.
                        Outlook.Application objApp = new Outlook.Application();
                        Outlook.MailItem mail = null;
                        mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
                        //The CreateItem method returns an object which has to be typecast to MailItem 
                        //before using it.
                        mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
                        //The parameters are explained below
                        mail.To = recipientEmailAddress;
                        //mail.CC = "[email protected]";//All the mail lists have to be separated by the ';'
    
                        //To send email:
                        //mail.Send();
                        //To show email window
                        await Task.Run(() => mail.Display());
                    }
    
                } catch(System.Exception) {
                    return new PdfErrorResponse {
                        ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                    };
                }

Proxy setting for R

Inspired by all the responses related on the internet, finally I've found the solution to correctly configure the Proxy for R and Rstudio.

There are several steps to follow, perhaps some of the steps are useless, but the combination works!

  1. Add environment variables http_proxy and https_proxy with proxy details.

    variable name: http_proxy
    variable value: https://user_id:password@your_proxy:your_port/
    
    variable name: https_proxy
    variable value: https:// user_id:password@your_proxy:your_port
    
  2. If you start R from a desktop icon, you can add the --internet flag to the target line (right click -> Properties)

    e.g."C:\Program Files\R\R-2.8.1\bin\Rgui.exe" --internet2

  3. For RStudio just you have to do this:

    Firstly, open RStudio like always, select from the top menu:

    Tools-Global Options-Packages

    Uncheck the option: Use Internet Explorer library/proxy for HTTP

  4. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents.

    Note that: if it does not exist you can create it just by writing this command in R:

    file.edit('~/.Renviron')
    

    Then add these six lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy = https:// user_id:password@your_proxy:your_port
    
    http_proxy_user = user_id:password
    
    https_proxy = https:// user_id:password0@your_proxy:your_port
    
    https_proxy_user = user_id:password
    
    ftp_proxy = user_id:password@your_proxy:your_port
    
  5. Restart R. Type the following commands in R to assure that the configuration above works well:

    Sys.getenv("http_proxy")
    
    Sys.getenv("http_proxy_user")
    
    Sys.getenv("https_proxy")
    
    Sys.getenv("https_proxy_user")
    
    Sys.getenv("ftp_proxy")
    
  6. Now you can install the packages as you want by using the command like:

    install.packages("mlr",method="libcurl")
    

    It's important to add method="libcurl", otherwise it won't work.

How to test an SQL Update statement before running it?

I know this is a repeat of other answers, but it has some emotional support to take the extra step for testing update :D

For testing update, hash # is your friend.

If you have an update statement like:

UPDATE 
wp_history
SET history_by="admin"
WHERE
history_ip LIKE '123%'

You hash UPDATE and SET out for testing, then hash them back in:

SELECT * FROM
#UPDATE
wp_history
#SET history_by="admin"
WHERE
history_ip LIKE '123%'

It works for simple statements.

An additional practically mandatory solution is, to get a copy (backup duplicate), whenever using update on a production table. Phpmyadmin > operations > copy: table_yearmonthday. It just takes a few seconds for tables <=100M.

Axios having CORS issue

This work out for me :

in javascript :

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order
          }).then(function (response) {
            console.log(response.data);
          });

and in the backend (.net core) : in startup:

 #region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

and in controller before action

[EnableCors("AllowOrigin")]

Get user location by IP address

Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.

The code below requires the Json.NET package.

public static string GetUserCountryByIp(string ip)
{
    IpInfo ipInfo = new IpInfo();
    try
    {
        string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
        ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
        ipInfo.Country = myRI1.EnglishName;
    }
    catch (Exception)
    {
        ipInfo.Country = null;
    }
    
    return ipInfo.Country;
}

And the IpInfo Class I used:

public class IpInfo
{
    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

Android Min SDK Version vs. Target SDK Version

When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.

A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.

Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.

If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).

As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.

In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive

@TargetApi(nn)

tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:

@TargetApi(11)
    public void refreshActionBarIfApi11OrHigher() {
      //If the API is 11 or higher, set up the actionBar and display it
      if(Build.VERSION.SDK_INT >= 11) {
        //ActionBar only exists at API level 11 or higher
        ActionBar actionBar = getActionBar();

        //This should cause onPrepareOptionsMenu() to be called.
        // In versions of the API prior to 11, this only occurred when the user pressed 
        // the dedicated menu button, but at level 11 and above, the action bar is 
        // typically displayed continuously and so you will need to call this
        // each time the options on your menu change.
        invalidateOptionsMenu();

        //Show the bar
        actionBar.show();
    }
}

You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.

An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.

minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.

An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

this is the right answer, I tried, and the value passed is the values separated by ","

How do I use the JAVA_OPTS environment variable?

Actually, you can, even though accepted answer saying that you can't.

There is a _JAVA_OPTIONS environment variable, more about it here

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

Configure Flask dev server to be visible across the network

Go to your project path on CMD(command Prompt) and execute the following command:-

set FLASK_APP=ABC.py

SET FLASK_ENV=development

flask run -h [yourIP] -p 8080

you will get following o/p on CMD:-

  • Serving Flask app "expirement.py" (lazy loading)
    • Environment: development
    • Debug mode: on
    • Restarting with stat
    • Debugger is active!
    • Debugger PIN: 199-519-700
    • Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Now you can access your flask app on another machine using http://[yourIP]:8080/ url

Run a task every x-minutes with Windows Task Scheduler

Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"

In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.

I thought doing an "Export" and editing the XML from: PT30M to PT2M

and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that

My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)

Integer value in TextView

tv.setText(Integer.toString(intValue))

Error handling in getJSON calls

Why not

getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
    // ...
});

function getJSON(url,params,callback) {
    return $.getJSON(url,params,callback)
        .fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
            console.dir(jqXMLHttpRequest);
            alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
        })
}

??

For details on the used .fail() method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR

Since the jqXHR is returned by the function, a chaining like

$.when(getJSON(...)).then(function() { ... });

is possible.

Is the sizeof(some pointer) always equal to four?

No, the size of a pointer may vary depending on the architecture. There are numerous exceptions.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

How do you change the document font in LaTeX?

I found the solution thanks to the link in Vincent's answer.

 \renewcommand{\familydefault}{\sfdefault}

This changes the default font family to sans-serif.

Change default timeout for mocha

Just adding to the correct answer you can set the timeout with the arrow function like this:

it('Some test', () => {

}).timeout(5000)

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

File permissions are restrictive on the Postgres db owned by the Mac OS. These permissions are reset after reboot, or restart of Postgres: e.g. serveradmin start postgres.

So, temporarily reset the permissions or ownership:

sudo chmod o+rwx /var/pgsql_socket/.s.PGSQL.5432
sudo chown "webUser"  /var/pgsql_socket/.s.PGSQL.5432

Permissions resetting is not secure, so install a version of the db that you own for a solution.

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

How to debug external class library projects in visual studio?

[according to Martin Beckett, the guy who send me this answer ]

You can debug into an external library.

In the project settings tab look for 'visual studio directories' in the 'source code' field include the path to the openCV sources. Then make sure that the .pdb files for each of the debug dll are in the same directory as the dll.

How do I send a JSON string in a POST request in Go

In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)

So, in the end your code will become like follow:

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)
    request := gorequest.New()
    titleList := []string{"title1", "title2", "title3"}
    for _, title := range titleList {
        resp, body, errs := request.Post(url).
            Set("X-Custom-Header", "myvalue").
            Send(`{"title":"` + title + `"}`).
            End()
        if errs != nil {
            fmt.Println(errs)
            os.Exit(1)
        }
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        fmt.Println("response Body:", body)
    }
}

This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.

JavaScript: Is there a way to get Chrome to break on all errors?

This is now supported in Chrome by the "Pause on all exceptions" button.

To enable it:

  • Go to the "Sources" tab in Chrome Developer Tools
  • Click the "Pause" button at the bottom of the window to switch to "Pause on all exceptions mode".

Note that this button has multiple states. Keep clicking the button to switch between

  • "Pause on all exceptions" - the button is colored light blue
  • "Pause on uncaught exceptions", the button is colored purple.
  • "Dont pause on exceptions" - the button is colored gray

How can I export a GridView.DataSource to a datatable or dataset?

This comes in late but was quite helpful. I am Just posting for future reference

DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

Exact difference between CharSequence and String in java

I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)

java.lang.String is an implementation of this interface...

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

Validate phone number using angular js

use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also. on npm: https://www.npmjs.com/package/ng-intl-tel-input

more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

You can just use Lombok with access level PRIVATE in @NoArgsConstructor annotation to avoid unnecessary initialization.

@NoArgsConstructor(access = AccessLevel.PRIVATE)

public class FilePathHelper {

// your code

}

html vertical align the text inside input type button

I had a button where the background-image had a shadow below it so the text alignment was off from the top. Changing the line-height wouldn't help. I added padding-bottom to it and it worked.

So what you have to do is determine the line-height you want to play with. So, for example, if I have a button who's height is truly 90px but I want the line-height to be 80px I would have something like this:

input[type=butotn].mybutton{
    background: url(my/image.png) no-repeat center top; /*Image is 90px x 150px*/
    width: 150px;
    height: 80px; /*shadow at the bottom is 10px (90px-10px)*/
    padding-bottom: 10px; /*the padding will make up for the lost height while maintaining the line-height to the proper height */

}

I hope this helps.

How to parse/format dates with LocalDateTime? (Java 8)

You can also use LocalDate.parse() or LocalDateTime.parse() on a String without providing it with a pattern, if the String is in ISO-8601 format.

for example,

String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);

String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);

Output,

Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30

and use DateTimeFormatter only if you have to deal with other date patterns.

For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:

DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);

Output

04 Aug 2015 parses to 2015-08-04

also remember that the DateTimeFormatter object is bidirectional; it can both parse input and format output.

String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));

Output

2015-08-04 formats as 04 Aug 2015

(see complete list of Patterns for Formatting and Parsing DateFormatter)

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

   p       pad next                    pad modifier      1

   '       escape for text             delimiter
   ''      single quote                literal           '
   [       optional section start
   ]       optional section end
   #       reserved for future use
   {       reserved for future use
   }       reserved for future use

Set size of HTML page and browser window

You could use width: 100%; in your css.

How to overlay density plots in R?

Whenever there are issues of mismatched axis limits, the right tool in base graphics is to use matplot. The key is to leverage the from and to arguments to density.default. It's a bit hackish, but fairly straightforward to roll yourself:

set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)

xrng = range(x1, x2)

#force the x values at which density is
#  evaluated to be the same between 'density'
#  calls by specifying 'from' and 'to'
#  (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])

matplot(kde1$x, cbind(kde1$y, kde2$y))

A plot depicting the output of the call to matplot. Two curves are observed, one red, the other black; the black curve extends higher than the red, while the red curve is the "fatter".

Add bells and whistles as desired (matplot accepts all the standard plot/par arguments, e.g. lty, type, col, lwd, ...).

SET NOCOUNT ON usage

Ok now I've done my research, here is the deal:

In TDS protocol, SET NOCOUNT ON only saves 9-bytes per query while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that 123 row(s) affected was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called DONE_IN_PROC embedded in the response. It's not a separate network packet so no roundtrips are wasted.

I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.

Here is a very detailed analysis about insignificance of SET NOCOUNT setting: http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/

Check if URL has certain string with PHP

$url = " www.domain.com/car/audi/";
if (strpos($url, "car")!==false){
    echo "Car here";
}
else {
   echo "No car here :(";
}

See strpos manual

cd into directory without having permission

You've got several options:

  • Use a different user account, one with execute permissions on that directory.
  • Change the permissions on the directory to allow your user account execute permissions.
    • Either use chmod(1) to change the permissions or
    • Use the setfacl(1) command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl option; see mount(8) and fstab(5) for details on the mount parameter.)

It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?

Filter Pyspark dataframe column with None value

You can use Column.isNull / Column.isNotNull:

df.where(col("dt_mvmt").isNull())

df.where(col("dt_mvmt").isNotNull())

If you want to simply drop NULL values you can use na.drop with subset argument:

df.na.drop(subset=["dt_mvmt"])

Equality based comparisons with NULL won't work because in SQL NULL is undefined so any attempt to compare it with another value returns NULL:

sqlContext.sql("SELECT NULL = NULL").show()
## +-------------+
## |(NULL = NULL)|
## +-------------+
## |         null|
## +-------------+


sqlContext.sql("SELECT NULL != NULL").show()
## +-------------------+
## |(NOT (NULL = NULL))|
## +-------------------+
## |               null|
## +-------------------+

The only valid method to compare value with NULL is IS / IS NOT which are equivalent to the isNull / isNotNull method calls.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

The easy solution is to create a payload class that has the str1 and the str2 as attributes:

@Getter
@Setter
public class ObjHolder{

String str1;
String str2;

}

And after you can pass

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}

and the body of your request is:

{
    "str1": "test one",
    "str2": "two test"
}

How to use sbt from behind proxy?

When I added the proxy info to the %JAVA_OPTS%, I got an error "-Dhttp.proxyHost=yourserver was unexpected at this time". I put the proxy info in %SBT_OPTS% and it worked.

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

Get a list of dates between two dates using a function

Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

CREATE TABLE Numbers
(Number int  NOT NULL,
    CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
    SET @x=@x+1
    INSERT INTO Numbers VALUES (@x)
END

here is the function:

CREATE FUNCTION dbo.ListDates
(
     @StartDate    char(10)  
    ,@EndDate      char(10)
)
RETURNS
@DateList table
(
    Date datetime
)
AS
BEGIN


IF ISDATE(@StartDate)!=1 OR ISDATE(@EndDate)!=1
BEGIN
    RETURN
END

INSERT INTO @DateList
        (Date)
    SELECT
        CONVERT(datetime,@StartDate)+n.Number-1
        FROM Numbers  n
        WHERE Number<=DATEDIFF(day,@StartDate,CONVERT(datetime,@EndDate)+1)


RETURN

END --Function

use this:

select * from dbo.ListDates('2010-01-01', '2010-01-13')

output:

Date
-----------------------
2010-01-01 00:00:00.000
2010-01-02 00:00:00.000
2010-01-03 00:00:00.000
2010-01-04 00:00:00.000
2010-01-05 00:00:00.000
2010-01-06 00:00:00.000
2010-01-07 00:00:00.000
2010-01-08 00:00:00.000
2010-01-09 00:00:00.000
2010-01-10 00:00:00.000
2010-01-11 00:00:00.000
2010-01-12 00:00:00.000
2010-01-13 00:00:00.000

(13 row(s) affected)

Git pushing to remote branch

First, let's note that git push "wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec.

The remote part is usually trivial as it's almost always just the word origin. The trickier part is the refspec. Most commonly, people write a branch name here: git push origin master, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.

In particular, a refspec has two colon-separated parts. For git push, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name and the part on the right would be branch_name_test. For instance:

git push origin foo:foo_test

As you are doing the push, you can tell your git push to set your branch's upstream name at the same time, by adding -u to the git push options. Setting the upstream name makes your git save the foo_test (or whatever) name, so that a future git push with no arguments, while you're on the foo branch, can try to push to foo_test on the remote (git also saves the remote, origin in this case, so that you don't have to enter that either).

You need only pass -u once: it basically just runs git branch --set-upstream-to for you. (If you pass -u again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to yourself.)

However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default will be set to simple, which will refuse to push because the upstream's name differs from your own local name. If you set push.default to upstream, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)


1More precisely, git consults your remote.remote.push setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.

2This doesn't have to be a branch name. For instance, you can supply HEAD, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch on the right, though (it depends on what names are already on the remote).

Plotting of 1-dimensional Gaussian distribution function

You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.

So just change the gaussian() function to:

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

Spring - applicationContext.xml cannot be opened because it does not exist

enter image description here

I was struggling since a couple of hours for this issue because i was putting that file under resources folder but it didn't help me, finally i realized my mistake. Put it directly under src/main/java.

How to set xampp open localhost:8080 instead of just localhost

I believe the admin button will open the default configuration always. It simply contains a link to localhost/xampp and it doesn't read the server configuration.

If you change the default settings, you know what you changed and you can enter the URL directly in the browser.

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

It sounds to me that you really want to limit the rows being returned in your query and page through the results. If so, you can do something like:

select * from (select rownum myrow, a.* from TEST1 a )
where myrow between 5 and 10 ;

You just have to determine your boundaries.

How to trigger checkbox click event even if it's checked through Javascript code?

Trigger function from jQuery could be your answer.

jQuery docs says: Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user

Thus best one line solution should be:

$('.selector_class').trigger('click');

//or

$('#foo').click();

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Not all at once. But you can press

Alt + Enter

People assume it only works when you are at the particular item. But it actually works for "next missing type". So if you keep pressing Alt + Enter, IDEA fixes one after another until all are fixed.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Delimiters, delimiters...

You really need them when there are multiple statements in your procedure. (in other words, do you have a ; in your code and then more statements/commands? Then, you need to use delimiters).

For such a simpler rpocedure as yours though, you could just do:

CREATE PROCEDURE ProG()
  SELECT * FROM `hs_hr_employee_leave_quota`;

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

dropping rows from dataframe based on a "not in" condition

You can use Series.isin:

df = df[~df.datecolumn.isin(a)]

While the error message suggests that all() or any() can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).

You can read more about this in the Gotchas.

Eclipse and Windows newlines

To recursively remove the carriage returns (\r) from the CVS/* files in all child directories, run the following in a unix shell:

find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;

PHP: Return all dates between two dates in an array

Here is the another solution. Please check this.

$first = '10/30/2017'; //starting date
$last= '10/11/2017';   //ending date
$first_time_arr=explode('/',$first); 
$last_time_arr=explode('/',$last);
//create timestamp of starting date
$start_timestamp=mktime(0,0,0, $first_time_arr[0], $first_time_arr[1],$first_time_arr[2]);
//create timestamp of ending date
$end_timestamp=mktime(0,0,0, $last_time_arr[0], $last_time_arr[1],$last_time_arr[2]);
$date_arr=array();
for($i=$start_timestamp;$i<=$end_timestamp;$i=$i+86400){
    $date_arr[]=date("Y-m-d",$i); //this will save all dates in array
}

Reducing the gap between a bullet and text in a list item

I'm not sure whether this is the best way to do it, but you could specify a negative text-indent:

li {
    text-indent: -4px;
}

...where your HTML code looks like:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

(Tested in Safari 4.0.4 and Firefox 3.0.11.)

How to fix Subversion lock error

I solved this problem by doing these:

  1. Right click on your project.

  2. Click on Team

  3. Click Refresh/Cleaup

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

DataRow: Select cell value by a given column name

You can get the column value in VB.net

Dim row As DataRow = fooTable.Rows(0)
Dim temp = Convert.ToString(row("ColumnName"))

And in C# you can use Jimmy's Answer, just be careful while converting it to ToString(). It can throw null exception if the data is null instead Use Convert.ToString(your_expression) to avoid null exception reference

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

There are possible solutions here: http://forums.mysql.com/read.php?35,64808,254785#msg-254785 and here: http://forums.mysql.com/read.php?35,23138,254786#msg-254786

All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.

Finally, more or less by accident, I bumped into the file:

...path_to_XAMPP\XAMPP...\mysql\bin\mysqld-debug.exe

Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.

Apache won't follow symlinks (403 Forbidden)

With the option FollowSymLinks enabled:

$ rg "FollowSymLinks" /etc/httpd/
/etc/httpd/conf/httpd.conf
269:    Options Indexes FollowSymLinks

you need all the directories in symlink to be executable by the user httpd is using.

so for this general use case:

cd /path/to/your/web
sudo ln -s $PWD /srv/http/

You can check owner an permissions with namei:

$ namei -m /srv/http/web
f: /srv/http/web
 drwxr-xr-x /
 drwxr-xr-x srv
 drwxr-xr-x http
 lrwxrwxrwx web -> /path/to/your/web
   drwxr-xr-x /
   drwxr-xr-x path
   drwx------ to
   drwxr-xr-x your
   drwxr-xr-x web

In my case to directory was only executable for my user:

Enable execution by others solve it:

chmod o+x /path/to

See the non executable directory could be different, or you need to affect groups instead others, that depends on your case.

How do I set response headers in Flask?

You can do this pretty easily:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Look at flask.Response and flask.make_response()

But something tells me you have another problem, because the after_request should have handled it correctly too.

EDIT
I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are:

curl -i http://127.0.0.1:5000/your/endpoint

You should see

> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT

Noting the Access-Control-Allow-Origin header.

EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem.

For example:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined

Targeting only Firefox with CSS

The following code tends to throw Style lint warnings:

@-moz-document url-prefix() {
    h1 {
        color: red;
    }
}

Instead using

@-moz-document url-prefix('') {
    h1 {
        color: red;
    }
}

Helped me out! Got the solution for style lint warning from here

Difference in days between two dates in Java?

Based on @Mad_Troll's answer, I developed this method.

I've run about 30 test cases against it, is the only method that handles sub day time fragments correctly.

Example: If you pass now & now + 1 millisecond that is still the same day. Doing 1-1-13 23:59:59.098 to 1-1-13 23:59:59.099 returns 0 days, correctly; allot of the other methods posted here will not do this correctly.

Worth noting it does not care about which way you put them in, If your end date is before your start date it will count backwards.

/**
 * This is not quick but if only doing a few days backwards/forwards then it is very accurate.
 *
 * @param startDate from
 * @param endDate   to
 * @return day count between the two dates, this can be negative if startDate is after endDate
 */
public static long daysBetween(@NotNull final Calendar startDate, @NotNull final Calendar endDate) {

    //Forwards or backwards?
    final boolean forward = startDate.before(endDate);
    // Which direction are we going
    final int multiplier = forward ? 1 : -1;

    // The date we are going to move.
    final Calendar date = (Calendar) startDate.clone();

    // Result
    long daysBetween = 0;

    // Start at millis (then bump up until we go back a day)
    int fieldAccuracy = 4;
    int field;
    int dayBefore, dayAfter;
    while (forward && date.before(endDate) || !forward && endDate.before(date)) {
        // We start moving slowly if no change then we decrease accuracy.
        switch (fieldAccuracy) {
            case 4:
                field = Calendar.MILLISECOND;
                break;
            case 3:
                field = Calendar.SECOND;
                break;
            case 2:
                field = Calendar.MINUTE;
                break;
            case 1:
                field = Calendar.HOUR_OF_DAY;
                break;
            default:
            case 0:
                field = Calendar.DAY_OF_MONTH;
                break;
        }
        // Get the day before we move the time, Change, then get the day after.
        dayBefore = date.get(Calendar.DAY_OF_MONTH);
        date.add(field, multiplier);
        dayAfter = date.get(Calendar.DAY_OF_MONTH);

        // This shifts lining up the dates, one field at a time.
        if (dayBefore == dayAfter && date.get(field) == endDate.get(field))
            fieldAccuracy--;
        // If day has changed after moving at any accuracy level we bump the day counter.
        if (dayBefore != dayAfter) {
            daysBetween += multiplier;
        }
    }
    return daysBetween;
}

You can remove the @NotNull annotations, these are used by Intellij to do code analysis on the fly

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

How to use count and group by at the same select statement

if You Want to use Select All Query With Count Option, try this...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition

What is the difference between the HashMap and Map objects in Java?

Map is the static type of map, while HashMap is the dynamic type of map. This means that the compiler will treat your map object as being one of type Map, even though at runtime, it may point to any subtype of it.

This practice of programming against interfaces instead of implementations has the added benefit of remaining flexible: You can for instance replace the dynamic type of map at runtime, as long as it is a subtype of Map (e.g. LinkedHashMap), and change the map's behavior on the fly.

A good rule of thumb is to remain as abstract as possible on the API level: If for instance a method you are programming must work on maps, then it's sufficient to declare a parameter as Map instead of the stricter (because less abstract) HashMap type. That way, the consumer of your API can be flexible about what kind of Map implementation they want to pass to your method.

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

A function to convert null to string

When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString() and it will return ""

Example:

 reader["Column"].ToString() 

Gets you "" if the value returned is DBNull.Value

If the scenario is not always a database, then I'd go for an Extension method:

public static class Extensions
{

    public static string EmptyIfNull(this object value)
    {
        if (value == null)
            return "";
        return value.ToString();
    }
}

Usage:

string someVar = null; 
someVar.EmptyIfNull();

When is del useful in Python?

Here goes my 2 cents contribution:

I have a optimization problem where I use a Nlopt library for it. I initializing the class and some of its methods, I was using in several other parts of the code.

I was having ramdom results even if applying the same numerical problem.

I just realized that by doing it, some spurius data was contained in the object when it should have no issues at all. After using del, I guess the memory is being properly cleared and it might be an internal issue to that class where some variables might not be liking to be reused without proper constructor.

Checking if a double (or float) is NaN in C++

It seems to me that the best truly cross-platform approach would be to use a union and to test the bit pattern of the double to check for NaNs.

I have not thoroughly tested this solution, and there may be a more efficient way of working with the bit patterns, but I think that it should work.

#include <stdint.h>
#include <stdio.h>

union NaN
{
    uint64_t bits;
    double num;
};

int main()
{
    //Test if a double is NaN
    double d = 0.0 / 0.0;
    union NaN n;
    n.num = d;
    if((n.bits | 0x800FFFFFFFFFFFFF) == 0xFFFFFFFFFFFFFFFF)
    {
        printf("NaN: %f", d);
    }

    return 0;
}

How to cast or convert an unsigned int to int in C?

If you have a variable unsigned int x;, you can convert it to an int using (int)x.

Spark read file from S3 using sc.textFile ("s3n://...)

Ran into the same problem in Spark 2.0.2. Resolved it by feeding it the jars. Here's what I ran:

$ spark-shell --jars aws-java-sdk-1.7.4.jar,hadoop-aws-2.7.3.jar,jackson-annotations-2.7.0.jar,jackson-core-2.7.0.jar,jackson-databind-2.7.0.jar,joda-time-2.9.6.jar

scala> val hadoopConf = sc.hadoopConfiguration
scala> hadoopConf.set("fs.s3.impl","org.apache.hadoop.fs.s3native.NativeS3FileSystem")
scala> hadoopConf.set("fs.s3.awsAccessKeyId",awsAccessKeyId)
scala> hadoopConf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey)
scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
scala> sqlContext.read.parquet("s3://your-s3-bucket/")

obviously, you need to have the jars in the path where you're running spark-shell from

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

Include jQuery in the JavaScript Console

Per this answer:

fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))

For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.

This is the equivalent if your browser isn't so modern:

fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})

How can I format a list to print each element on a separate line in python?

You can just use a simple loop: -

>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
        print elem 

10
12
14

Automate scp file transfer using a shell script

This will work:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

imagecreatefromjpeg and similar functions are not working in PHP

In Ubuntu/Mint (Debian based)

$ sudo apt-get install php5-gd

Correct way to load a Nib for a UIView subclass

Follow the following steps

  1. Create a class named MyView .h/.m of type UIView.
  2. Create a xib of same name MyView.xib.
  3. Now change the File Owner class to UIViewController from NSObject in xib. See the image below enter image description here
  4. Connect the File Owner View to your View. See the image below enter image description here

  5. Change the class of your View to MyView. Same as 3.

  6. Place controls create IBOutlets.

Here is the code to load the View:

UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];

Hope it helps.

Clarification:

UIViewController is used to load your xib and the View which the UIViewController has is actually MyView which you have assigned in the MyView xib..

Demo I have made a demo grab here

postgresql duplicate key violates unique constraint

Intro

I also encountered this problem and the solution proposed by @adamo was basically the right solution. However, I had to invest a lot of time in the details, which is why I am now writing a new answer in order to save this time for others.

Case

My case was as follows: There was a table that was filled with data using an app. Now a new entry had to be inserted manually via SQL. After that the sequence was out of sync and no more records could be inserted via the app.

Solution

As mentioned in the answer from @adamo, the sequence must be synchronized manually. For this purpose the name of the sequence is needed. For Postgres, the name of the sequence can be determined with the command PG_GET_SERIAL_SEQUENCE. Most examples use lower case table names. In my case the tables were created by an ORM middleware (like Hibernate or Entity Framework Core etc.) and their names all started with a capital letter.

In an e-mail from 2004 (link) I got the right hint.

(Let's assume for all examples, that Foo is the table's name and Foo_id the related column.)

Command to get the sequence name:

SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id');

So, the table name must be in double quotes, surrounded by single quotes.

1. Validate, that the sequence is out-of-sync

SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')) AS "Current Value", MAX("Foo_id") AS "Max Value" FROM "Foo";

When the Current Value is less than Max Value, your sequence is out-of-sync.

2. Correction

SELECT SETVAL((SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')), (SELECT (MAX("Foo_id") + 1) FROM "Foo"), FALSE);

How does String substring work in Swift

Same frustration, this should not be that hard...

I compiled this example of getting positions for substring(s) from larger text:

//
// Play with finding substrings returning an array of the non-unique words and positions in text
//
//

import UIKit

let Bigstring = "Why is it so hard to find substrings in Swift3"
let searchStrs : Array<String>? = ["Why", "substrings", "Swift3"]

FindSubString(inputStr: Bigstring, subStrings: searchStrs)


func FindSubString(inputStr : String, subStrings: Array<String>?) ->    Array<(String, Int, Int)> {
    var resultArray : Array<(String, Int, Int)> = []
    for i: Int in 0...(subStrings?.count)!-1 {
        if inputStr.contains((subStrings?[i])!) {
            let range: Range<String.Index> = inputStr.range(of: subStrings![i])!
            let lPos = inputStr.distance(from: inputStr.startIndex, to: range.lowerBound)
            let uPos = inputStr.distance(from: inputStr.startIndex, to: range.upperBound)
            let element = ((subStrings?[i])! as String, lPos, uPos)
            resultArray.append(element)
        }
    }
    for words in resultArray {
        print(words)
    }
    return resultArray
}

returns ("Why", 0, 3) ("substrings", 26, 36) ("Swift3", 40, 46)

Check if list is empty in C#

You should use a simple IF statement

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();

Compare one String with multiple values in one expression

In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like

if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
    // ...
}

Font scaling based on width of container

But what if the container is not the viewport (body)?

The real answer is in the transform property allows you to visually manipulate an element by skewing, rotating, translating, or scaling:

https://css-tricks.com/almanac/properties/t/transform/

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

How to set cursor position in EditText?

as a reminder: if you are using edittext.setSelection() to set the cursor, and it is NOT working while setting up an alertdialog for example, make sure to set the selection() AFTER the dialog has been created

example:

AlertDialog dialog = builder.show();
input.setSelection(x,y);

What is a "cache-friendly" code?

Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.

Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.

So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.

Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.

So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.

If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

How can I make my layout scroll both horizontally and vertically?

You can do this by using below code

<HorizontalScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <ScrollView
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">
                            
                        </LinearLayout>
                    </ScrollView>
    </HorizontalScrollView>

Length of array in function argument

First, a better usage to compute number of elements when the actual array declaration is in scope is:

sizeof array / sizeof array[0]

This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.

Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.

Third, C doesn't have references so your usage of & in a declaration won't work.

I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.

Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.

Android - Package Name convention

But if your Android App is only for personal purpose or created by you alone, you can use:

me.app_name.app

Apply CSS to jQuery Dialog Buttons

If still noting is working for you add the following styles on your page style sheet

.ui-widget-content .ui-state-default {
  border: 0px solid #d3d3d3;
  background: #00ACD6 50% 50% repeat-x;
  font-weight: normal;
  color: #fff;
}

It will change the background color of the dialog buttons.

How do I get rid of the b-prefix in a string in python?

****How to remove b' ' chars which is decoded string in python ****

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

write multiple lines in a file in python

this also works:

target.write("{}" "\n" "{}" "\n" "{}" "\n".format(line1, line2, line3))

Possible reasons for timeout when trying to access EC2 instance

For me, it was that I had deleted everything from the boot volume. And couldn't connect to the instance anymore.

How to use LogonUser properly to impersonate domain user from workgroup client

Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.

Create a CSV File for a user in PHP

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

R: Print list to a text file

Here's another way using sink:

sink(sink_dir_and_file_name); print(yourList); sink()

Catch a thread's exception in the caller thread in Python

In Python 3.8, we can use threading.excepthook to hook the uncaught exceptions in all the child threads! For example,

threading.excepthook = thread_exception_handler

Referer: https://stackoverflow.com/a/60002752/5093308

Capturing browser logs with Selenium WebDriver using Java

I assume it is something in the lines of:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ChromeConsoleLogging {
    private WebDriver driver;


    @BeforeMethod
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");        
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
        driver = new ChromeDriver(caps);
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }

    public void analyzeLog() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
            //do something useful with the data
        }
    }

    @Test
    public void testMethod() {
        driver.get("http://mypage.com");
        //do something on page
        analyzeLog();
    }
}

Source : Get chrome's console log

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

Select Rows with id having even number

SELECT * FROM ( SELECT *, Row_Number() 
OVER(ORDER BY country_gid) AS sdfg  FROM eka_mst_tcountry ) t 
WHERE t.country_gid % 2 = 0 

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

Change Text Color of Selected Option in a Select Box

<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

Add this import <%@page import="java.util.Map" %>

This worked for me, but I also needed to add <%@ page import="java.util.HashMap" %>. It seems that the above answer is true, that if you have the newer tomcat you might not need to add these lines, but as I could not change my whole system, this worked.
Thank you

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

Conditionally formatting cells if their value equals any value of another column

I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)

However, if we are trying to match "any" value of another column, how about using nested loops like the following?

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String


sheetName = "Sheet1"            'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

For lRowA = 1 To lastRow         'Loop through all rows
    For lRowB = 1 To lastRow
        If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then

        Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3  'Set Color to RED
    End If

Next lRowB
Next lRowA

End Sub

How to create an Excel File with Nodejs?

You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.

c# razor url parameter from view

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

In Java how does one turn a String into a char or a char into a String?

In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();

What is the difference between Integer and int in Java?

int is a primitive data type while Integer is a Reference or Wrapper Type (Class) in Java.

after java 1.5 which introduce the concept of autoboxing and unboxing you can initialize both int or Integer like this.

int a= 9
Integer a = 9 // both valid After Java 1.5.

why Integer.parseInt("1"); but not int.parseInt("1"); ??

Integer is a Class defined in jdk library and parseInt() is a static method belongs to Integer Class

So, Integer.parseInt("1"); is possible in java. but int is primitive type (assume like a keyword) in java. So, you can't call parseInt() with int.

NodeJS - What does "socket hang up" actually mean?

I do both web (node) and Android development, and open Android Studio device simulator and docker together, both of them use port 8601, it complained socket hang up error, after close Android Studio device simulator and it works well in node side. Don’t use Android Studio device simulator and docker together.

How to make a checkbox checked with jQuery?

from jQuery v1.6 use prop

to check that is checkd or not

$('input:radio').prop('checked') // will return true or false

and to make it checkd use

$("input").prop("checked", true);

Simple function to sort an array of objects

How about this?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

iPhone SDK:How do you play video inside a view? Rather than fullscreen

As of the 3.2 SDK you can access the view property of MPMoviePlayerController, modify its frame and add it to your view hierarchy.

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
player.view.frame = CGRectMake(184, 200, 400, 300);
[self.view addSubview:player.view];
[player play];

There's an example here: http://www.devx.com/wireless/Article/44642/1954

Binding Listbox to List<object> in WinForms

ListBox1.DataSource = CreateDataSource();
ListBox1.DataTextField = "FieldProperty";
ListBox1.DataValueField = "ValueProperty";

Please refer to this article for detailed examples.

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

Visual Studio Community 2015 expiration date

In case you had enabled 2-Step verification for your Microsoft account disable it when updating the VS License using the 'Check for Updated License' option provided in the window.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

After looking around, the solution was to remove the NDK designation from my preferences.

Android Studio ? Preferences ? System Settings ? Android SDK ? SDK Tools ? Unselect NDK ? Apply button.

Project and Gradle compiled fine after that and I was able to move on with my project work.

As far as why this is happening, I do not know but for more info on NDK check out:

How to export table data in MySql Workbench to csv?

You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:

MySQL Workbench Export Resultset Button

Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:

MySQL Workbench Preferences Dialog

Hope this helps.

Python, HTTPS GET with basic authentication

requests.get(url, auth=requests.auth.HTTPBasicAuth(username=token, password=''))

If with token, password should be ''.

It works for me.

Is there a short contains function for lists?

The list method index will return -1 if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if statement you can do the following:

if myItem in list:
    #do things

You can also check if an element is not in a list with the following if statement:

if myItem not in list:
    #do things

How to pass variable number of arguments to printf/sprintf

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.

Android difference between Two Dates

It will give you difference in months

long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;

System.out.println(String.format("%d months", elapsedDays/30));

C# compiler error: "not all code paths return a value"

class Program
{
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;


    public double[] CheckSorting()
    {
        for(int i = 1; i < a.Length; i++)
        {
            if (a[i] < a[i - 1])
                result = b;
            else
                result = a;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Program checkSorting = new Program();
        checkSorting.CheckSorting();
        Console.ReadLine();
    }
}

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

A reference to the dll could not be added

The following worked for me:

Short answer

Run the following via command line (cmd):

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

And a valid dll will be created for you.

Longer answer

  • Open cmd

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

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

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

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

Is it possible to have multiple statements in a python lambda expression?

You can do it in O(n) time using min and index instead of using sort or heapq.

First create new list of everything except the min value of the original list:

new_list = lst[:lst.index(min(lst))] + lst[lst.index(min(lst))+1:]

Then take the min value of the new list:

second_smallest = min(new_list)

Now all together in a single lambda:

map(lambda x: min(x[:x.index(min(x))] + x[x.index(min(x))+1:]), lst)

Yes it is really ugly, but it should be algorithmically cheap. Also since some folks in this thread want to see list comprehensions:

[min(x[:x.index(min(x))] + x[x.index(min(x))+1:]) for x in lst]

Date difference in years using C#

I have written an implementation that properly works with dates exactly one year apart.

However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.

So without further ado, here is the code:

DateTime zeroTime = new DateTime(1, 1, 1);

DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);

TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;

// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);

how to calculate binary search complexity

For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation

Apply Masters Theorem for computing Run time complexity of recurrence relations : T(N) = aT(N/b) + f(N)

Here, a = 1, b = 2 => log (a base b) = 1

also, here f(N) = n^c log^k(n) //k = 0 & c = log (a base b)

So, T(N) = O(N^c log^(k+1)N) = O(log(N))

Source : http://en.wikipedia.org/wiki/Master_theorem

How to call a RESTful web service from Android?

I used OkHttpClient to call restful web service. It's very simple.

OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
                .url(url)
                .build();

Response response = httpClient.newCall(request).execute();
String body = response.body().string()

Attach Authorization header for all axios requests

export const authHandler = (config) => {
  const authRegex = /^\/apiregex/;

  if (!authRegex.test(config.url)) {
    return store.fetchToken().then((token) => {
      Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
      return Promise.resolve(config);
    });
  }
  return Promise.resolve(config);
};

axios.interceptors.request.use(authHandler);

Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:

  1. If using axios for the request to get a token in your store, you need to detect the path before adding the header. If you don't, it will try to add the header to that call as well and get into a circular path issue. The inverse of adding regex to detect the other calls would also work
  2. If the store is returning a promise, you need to return the call to the store to resolve the promise in the authHandler function. Async/Await functionality would make this easier/more obvious
  3. If the call for the auth token fails or is the call to get the token, you still want to resolve a promise with the config

Hash String via SHA-256 in Java

Java 8: Base64 available:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );

Parsing a pcap file in python

You might want to start with scapy.

Remove NA values from a vector

You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

Description Box using "onmouseover"

Although not necessarily a JavaScript solution, there is also a "title" global tag attribute that may be helpful.

<a href="https://stackoverflow.com/questions/3559467/description-box-on-mouseover" title="This is a title.">Mouseover me</a>

Mouseover me

add Shadow on UIView using swift 3

CODE SNIPPET:

extension UIView {

  // OUTPUT 1
  func dropShadow(scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOpacity = 0.5
    layer.shadowOffset = CGSize(width: -1, height: 1)
    layer.shadowRadius = 1

    layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }

  // OUTPUT 2
  func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = color.cgColor
    layer.shadowOpacity = opacity
    layer.shadowOffset = offSet
    layer.shadowRadius = radius

    layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }
}

NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

OUTPUT 1:

shadowView.dropShadow()

enter image description here

OUTPUT 2:

shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)

enter image description here

layer.shouldRasterize = true will make the shadow static and cause a shadow for the initial state of the UIView. So I would recommend not to use layer.shouldRasterize = true in dynamic layouts like view inside a UITableViewCell.

How do I convert from BLOB to TEXT in MySQL?

You can do it very easily.

ALTER TABLE `table_name` CHANGE COLUMN `column_name` `column_name` LONGTEXT NULL DEFAULT NULL ;

The above query worked for me. I hope it helps you too.

C# difference between == and Equals()

== Operator

  1. If operands are Value Types and their values are equal, it returns true else false.
  2. If operands are Reference Types with exception of string and both refer to the same instance (same object), it returns true else false.
  3. If operands are string type and their values are equal, it returns true else false.

.Equals

  1. If operands are Reference Types, it performs Reference Equality that is if both refer to the same instance (same object), it returns true else false.
  2. If Operands are Value Types then unlike == operator it checks for their type first and if their types are same it performs == operator else it returns false.

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

What is the way of declaring an array in JavaScript?

In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

How to return Json object from MVC controller to view

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>

How to convert QString to int?

You can use:

QString str = "10";
int n = str.toInt();

Output:

n = 10

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

Using group by and having clause

The semantics of Having

To better understand having, you need to see it from a theoretical point of view.

A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.

The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.

Lets say your query is:

select a, b, count(*) 
from Table 
where c > 100 
group by a, b 
having count(*) > 10;

The evaluation of this query can be seen as the following steps:

  1. Perform the WHERE, eliminating rows that do not satisfy it.
  2. Group the table into subsets based upon the values of a and b (each tuple in each subset has the same values of a and b).
  3. Eliminate subsets that do not satisfy the HAVING condition
  4. Process each subset outputting the values as indicated in the SELECT part of the query. This creates one output tuple per subset left after step 3.

You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).

In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:

SELECT list 
FROM table
GROUP BY attrList
HAVING condition;

can be rewritten as:

SELECT list from (
   SELECT listatt 
   FROM table 
   GROUP BY attrList) as Name
WHERE condition;

The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:

select a, b, count 
from (select a, b, count(*) as count
      from Table 
      where c > 100
      group by a, b) as someName
where count > 10;

The solution you need

Your solution seems to be correct:

SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2 

You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2, which is that you wanted originally.

Best solution to your problem

I personally prefer a simpler cleaner solution:

  1. You need to only group by Supplies (sid, pid, jid**, quantity) to find the sid of those that supply at least to two projects.
  2. Then join it to the Suppliers table to get the supplier same.

 SELECT sid, sname from
    (SELECT sid from supplies 
    GROUP BY sid, pid 
    HAVING count(DISTINCT jid) >= 2
    ) AS T1
NATURAL JOIN 
Supliers;

It will also be faster to execute, because the join is only done when needed, not all the times.

--dmg

toggle show/hide div with button?

Pure JavaScript:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

SEE DEMO

jQuery:

$("#button").click(function() { 
    // assumes element with id='button'
    $("#newpost").toggle();
});

SEE DEMO

How to vertically align <li> elements in <ul>?

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .toolbar ul {
            display:table-row;
        }
        .toolbar ul li
        {
            display: table-cell;
            height: 100px;
            list-style-type: none;
            margin: 10px;
            vertical-align: middle;
        }
        .toolbar ul li a {
            display:table-cell;
            vertical-align: middle;
            height:100px;
            border: solid 1px black;
        }
        .toolbar ul li.button a {
            height:50px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <div class="toolbar">
        <ul>
            <li><a href="#">first item<br />
                first item<br />
                first item</a></li>
            <li><a href="#">second item</a></li>
            <li><a href="#">last item</a></li>
            <li class="button"><a href="#">button<br />
                button</a></li>
        </ul>
    </div>
</body>
</html>

Change the content of a div based on selection from dropdown menu

I am not a coder, but you could save a few lines:

<div>
            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>
            </select>
        </div>

<div id="less_is_more"></div>

Here is demo.

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

Vertical align in bootstrap table

SCSS

.table-vcenter {
    td,
    th {
        vertical-align: middle;
    }
}

use

<table class="table table-vcenter">
</table>

port forwarding in windows

I've solved it, it can be done executing:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111

Official docs

Simplest Way to Test ODBC on WIndows

a simple way is:

create a fake "*.UDL" file on desktop

(UDL files are described here: https://msdn.microsoft.com/en-us/library/e38h511e(v=vs.71).aspx.

in case you can also customized it as explained there. )

How do you read CSS rule values with JavaScript?

Here is code to iterate through all rules in a page:

_x000D_
_x000D_
function iterateCSS(f) {_x000D_
  for (const styleSheet of window.document.styleSheets) {_x000D_
    const classes = styleSheet.rules || styleSheet.cssRules;_x000D_
    if (!classes) continue;_x000D_
_x000D_
    for (const cssRule of classes) {_x000D_
      if (cssRule.type !== 1 || !cssRule.style) continue;_x000D_
      const selector = cssRule.selectorText, style=cssRule.style;_x000D_
      if (!selector || !style.cssText) continue;_x000D_
      for (let i=0; i<style.length; i++) {_x000D_
        const propertyName=style.item(i);_x000D_
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {_x000D_
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');_x000D_
});
_x000D_
_x000D_
_x000D_

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

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

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

Get the current date and time

use DateTime.Now

try this:

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

How to count duplicate rows in pandas dataframe?

ran into this problem today and wanted to include NaNs so I replace them temporarily with "" (empty string). Please comment if you do not understand something :). This solution assumes that "" is not a relevant value for you. It should also work with numerical data (I have tested it sucessfully but not extensively) since pandas will infer the data type again after replacing "" with np.nan.

import pandas as pd

# create test data
df = pd.DataFrame({'test':['foo','bar',None,None,'foo'],
                  'test2':['bar',None,None,None,'bar'],
                  'test3':[None, 'foo','bar',None,None]})

# fill null values with '' to not lose them during groupby
# groupby all columns and calculate the length of the resulting groups
# rename the series obtained with groupby to "group_count"
# reset the index to get a DataFrame
# replace '' with np.nan (this reverts our first operation)
# sort DataFrame by "group_count" descending
df = (df.fillna('')\
      .groupby(df.columns.tolist()).apply(len)\
      .rename('group_count')\
      .reset_index()\
      .replace('',np.nan)\
      .sort_values(by = ['group_count'], ascending = False))
df
  test test2 test3  group_count
3  foo   bar   NaN            2
0  NaN   NaN   NaN            1
1  NaN   NaN   bar            1
2  bar   NaN   foo            1

Progress during large file copy (Copy-Item & Write-Progress?)

cmd /c copy /z src dest

not pure PowerShell, but executable in PowerShell and it displays progress in percents