text:
Q: How to import from parent directory using importlib in Python? I have a directory like this:
Project Folder
├─main.py
├─Utils
│  └─util1.py
└─Plugins
   └─plugin1.py

How can I import util1.py directly from plugin1.py? I tried using importlib.import_module('Utils.util1', '..'), but that didn't work. from ..Utils import util1 and from .. import Utils.util1 also did not work (ValueError: attempted relative import beyond top-level package)
Please note: its not utils and plugins in my directory, I just named them like that here for ease.

A: # From http://stackoverflow.com/a/11158224

# Solution A - If the script importing the module is in a package
from .. import mymodule

# Solution B - If the script importing the module is not in a package
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import mymodule

A: you could do:
not tested
import os, sys
currentDir = os.getcwd()
os.chdir('..') # .. to go back one dir | you can do "../aFolderYouWant"
sys.path.insert(0, os.getcwd())
import mymodule
os.chdir(currentDir) # to go back to your home directory


text:
Q: Flight seating: Python (reset seating problem) I'm working on an assignment that books seats on a flight, the code I have so far works for everything besides the part for resetting all the seats to available when the flight is fully booked.
NUM_ROWS = 2
NUM_COLS = 1
AVAIL = '-'
BOOKED = 'X'

seatTable = []
for i in range(NUM_ROWS):
    column = []
    for j in range(NUM_COLS):
        column.append(AVAIL)
    seatTable.append(column)

def resetTable(seats):          ##<--need to fix
    seatTable = []
    for i in range(NUM_ROWS):
        column = []
        for j in range(NUM_COLS):
            column.append(AVAIL)
        seatTable.append(column)
    resetTable(printTable(seatTable))   ##<-- not correct
    print()

def printTable(seats):
    i=1
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    print('Row', end=' ')

    for num in range(NUM_COLS):
        print(f'{alpha[num]:2s}'.format(alpha),end='')
    print()

    for num in seats:
        print(f'{str(i):3s}'.format(str(i)), end=' ')
        i+=1
        for j in num:
            print(j,end=' ')
        print()

def full(seats):
    for row in seats:
        for seat in row:
            if seat == AVAIL:
                return False
    return True

def getRes():
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    while True:
        try:
            rowNum = input(f'Enter a row number (1 to {NUM_ROWS}): ')
            seatLetter = input(f'Enter a seat letter (A to {(alpha[NUM_COLS-1]).upper()}): ')
            reserve(seatTable,rowNum,seatLetter)
            break
        except:
            pass
        print('Error, Please choose another seat')
    print(f'Seat {rowNum}{seatLetter.upper()} has been booked\n')

def reserve(seats,resR,resC):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    column = 0
    p = 0
    for i in alpha:
        if i.lower() == resC.lower():
            column = p
        p+=1
    row = int(resR)-1
    seats[row][column] = BOOKED

def main():
    printTable(seatTable)
    while not full(seatTable):
        getRes()
        printTable(seatTable)
    print('Plane is booked')
    next = input('\nWould you like to check the next flight? (Y/N): ')
    if next == 'y':                        ##<---problem
        resetTable(printTable(seatTable))
        return main()
    else:
        exit()
main()

When I run the code to check for the "next flight" the seats reset, but then gets stuck on an infinite loop, followed by an error:
line 23, in resetTable
     resetTable(printTable(seatTable)) ##<-- not correct
     [Previous line repeated 992 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

How can I fix the resetTable() function to work?

A: Try this
NUM_ROWS = 2
NUM_COLS = 1
AVAIL = '-'
BOOKED = 'X'

seatTable = []
for i in range(NUM_ROWS):
    column = []
    for j in range(NUM_COLS):
        column.append(AVAIL)
    seatTable.append(column)

def resetTable(seats):
    for i in range(NUM_ROWS):
        column = []
        for j in range(NUM_COLS):
            seatTable[i][j] = AVAIL

def printTable(seats):
    i=1
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    print('Row', end=' ')

    for num in range(NUM_COLS):
        print(f'{alpha[num]:2s}'.format(alpha),end='')
    print()

    for num in seats:
        print(f'{str(i):3s}'.format(str(i)), end=' ')
        i+=1
        for j in num:
            print(j,end=' ')
        print()

def full(seats):
    for row in seats:
        for seat in row:
            if seat == AVAIL:
                return False
    return True

def getRes():
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    while True:
        try:
            rowNum = input(f'Enter a row number (1 to {NUM_ROWS}): ')
            seatLetter = input(f'Enter a seat letter (A to {(alpha[NUM_COLS-1]).upper()}): ')
            reserve(seatTable,rowNum,seatLetter)
            break
        except:
            pass
        print('Error, Please choose another seat')
    print(f'Seat {rowNum}{seatLetter.upper()} has been booked\n')

def reserve(seats,resR,resC):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    column = 0
    p = 0
    for i in alpha:
        if i.lower() == resC.lower():
            column = p
        p+=1
    row = int(resR)-1
    seats[row][column] = BOOKED

def main():
    printTable(seatTable)
    while not full(seatTable):
        getRes()
        printTable(seatTable)
    print('Plane is booked')
    next = input('\nWould you like to check the next flight? (Y/N): ')
    if next == 'y':
        resetTable(seatTable)
        return main()
    else:
        exit()
main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove an identity involving Gamma function and Gaussian hypergeometric function The question asks to prove the following identity:
$$\int_0^{2\pi}\!\!\frac{e^{-in\Psi}}{\left[\left(\frac{\rho}{\rho_0}\right)^2+1-2\left(\frac{\rho}{\rho_0}\right)\cos\Psi\right]^{\frac{1+u}{2}}}\mathbb{d}\Psi=\frac{2\pi\Gamma\left(n+\frac{1+u}{2}\right)}{\Gamma\left(\frac{1+u}{2}\right)\Gamma(n+1)}\left(\frac{\rho}{\rho_0}\right)^n F\left(\frac{1+u}{2},n+\frac{1+u}{2},n+1,\left(\frac{\rho}{\rho_0}\right)^2\right)
$$
where $i$ is the unit imaginary number, $n$ is an arbitrary integer, $\Gamma$ denotes the Gamma function, $F$ denotes the Gaussian hypergeometric function.
I have not even the slightest clue on how to deal with it. Can anyone help?

A: The left side is an even function of $n$, so let us assume (as you implicitly do on the right) that $n\geq0$. Also, denote $t=\frac{\rho}{\rho_0}$ and $a=\frac{1+u}{2}$. We want to compute
$$ I= \int_0^{2\pi}\frac{e^{-in\Psi}}{\left(1-2t\cos\Psi+t^2\right)^{a}}d\Psi.\qquad\qquad (\mathrm{A})$$
Write
$$ 1-2t\cos\Psi+t^2=1-t(e^{i\Psi}+e^{-i\Psi})+t^2= (1-te^{i\Psi})(1-te^{-i\Psi}).$$
Recall that $(1-x)^{-a}=\sum_{j=0}^{\infty}\frac{\Gamma(a+j)}{\Gamma(a)\Gamma(j+1)}x^j$. Multiplying two such series, we can write
$$ \left(1-2t\cos\Psi+t^2\right)^{-a}=\sum_{j=0}^{\infty}\sum_{k=0}^{\infty}\frac{\Gamma(a+j)\Gamma(a+k)}{\Gamma(a)\Gamma(j+1)\Gamma(a)\Gamma(k+1)}t^{j+k}e^{i(j-k)\Psi}.$$
Now we want to substitute this double series into (A) and integrate $e^{i(j-k-n)\Psi}$ w.r.t. $\Psi$. This is an easy task since almost all integrals are equal to zero. The only non-zero terms come from $j-k-n=0$, where the integral is equal to $2\pi$. Therefore (leaving only the sum over $k$ and replacing $j$ by $n+k$) we find
\begin{align*} I =2\pi\sum_{k=0}^{\infty}\frac{\Gamma(a+n+k)\Gamma(a+k)}{\Gamma(a)\Gamma(n+k+1)\Gamma(a)\Gamma(k+1)}t^{n+2k}=\\
=2\pi t^n\times\frac{\Gamma(a+n)}{\Gamma(a)\Gamma(n+1)}\times\sum_{k=0}^{\infty}\frac{\Gamma(n+a+k)\Gamma(n+1)\Gamma(a+k)}{\Gamma(n+a)\Gamma(n+k+1)\Gamma(a)}\frac{\left(t^2\right)^k}{k!}.
\end{align*}
The last sum is the standard series representation of $_2F_1(a,n+a,n+1,t^2)$, and we obtain the necessary identity. $\blacksquare$
There are several other ways to prove the same formula. For example, if you are ok with complex analysis, you can consider (A) as an integral over unit circle in the complex plane $z=e^{-i\Psi}$ and then shrink it to the branch cut $[0,t]$. This will give Euler integral representation of $_2F_1$.


text: Q: Mysql database is not starting in Bitnami wamp stack My mysql database in the bitnami wamp stack stopped unexpectedly and I am not able to restart it again. When I try to start the mysql from wmap stack manager it is continously showing 'starting' for hours. There is no change in the status. I have tried to start the mysql service from windows services, then I am getting a service timeout error.Following is the log I am getting in my mysql logs :


text:
Q: How to cache inserted values to HashMap from different threads and insert them to db after time interval I am learning RxJava and trying to simulate situation like this:
I have a hashMap:
private HashMap<String, Object> cacheToInsertToDb;

Suppose i put some values to it from different threads:
 Observable.interval(1, TimeUnit.SECONDS)
            .take(30) // up to 30 items
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    cacheToInsertToDb.put(aLong+"", aLong);
                    Log.d("Observable", cacheToInsertToDb.values().toString());
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {

                }
            }, new Action() {
                @Override
                public void run() throws Exception {

                }
            });

How can i manage situtation like this in RxJava: After insert of the values from diferrent threads in time interval like 30 seconds clear the hashmap and insert values to db, all in different thread. I want to not lose any inserted values. All should be synchronized. Is it possible to do it in one query in RxJava or is it more complicated?
For now i create something like this:
       Observable.interval(10, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    //TODO save current values and clear
                    cacheToInsertToDb.clear();
                    Log.d("CLEARED", cacheToInsertToDb.values().toString());
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {

                }
            }, new Action() {
                @Override
                public void run() throws Exception {

                }
            });

A: There are two things that you need in order to get that approach to work.
The first part is using a serialized source. Create a serialized subject, by:
Subject<Long> source = PublishSubject.<Long>create().toSerialized();

Now, each of your active threads can safely use source.onNext(value).
The second part is to move the caching and flushing to its own thread:
source
  .buffer( 30, TimeUnit.SECONDS )
  .subscribe( bufferedData -> db.write(bufferedData) );

buffer() will operate on a particular scheduler, and all downstream operations will run on that thread.


text:
Q: Hive: SELECT * statement works but not SELECT COUNT(*) I have HDP 1.1 on windows Server 2008 R2.
I loaded a web log in to hive table.
Create Table statement:
create table logtable (datenonQuery string , hours string, minutes string, seconds string, TimeTaken string, Method string, UriQuery string, ProtocolStatus string) row format serde 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe' with serdeproperties( "input.regex" = "(\\S+)\\t(\\d+):(\\d+):(\\d+)\\t(\\S+)\\t(\\S+)\\t(\\S+)\\t(\\S+)", "output.format.string" = "%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s") stored as textfile;

Load Statement:
load data local inpath 'D:\Logfiles\' into table logtable;

Select Statement:
Select * from logtable;

Everything so far works fine.
The following statement fails:
Select count(*) from logtable;

with exception:

FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

Edit1:
The diagnostic info in the Failed Job Table shows following info:

'# of failed Map Tasks exceeded allowed limit. FailedCount: 1. LastFailedTask: task_201306251711_0010_m_000000'

A: This is rather a hadoop related thing than hive. Th reason why SELECT * works and SELECT COUNT(*) doesn't is that latter involves a MR job. What is your datasize?
Try increasing the mapper heapsize by setting the property mapred.job.map.memory.mb to some higher value. Also try increasing the number of mappers by lowering the split size through mapred.min.split.size and see if it makes any difference.

A: If the output resultset has 2 columns with same name (possible in hive/impala) then count(*) won't work.
e.g. Query #1 will give results whereas Query #2 will give an error.
Resolution - Aliasing product_code column will resolve the error from Query #2
1) Select
a.product_code, b.product_code, b.product_name, a.purchase_date, a.purchase_qty
from
product_fact a
inner join product_dim b
on (a.product_code = b.product_code)
2) Select * from (
Select
a.product_code, b.product_code, b.product_name, a.purchase_date, a.purchase_qty
from
product_fact a
inner join product_dim b
on (a.product_code = b.product_code)
) as C

A: For me this particular error was an access issue. It was resolved when I connected to the DB using a username and password


text:
Q: Every element of a group has finite order Suppose that $G$ is a group, and that the intersection over the non-trivial subgroups of $G$ is non-trivial, i.e., that $$\bigcap_{H<G\atop H\ne \{e\}} H\neq\{e\}.$$ I need to demonstrate that  every element of $G$ has finite order.
I tried showing that if the intersection is trivial, an element of infinite order would be there, but couldn't get anywhere.


text:
Q: JS RegEx allow certain characters and a few character only when part of a specific sequence For quite a few hours I have been struggling with the following:
I want to use RegEx using JS to allow the following characters:
/^[a-zA-Z0-9 -.,]*$/igm

However I would also want to allow  or , which means I would allow the character < & > and /, but only when in either of the two forms above ( or ).
I was playing with something like;
/^(<(?=br \/>|br\/>))*&/img

Clearly this is not working, and I cannot seem to figure out how to test in one line of code whether the user input (a string) contains just the allowed characters plus the extra characters(<,>,/) but only when used as ( or ).
Your help is very much appreciated. Thank you.

A: You can use
^(?:<br ?\/>|[a-zA-Z0-9 .,-])*$

Details

*

*^ - start of string

*(?:<br ?\/>|[a-zA-Z0-9 .,-])* - zero or more:

*

*<br ?\/> - <br, an optional space, />

*| - or

*[a-zA-Z0-9 .,-] - a letter, digit, space, dot, comma or hyphen

*$ - end of string.


text:
Q: Displaying Different Images React I have the following classes in CSS that make me display a different image on a page after some period of time:
.image-fader {
  width: 300px;
  height: 300px;
}

.image-fader img {
  position: absolute;
  top: 0px;
  left: 0px;
  animation-name: imagefade;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-duration: 8s;
}

@keyframes imagefade {
  0% {
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  25% {
    opacity: 0;
  }
  92% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.image-fader img:nth-of-type(1) {
  animation-delay: 6s;
}
.image-fader img:nth-of-type(2) {
  animation-delay: 4s;
}
.image-fader img:nth-of-type(3) {
  animation-delay: 2s;
}
.image-fader img:nth-of-type(4) {
  animation-delay: 0;
}

So far I only have this CSS code that displays a single image:
.defaultHero,
.roomsHero {
  min-height: calc(100vh - 66px);
  background: url("./images/defaultBcg.jpeg") center/cover no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}

My Hero Component looks like this:
import React from 'react'

export default function Hero({children, hero}) {
return (

        {children}

)
}

Hero.defaultProps = {
    hero: "defaultHero"
};

And I'm calling it in my Homepage like this:
import React from 'react'
import Hero from "../Components/Hero";
import Banner from "../Components/Banner";
import {Link} from 'react-router-dom';

export default function Home() {
    return (
        <Hero>
            <Banner title="Affordable Apartments" subtitle="Family
        Apartments Starting At €90 per night">
        <Link to= "/rooms" className="btn-primary">
            our apartments
        </Link>
        </Banner>
        </Hero>
    );
}

}

How can I reference the image-fader class in my About page in order to return many images.

A: well with javascript you can do it like this:
import React from "react";
import image1 from "./img/1.png";
import image2 from "./img/2.png";
import image3 from "./img/3.png";

const imageArray = [image1, image2, image3];

const App = () => {
  const [current, setCurrent] = React.useState(0);

  React.useEffect(() => {
    const timerId = setInterval(() => {
        setCurrent(cur => (cur < imageArray.length - 1 ? cur + 1 : 0));
    }, 500);
    return () => {
        clearInterval(timerId);
    };
  }, []);

  return (

        {current}

  );
};
export default App;


text:
Q: How to test JSON result from Ruby on Rails functional tests? How can I assert my Ajax request and test the JSON output from Ruby on Rails functional tests?

A: In Rails >= 5
Use ActionDispatch::TestResponse#parsed_body.
Example:
user = @response.parsed_body
assert_equal "Mike", user['name']

In Rails up to 4.x
Use JSON.parse, which takes a string as input and returns a Ruby hash that the JSON represents.
Example:
user = JSON.parse(@response.body)
assert_equal "Mike", user['name']

A: Rails has JSON support built in:
def json_response
    ActiveSupport::JSON.decode @response.body
end

No need for a plugin
Then you can do something like this:
assert_equal "Mike", json_response['name']

A: If you are using RSpec, json_spec is worth a look
https://github.com/collectiveidea/json_spec

A: Also for short JSON responses you can simply match a string of the JSON to @response.body. This prevents having to rely on yet another gem.
assert_equal '{"total_votes":1}', @response.body

A: In newer versions of rails, you can leverage parsed_body to get access to this in your tests without any work.

Calling parsed_body on the response parses the response body based on the last response MIME type.
Out of the box, only :json is supported. But for any custom MIME types you've registered, you can add your own encoders...

https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/IntegrationTest.html

A: None of the answers provides a nice maintainable way to verify a JSON response. I find this one to be the best:
https://github.com/ruby-json-schema/json-schema
It provides a nice implementation for the standard json schema
You can write a schema like:
schema = {
    "type"=>"object",
    "required" => ["a"],
    "properties" => {
        "a" => {
            "type" => "integer",
            "default" => 42
        },
        "b" => {
            "type" => "object",
            "properties" => {
                "x" => {
                    "type" => "integer"
                }
            }
        }
    }
}

and use it like: JSON::Validator.validate(schema, { "a" => 5 })
Best way to verify it against my android client implementation.

A: Actually, you can use implicitly the JSON module:
assert_equal assigns(:user).to_json, @response.body

A: As noted, you use JSON.parse to test the JSON, but where you perform that assertion depends on how you are rendering the JSON.
If you are generating the JSON in the controller, you parse the JSON in controller functional tests (as the other answers are showing). If you are rendering JSON, with a view using Jbuilder, rabl or another gem that takes this approach, then parse the JSON in the view unit tests not the controller functional tests. Unit tests are generally faster to execute and easier to write - e.g., you can build models in-memory rather than create them in the database.

A: You can use the AssertJson gem for a nice DSL which allows you to check for keys and values which should exist in your JSON response.
Add the gem to your Gemfile:
group :test do
  gem 'assert_json'
end

This is a quick example how your functional/controller test could look like (the example is an adaption from their README):
class ExampleControllerTest < ActionController::TestCase
  include AssertJson

  def test_my_action
    get :my_action, :format => 'json'
    # => @response.body= '{"key":[{"inner_key":"value1"}]}'

    assert_json(@response.body) do
      has 'key' do
        has 'inner_key', 'value1'
      end
      has_not 'key_not_included'
    end
  end

end

You just have to include the AssertJson module in your test and use the assert_json block where you can check the response for existent and non-existant keys and values. Hint: it's not immediately visible in the README, but to check for a value (e.g. if your action just returns an array of strings) you can do
  def test_my_action
    get :my_action, :format => 'json'
    # => @response.body= '["value1", "value2"]'

    assert_json(@response.body) do
      has 'value1'
      has 'value2'
      has_not 'value3'
    end
  end


text:
Q: Live updating message in tkinter I have been learning python for a few weeks now, and decided to get into tkinter and GUI scripting. It is easy enough to follow along with tutorials, but the best way to learn is by doing it yourself. I decided to make a simple press the button get money, and it is all set up, but I cannot have it print out a live update of how many points you have. If anyone could help me that would be swell. Thanks in advance! :)
P.S. everything works except for the "you have somthing money" part so don't question the rest. It is referenced in other parts
class SellPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        WelcomePage.configure(self, background='#08FFC7')

        def makeMoney():
            x = random.randint(1,100)
            global money
            if x == 100:
                money = money + 5
            else:
                money = money + 1

        label1 = ttk.Label(self, text="Begin making money!", font=LARGE_FONT)
        label1.pack()
        button1 = ttk.Button(self, text="Make money!", command=makeMoney)
        button1.pack()
        label2 = ttk.Label(self, text="You have "+str(money)+" dollars!")
        label2.pack()


text:
Q: Why is Vue putting my element body in an attribute? This is my template for "Guess":
<template>

    Kevin was here:{{ value }}

</template>

But the produced HTML looks like this actual output:

 Kevin was here:

Expected output:

 Kevin was here: Kevin

Here's how I'm using the template:

data: () => ({
  guesses: [
    "Kevin",
    "Apple",
    "",
    "",
    "",
    "",
  ]
}),

<Guess
  v-for="(guess, i) in guesses"
  :key="`guess-${i}`"
  :label="`guess-${i}`"
  :value="guess"
/>

A: A commenter asked if I'd registered the Guess component.  I had not.  Thank you.
This fixed it:

A: On your component usage, you injected dependencies just fine as below
<Guess
  v-for="(guess, i) in guesses"
  :key="`guess-${i}`"
  :label="`guess-${i}`"
  :value="guess"
/>

then inside this component how do you pickup these dependencies to that you can use em'?... as you've guessed, you need props
<template>

    Kevin was here:{{ value }}

</template>


text:
Q: Getting error when I am trying to fetch my main url patterns I am a beginner in Django I have created a Django project in that I have included two more application when I did add urls.py file in both Applications both are working well but when I am fetching my main admin URL it is giving an error
Page not found (404)
Request Method: GET
URL:    http://127.0.0.1:8000/
the URLconf defined in mac.urls, Django tried these URL patterns, in this order:

admin/
shop/
blog/
The empty path didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to
 False, and Django will display a standard 404 page.

when I am fetching this URL in http://127.0.0.1:8000/ i am getting an error it is working for http://127.0.0.1:8000/shop/
here is my main urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls')),
]

A: Your django app has 3 routes:
http://127.0.0.1:8000/admin/ goes to django admin app
http://127.0.0.1:8000/shop/ goes to your shop app
http://127.0.0.1:8000/blog/ goes to your blog app
And since you have no configuration for http://127.0.0.1:8000, you see an error instead.
You can see that in the error, when django tries to match your url with list of available urls.
If you want to get admin app on url http://127.0.0.1:8000, change urls.py to:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('', admin.site.urls),
path('shop/', include('shop.urls')),
path('blog/', include('blog.urls')),
]

It's generally not advisable to set admin app at root url - it has it's own system of urls inside (admin/<app_name>/<model_name>), so chances are it will shadow your urls and make the unreachable.

A: Create a view that will be your front page.
From there you should link to the other areas of your website.
Don't direct that to admin, that's ridiculous.

A: You've created a Django project and started two apps. You should have a project-level urls.py file and then an app-level urls.py file for each of your apps.
To explain that in greater detail lets say our Django project is called config and our two apps are called app1 and app2. Your project-level urls.py file, which will be located at config/urls.py, could contain the following:
    # config/urls.py

    from django.contrib import admin
    from django.urls import path, include
    from django.views.generic.base import TemplateView

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', TemplateView.as_view(template_name='home.html'),
            name='home'),
        path('app1/', include('app1.urls')),
        path('app2/', include('app2.urls')),
    ]

In this file we specify a route for our admin panel, which on your local server will be located at http://127.0.0.1:8000/admin. We've also specified a home route, the second path with the empty string. This means when you navigate to http://127.0.0.1:8000/ you will be directed to your home page (for the example above I just used a generic built-in view). It's not a good idea to route immediately to your admin panel.
We've also included paths to our other two apps. What these two lines essentially say is: "include the urls from this other app". Now we need to create two urls.py files, one for each of our apps. In this example I'll just focus on the urls.py file for app1:
    # app1/urls.py

    from django.urls import path
    from .views import AppContentView

    urlpatterns = [
        path('content/', AppContentView.as_view(),
            name='app_content'),
    ]

This is a view that you would have to create, but what we've now done is we've created one path that will be located at http://127.0.0.1:8000/app1/content. In fact any new paths we create in this file will always begin with http://127.0.0.1:8000/app1/, because we've already told Django in our project-level urls.py to include the urls from the app1 urls.py file so we've essentially prefixed all of these paths with /app1/.
If you think of urls configurations like a tree it might help too:
                  Project Level Url Configs.
                              |
                              |
                              |
                 ___________________________
                 |                          |
                 |                          |
          App 1 Url Configs.          App 2 Url Configs.


text:
Q: Unable to update git config: failed to lock file [home]/snap/gitkraken/137/.gitconfig.lock' for writing: So I installed the latest version of Gitkraken(v5.02) and wanted to try the new gpg key feature. Firstly, the documentation says that if you have an existing key, gitkraken will automatically use it, but mine doesn't.
Also, when in the gpg settings menu, I chose the sign commits by default option,

I get the following error:

Though I tried deleting the .gitconfig.lock file and even reinstalled gitkraken, I can't get it to work.
Am I missing something obvious?
EDIT: I installed gitkraken using snap:
sudo snap install gitkraken

A: I asked this question on the gitkraken help slack channel. They suggested using the .deb installer instead of snap. It worked exactly as expected.
The .deb installer fixes both the auto-detection of gpg keys problem as well as the "failed to lock file problem".
In the same chat, someone else responded that snap probably was n't working properly due to the issue of sandboxing.
The issue with snap may be solved in more recent updates from gitkraken.


text:
Q: How to retrieve a succession of text messages/status reports from a PHP script that is the action of a form submission? I have a form that currently is processed by an action in a PHP script when submitted. The PHP script contains a number of procedures that take time to process. I'd like to print to the parent script (the one with the form, which remains visible on screen until the PHP script is finished) status reports from the PHP script, e.g.:

Procedure 1 has begun... Procedure 1 is finished.
Procedure 2 has begun... Procedure 2 is finished.
Procedure 3 has begun... Procedure 3 is finished.

etc.
I understand that the primary way to do this is by intercepting the form submission with an AJAX call, like this:
$('#formID').on('submit',function(e){
    e.preventDefault();
    $.ajax({
        type     : "POST",
        cache    : false,
        url      : $(this).attr('action'),
        data     : $(this).serialize(),
        success  : function(data) {
            // do something with the returned data from the PHP script
        }
    });
});

However, that would seem just to return/report the return value (echo message, etc.) from the PHP file that is called by the form. I want a series of messages to be returned to the parent form indicating the progress of the PHP script as it processes values from the form.
For reasons I don't fully understand, the form page remains visible until the PHP action is completed, at which point the page is redirected to a different page in the site by use of a header() directive at the end of the PHP script. (The code was originally written by a different developer; my understanding of his routine is imperfect. The submit() is called within a JQuery PLUpload function, which may or may not be why the form page remains on screen until the PHP action script is finished.)
Without breaking up the PHP form processing into a series of individual scripts, each processed separately, how can I use AJAX (or another technique) to intercept the default form processing and execute the PHP processing script such that status text messages may be echoed to the screen or appended as styled text on
 elements in the form page? (The PHP processing script relies on a series of variables that are derived from the values on the form, and it would be inelegant, to say the least, to have to recreate them in a succession of individual PHP files called sequentially, since the current PHP form processing script is efficient and works fine, albeit slow because of the nature of its operations.)

A: On my localhost, and perhaps on many live servers, the solution requires a header <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> followed by while (@ob_end_flush()); and then an explicit flush(); after each text echo. A simple example of this would be this short routine:
<?php
header( 'Content-type: text/html; charset=utf-8' );

while (@ob_end_flush());

function sendMsg($msg) {
    echo $msg;
    flush();
}

function sleep_test($sleep_time) {

    $x = "Beginning process:
";
    sendMsg($x);
    $y = "Waiting $sleep_time seconds ...
";
    sendMsg($y);
    sleep($sleep_time);
    $z = "Done.

";
    sendMsg($z);

}

sleep_test(1);
sleep_test(2);
sleep_test(3);
?>

However, I'm on a shared hosting plan on my live server whose admin settings (i.e., those I cannot alter via php.ini and Apache overrides, etc.) will not display its text until it is entirely processed; only then will the buffer be fully flushed. The script above works perfectly on my XAMPP and WAMP localhosts, and should for anyone else's, but if it doesn't and you're trying to get this kind of performance on your live host, then if this script doesn't flush the buffer until it is fully processed, it may not be possible; contact your liveserver's admin for info.
For my purposes, a very carefully constructed set of AJAX calls worked for the processing script from which I desired status text updates as the processing proceeded.


text:
Q: Querystring to optional arguments I have a querystring with a number of optional values eg.
/filter?location=scotland&minprice=100&maxprice=500

I have a filter method with a number of optional arguments
public List<result> Filter(
    bool isVisible = false,
    string location = null,
    int? minPrice = null,
    int? maxPrice = null,
)

I would like to use the querystring values as arguments on the filter method, but I can't think of a good way to do this.
The best way I can come up with is to use ?: conditions for each argument
var results = Filter(
   (Request.QueryString["isvisible"] != null ? Request.QueryString["isvisible"] == "true" : false)

and so on...
but using this method, if a particular querystring value hasn't been set, I have to pass in a default value, but I don't want to pass in a default, I want defaults to be set from within the filter method.
Is there a way to do this?  Or is there a better way to achieve the same thing?

A: Sounds like you just need to map the defaults.
There are actually two "interfaces" here: the interface from the caller to the Filter() method and the interface from the Filter() method to the data source. They don't have to have the same defaults.
public List<Whatever> Filter(string criteria1 = null, string criteria2 = null)
{
    criteria1 = criteria1 ?? SYSTEM_DEFAULT_FOR_CRITERIA1;
    criteria2 = criteria2 ?? SYSTEM_DEFAULT_FOR_CRITERIA2;

    return _dataSource.GetData(criteria1, criteria2);
}


text:
Q: Is there a way to use >, = or in a C# switch? I'm looking for ways to tidy a small section of code Here's the code that I have:
if (spc > 1)
{
   if (shpc == 0)
      return "You have " + spc.ToString() + " visible cards in your card deck. ";
   if (shpc == 1)
      return "You have " + vc.ToString() + " visible and 1 hidden card in your deck. ";
    return "You have " + vc.ToString() + " visible and " + shpc.ToString() + " hidden cards in your deck. ";
 }
 return null;

Does anyone know of a way I can code this with a switch or another way I could tidy the code?

A: I don't think it would make it tidier; switch statements are pretty ugly. But if you really want to, you could do something like this:
string Output = null;
switch(shpc)
{
    case 0: Output = $"You have {spc} visible cards in your card deck."; break;
    case 1: Output = $"You have {vc} visible and 1 hidden card in your deck."; break;
    default: Output = $"You have {vc} visible and {shpc} hidden cards in your deck."; break;
}
return Output;

EDIT.
As suggested by Franck in the comments, case 1 could be omitted in favor of a smarter default case:
$"You have {vc} visible and {shpc} hidden card{(shpc > 1? "s":"")} in your deck."

You could also omit the Output variable and return from the switch directly. None of this things would make it clearer IMO, so I wouldn't bother.

A: This is an opportunity to step back and refactor.  What's the problem?  Pluralization is the problem, so start with that.
private static string[] words = {"no", "one", "two", "three" };
public static string Pluralize(this string t, int q)
{
  string s = q == 1 ? "" : "s";
  string n = q < words.Length ? words[q] : q.ToString();
  return n + " " + t + s;
}

Can you see how you can use this to make your code look more like its meaning?

A: Why polluting some easy to read code by some fancy syntax? But if you really want, you may use a chained ternary operator.
if (spc > 1)
{
    return
        shcp == 0 ? "You have " + spc.ToString() + " visible cards in your card deck. " :
        shpc == 1 ? "You have " + vc.ToString() + " visible and 1 hidden card in your deck. " :
                    "You have " + vc.ToString() + " visible and " + shpc.ToString() + " hidden cards in your deck. ";
 }
 return null;

You can further delete all those ToString-calls, as they are implictely added anyway when concatenating strings and objects.

A: Assuming that spc and vc are the same thing (you forgot to clean the code up for us) this is the holy grail that you asked for, which I however don't particularly like. Full localizable sentences are preferred in my world.
if (vc > 0)
    return $"You have {vc} visible {shpc > 0 ? $"and {shpc} hidden " : ""}card{vc > 1 && shpc == 0 || shpc > 1 ? "s" : ""} in your deck. ";

A: How about:
if(shpc < 2)
  return null;

if (vc == 0 && hc == 0)
  return "You have no cards in your deck"
if (vc == 0)
  return $"You have {hc} hidden card{S(hc)} in your deck";
if (hc == 0)
  return $"You have {vc} visible card{S(vc)} in your deck";

return $"You have {vc} visible and {hc} hidden card{S(hc}} in your deck";

//a cheapo pluralize method.
private string S(int i){
  return i == 1 ? "": "s";
}

I've always preferred things that format string to be as readable (fewest string concats) as possible. Feel free to chop some of these out if for example you can never have an empty deck or a deck that has only hidden cards ; not sure what the rules of this game are
If you invert the logic of your if(shpc) you can avoid nesting. I've used another variable hc for the count of hidden cards - I couldn't work out if this was shpc or not, and there was a bit of confusion over consistency of spc/shpc/vc?
If you ever plan on translating your game into another language, don't do any of this. Take a look at something like i18next instead
Perhaps see also Clever way to append 's' for plural form in .Net (syntactic sugar)

A: This is a refactoring of your code using C# 6.0 string interpolation, C# 7.0 pattern matching and a C# 8.0 switch expression which answers your (purely syntactical) question. There are lots of other ways of doing it, I'm just giving a hint what's possible with modern C# language features. Whether it actually makes sense, depends on your business context. At the very least, the more concise syntax makes it easier to spot any logical problems; e.g. is it correct that you sometimes use spc and at other times vc to indicate the number of visible cards?
return shpc switch{
    _ when spc <= 1 => null,
    0 => $"You have {spc} visible cards in your card deck. ",
    1 => $"You have {vc} visible and one hidden card in your deck. ",
    _ => $"You have {vc} visible and {shpc} hidden cards in your deck. "
};


text:
Q: Does -XStrict do anything in GHC? I thought -XStrict was supposed turn GHC into a Strict Haskell, so I tried the infinite Fibonacci sequence test
my_zipWith f  x [] = []
my_zipWith f []  y = []
my_zipWith f (x:xt) (y:yt) = f x y : my_zipWith f xt yt

test_fibs n =
    let fibs = 0 : 1 : my_zipWith (+) fibs (tail fibs) in
    take n fibs

main = do
        putStr $ show $ test_fibs 15

to see if it would blow up in memory, but it doesn't:
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.0.2

$ ghc -XStrict fibs.hs && ./fibs
[1 of 1] Compiling Main             ( fibs.hs, fibs.o )
Linking fibs ...
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]

What am I doing wrong?

A: Strict pragma certainly let GHC evaluate everything strictly, but into only Weak Head Normal Form. For example:
(a, b) = (error "a", error "b")

If above code exists under Strict pragma, any error arises. Let's see your code:
test_fibs n =
    let fibs = 0 : 1 : my_zipWith (+) fibs (tail fibs) in
    take n fibs

fibs called recursively but in list cons, so now whole list is WHNF. That is reason why your code didn't stack.
This post will help you also. Enjoy recursion and laziness!
Add:
An easy way, to use deepseq:
{-# LANGUAGE Strict #-}
import Control.DeepSeq

my_zipWith f  x [] = []
my_zipWith f []  y = []
my_zipWith f (x:xt) (y:yt) = force $ f x y : my_zipWith f xt yt

test_fibs :: Int -> [Int]
test_fibs n =
    let fibs = 0 : 1 : my_zipWith (+) fibs (tail fibs) in
    force $ take n fibs

main = do
        putStr $ show $ test_fibs 15

force defined as force x = x `deepSeq` x, deepSeq evaluate an expression deeply literally to NF (Normal Form). This conversion is achieved with GHC.Generics. If convert manually, just have to evaluate inside of data, so can rewrite following:
{-# LANGUAGE Strict #-}

my_zipWith f  x [] = []
my_zipWith f []  y = []
my_zipWith f (x:xt) (y:yt) = f x y : go
    where
        go = my_zipWith f xt yt

test_fibs n =
    let
        fib2 = my_zipWith (+) fibs (tail fibs)
        fibs = 0 : 1 : fib2
    in
        take n fibs

main = do
        putStr $ show $ test_fibs 15

But they can't stack actually. Because GHC can detect infinite loop, but it's another story.


text:
Q: Need help in FORMAT function I wrote a code and want to convert the value like if user write 12, it should be converted into "12.00"
Reffered link
I referred the link above and got a "Format" function but when I tried it in my project, it converts the value into "0.00"
My code I written below...
    Private Sub txtDisc_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtDisc.KeyDown
    If e.KeyCode = Keys.Return Then
        txtDisc.Text = Format(txtDisc.Text, "0.00")
        txtOpeningBal.Focus()
    End If
End Sub

Please help me if I made any mistake in writing the code..
I am totally new with this function and also seen msdn helps but cannot understand it properly...

A: You need to convert the string txtDisc.Text to a numeric value, before passing it to the Format() method.
You could do something like:
txtDisc.Text = Format(Val(txtDisc.Text), "0.00")

Or you could parse the value, and use the .Net methods (rather than the VB6 compatibility methods), so something like:
Dim disc As Double
If Double.TryParse(txtDisc.Text, disc) Then
    txtDisc.Text = string.Format("{0:N2}", disc)
End If

A: First, you must parse your text input to get a numeric value. Then you can format it as you wish.
   txtDisc.Text = Format(Val(txtDisc.Text), "0.00")

Note: Val function is old approach, recommended one is through Double.Parse(), but I think in this simple example, you don't care.

A: You have to cast the text value to a number (double perhaps?) to perform format against.
Check this example:
Sub Main()
        Dim s As String = "12"
        Dim d As Double = Double.Parse(s)

        Console.WriteLine(d.ToString("#,##0.00"))
        Console.WriteLine(d.ToString("C1"))
        Console.WriteLine(d.ToString("C3"))
        Console.WriteLine(String.Format("{0:C2}", d))
        Console.WriteLine(String.Format("{0:C5}", d))

        Console.ReadLine()
    End Sub

"C" is for currency


text:
Q: How to add OCSP stapling in Golang server? This is how I configured my golang server:
func main() {
    ....
    config := &tls.Config{
        MinVersion: tls.VersionTLS12,
        PreferServerCipherSuites: true,
    }
    server := &http.Server{Addr: ":"+port, Handler: router, TLSConfig: config}
    err = server.ListenAndServeTLS(cert, key)
    ....
}

but our security vendor complaining on:

The server does not support OCSP stapling

How exactly to implement this?


text:
Q: Hide legend elements in ggplot2 I am trying to plot the parameter estimates and levels of hierarchy from a stan model output. For the legend, I am hoping to remove all labels except for the "Overall Effects" label but I can't figure out how to remove all of the species successfully.
Here is the code:
ggplot(dfwide, aes(x=Estimate, y=var, color=factor(sp), size=factor(rndm),
                   alpha=factor(rndm))) +
  geom_point(position =pd) +
  geom_errorbarh(aes(xmin=(`2.5%`), xmax=(`95%`)), position=pd,
                     size=.5, height = 0, width=0) +
  geom_vline(xintercept=0) +
  scale_colour_manual(values=c("blue", "red", "orangered1","orangered3", "sienna4",
                               "sienna2", "green4", "green3", "purple2", "magenta2"),
                      labels=c("Overall Effects", expression(italic("A. pensylvanicum"),
                               italic("A. rubrum"), italic("A. saccharum"),
                               italic("B. alleghaniensis"), italic("B. papyrifera"),
                               italic("F. grandifolia"), italic("I. mucronata"),
                               italic("P. grandidentata"), italic("Q. rubra")))) +
  scale_size_manual(values=c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1)) +
  scale_shape_manual(labels="", values=c("1"=16,"2"=16)) +
  scale_alpha_manual(values=c(1, 0.4)) + guides(size=FALSE, alpha=FALSE) +
  ggtitle(label = "A.") +
  scale_y_discrete(limits = rev(unique(sort(dfwide$var))), labels=estimates) +
  ylab("") +
  labs(col="Effects") + theme(legend.title=element_blank())

A: The key points you need to notice is that remove part of the labels in legend can't be achieved by the function in ggplot2, what you need to do is interact with grid, which more underlying since both lattice and ggplot2 are based grid,to do some more underlying work, we need some functions in the grid.
To remove part of the labels in legend, there are three functions need to be used, they are grid.force(), grid.ls() and grid.remove() . After draw the picture by ggplot2, then using grid.force() and grid.ls(), we can find all the elements in the  picture, they all are point, line, text, etc. Then we may need to find the elements we are interested, this process is interactive, since names of the element in ggplot2 are made by some numbers and text, they are not always meanful, after we identify the names of the element we are interested, we can use the grid.remove() function to remove the elements, blew is the sample code I made.
    library(grid)
    library(ggplot2)
    set.seed(1)
    data <- data.frame(x = rep(1:10, 2), y = sample(1:100, 20),
                       type = sample(c("A", "B"), 20, replace = TRUE))

    ggplot(data, aes(x = x, y =y,color = type))+
      geom_point()+
      geom_line()+
      scale_color_manual(values = c("blue", "darkred"))+
      theme_bw()

until now, we have finished draw the whole picture, then we need to do some works remove some elements in the picture.
    grid.force()
    grid.ls()

grid.ls() list all the element names
    grid.remove("key-4-1-1.5-2-5-2")
    grid.remove("key-4-1-2.5-2-5-2")
    grid.remove("label-4-3.5-4-5-4")

A: It's not perfect, but my solution would be to actually make two plots and combine them together. See this post where I lifted the extraction code from.
I don't have your data, but I think you will get the idea below:
library(ggplot2)
library(gridExtra)
library(grid)

#g_table credit goes to https://stackoverflow.com/a/11886071/2060081

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

p_legend = ggplot(dfwide[sp=='Overall Effects'], aes(x=Estimate, y=var, color=factor(sp),
size=factor(rndm),
                   alpha=factor(rndm))) +
  geom_point(position =pd) +
  geom_errorbarh(aes(xmin=(`2.5%`), xmax=(`95%`)), position=pd,
                     size=.5, height = 0, width=0) +
  geom_vline(xintercept=0) +
  scale_colour_manual(values=c("blue"),
                      labels=c("Overall Effects"))) +
  scale_size_manual(values=c(3)) +
  scale_shape_manual(labels="", values=c("1"=16,"2"=16)) +
  scale_alpha_manual(values=c(1, 0.4)) + guides(size=FALSE, alpha=FALSE) +
  ggtitle(label = "A.") +
  scale_y_discrete(limits = rev(unique(sort(dfwide$var))), labels=estimates) +
  ylab("") +
  labs(col="Effects") + theme(legend.title=element_blank())

p_legend = g_legend(p_legend)
One of your plots will just be the legend. Subset your data based on the Overall Effects and then plot the two plots together as a grid.


text:
Q: How can I compile a C++ project (with g++) to use on other computers? This may be obvious, but I want to make sure what to do before I do anything rash. I want to compile my C++ program, libraries and all, to a release executable such that the file can be run on any computer (running the same OS). Right now, I'm on Mac OS X (10.7.4) and I need to be able to run my executable on other Macs. The problem is I am using the OpenCV library in my project, and I only have it installed on this computer. Is there a way to compile with g++ such that if I open this program on a computer that doesn't have the OpenCV library installed, it will work anyway? As in, build all the dependencies into the executable. Or does this happen automatically?
I am also quite new to the ".o" object files, so can those have anything to do with it? I would prefer a way to get it all into a single file, but I'll settle for a package as long as it works.
Thank you.

A: To expand on molbdnilo's answer, you'll need to create an application bundle (see the Apple Bundle Programming guide).  You'll need to move your console application to MyApp.app/Contents/MacOS/MyApp.  There's also a Frameworks directory in which you'll need to add the OpenCV library as a framework.  See the OpenCV Wiki for some information on the OpenCV framework.  A framework (at its simplest) is pretty much a dynamic library wrapped in a particular directory structure.
I would suggest looking into using Xcode on the mac as it simplifies the construction of bundles and linking to frameworks compared to doing it yourself via scripting and Makefiles.

A: There are two ways to do this.  You can static link if you aren't going to run into licensing issues with any of the libraries you are linking to.  This is pretty easily handled by using g++ -o myApp -static -lopencv myapp.cpp  However, this also depends on static libraries existing for the libraries you want to link to.  Most distribute static libs with the shared libs these days.
The other way is to distribute the shared libraries and tell your application to force it to look in a certain spot for the shared library using -rpath.  Note:  I am telling you the Linux way to do this, it will probably work on a Mac but I have no way to test.
So say all of your shared libraries are in the same directory as your executable, you can compile with: g++ -rpath ./ -lopencv -o YourApp yourApp.cpp
I hope this helps.


text:
Q: Multiple THEN for same CASE condition with union in MySQL I have a table with data some like
  table : foo
 ---------------------------------
 id  | A1 | B1 | C1 | D1 | A2 | B2 | ........ so on
 ----------------------------------
 abc | 2  | 4  | 6  | 7  | 3  | 4  |......... so on
 -----------------------------------

output i needed is
 id  |  Value
 ------------
 abc |  2  |
 abc |  4  |
 abc |  6  |
 abc |  7  |
 abc |  3  |
 abc |  4  |

   ....and so on

Query i prepared
 select case when id='abc' then A1 else 0 end from foo
 union all
 select case when id='abc' then B1 else 0 end from foo
 union all
 select case when id='abc' then C1 else 0 end from foo
 union all
 select case when id='abc' then D1 else 0 end from foo
 union all
 select case when id='abc' then A2 else 0 end from foo
 union all
 select case when id='abc' then b2 else 0 end from foo

 .... and so on

i dont want my query to be so long, i want to make it dynamic with simple and short query is it possible.

A: You don't need a case statement for this
drop table if exists t,t1;

create table t(id varchar(3),a int,b int, c int);

insert into t values
('abc',1,2,3),('def',4,5,6);

select id,a value from t
union all
select id,b from t
union all
select id,c from t
order by id;

+------+-------+
| id   | value |
+------+-------+
| abc  |     1 |
| abc  |     2 |
| abc  |     3 |
| def  |     4 |
| def  |     5 |
| def  |     6 |
+------+-------+
6 rows in set (0.00 sec)

BUT you do potentially have problems - with your design you cannot tell which row came from column a (column b column c etc).
In order to force row ordering in column order (from left to right) you would need a column to hold the ordinal position so that you can order by that
select id,1 as col,a value from t
union all
select id,2,b from t
union all
select id,3,c from t
order by id,col;

Ignoring problems for now if you the number of columns can change and you don't want to recode then using prepared statements , possibly in a procedure may do https://dev.mysql.com/doc/refman/8.0/en/sql-syntax-prepared-statements.html
set @sql =
(
select group_concat(
         concat('select id,', column_name, ' as value from t union all ')
         )
from
(
select table_name,column_name
from information_schema.columns
where table_name = 't' and table_schema = 'sandbox' and column_name <> 'id'
) s
);

set @sql = (select replace(concat(substring(@sql,1,length(@sql) - 11),';'),',select','select'));

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

A: As already suggested by P.Salmon.
We need to use dynamic sql and to know from which column the value returns you can also add the column name in the select statement.
Query:
select
    group_concat(concat("select id, '", column_name, "' as col_name, case when id = 'abc' then ",
        column_name, " else 0 end as col_value from foo")
        separator '\nunion all\n')
        into @pivotcol
from (select column_name from information_schema.columns
        where table_name  = 'foo' and column_name <> 'id') t;

prepare stmt from @pivotcol;
execute stmt;
deallocate prepare stmt;

Result:

id  | col_name | col_value
:-- | :------- | --------:
abc | A1       |         2
abc | B1       |         4
abc | C1       |         6
abc | D1       |         7
abc | A2       |         3
abc | B2       |         4

db<>fiddle here


text:
Q: Responsive resizing I have a div which contains the following layout (top image): http://tinypic.com/r/287eu88/8
I am trying to work out how to move the elements to the configuration shown in the bottom image on resize/ on mobile devices but I can't work it out.
Here is the jsfiddle: http://jsfiddle.net/9DZSA/1/
If someone could point me in the right direction that would be good, I am a beginner so my code is probably not very good so any pointers would be great too!
Thanks!
"Links to jsFiddle.net must be accompanied by code" - Well I am not targetting a specific element but here is the html to satisfy the requirement:

     LATEST PROJECT

aboutaboutabout

Insert Project Name

Out believe has request not how comfort evident.

Extremity sweetness difficult behaviour he of.

With my them if up many.

Design

Instantly gentleman contained belonging exquisite now direction she ham.

        tH5">Accuracy & Details

Its hence ten smile age means. Seven chief sight far point any.

Posibilities

Children me laughing we prospect answered followed.

A: There are few possible ways to do it. You can select according to your need

*

*You can use media queries in which you define different stylesheets for different screens. This is the most used way currently. Sneak Peek:
  http://css-tricks.com/css-media-queries/ and
  https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

*You can use the viewport meta tag. Sneak Peek:https://developer.mozilla.org/en/docs/Mozilla/Mobile/Viewport_meta_tag

*You can design everything in % (fluid responsive) but that part is very tricky. From my experience I can say that designing a full
  website giving everything in % is very difficult.

I will suggest you to learn media query. Its quite simple and reliable.

A: You will have to take a look at media queries.
Media queries give you a way to target certain CSS properties only to specific media properties (including of course the viewport size, but also if it's print, or black and white, and so on).
Many people would suggest that you begin with a mobile-first approach, that is, you start by applying the CSS for the mobile, minimal version, and apply media queries at break points as your viewports get wider, enclosing your CSS like so:
@media (min-width: 480px){
   /* CSS goes here */
}


text:
Q: Can this code work or not Can the code below work or not to retrieve data from database and display.. I know that the sql4 can't work  in a mysql database can the php code below make it work or not.
<?php

include 'connect.php';
$sql2 = "SELECT * from pm Order by mid";

while ($row3 = mysql_fetch_array($sql2)) {
   $sql4 = mysql_query("SELECT * FROM reply ORDER BY mid =".$row3["$mid"]."  ");
   $row4 = mysql_fetch_array($sql4);
   echo"<trid='".$mid."'>	     ".$row['mid']."

".$row['reply']."
";
}

?>

esp. this mysql or mysql and php combined. Basically is the code below improper. I think it is.
<?php

$sql4 = mysql_query("SELECT * FROM reply ORDER BY mid =".$row3["$mid"]."  ");

?>

A: Put the following at the top of your PHP file and try it out yourself:
<?php

error_reporting(-1);
ini_set("display_errors", true);

// Your code goes here

?>

(I think the code is self-explaining)

A: Try...
$sql2 = "SELECT * from pm Order by mid";

$result = mysql_query($sql2); <- MISSING THIS LINE

while ($row3 = mysql_fetch_array($result))
    {
    // OTHER CODE HERE
    }


text:
Q: Does Ubuntu damage USB drives? Whenever I unmount a USB drive with Nautilus and plug it to a Windows machine, I receive a warning that the drive needs to be repaired.

(the same message like in this screenshot)
For 10+ years working with windows I never had a corrupted or damaged USB drive but during the last two years three of my USB drives became inoperative, so I cannot prove it, but it's obvious that this is related to Ubuntu's (un)mount behavior.
A friend told me I can prevent such damage using udisks and sync, but I hope this is not the way to do it, mounting drives with shell commands in 2016.

A: This is mostly an issue with Windows. It thinks it is the only OS in the world and acts out if it detects something it does not understand.
Just because Windows says you must repair the drive does not make it true.
Any of my drives used with Ubuntu get this message from Windows, I just say no and they work fine with Windows.
In short there is nothing wrong with the drive, it is just there is something on there that Windows does not understand and its response is destroy it.
Don't repair the drive, it will format it without telling you and you will lose all the data on the drive.

A: I've seen lots of usb drives, especially flash (SD, etc) cards in USB adapters, with FAT filesystems (virtually every USB drive comes pre-formatted with FAT32) getting corrupted while using Ubuntu & Ubuntu-derived distros. It was almost a regular occurrence every few months of regular daily use.
If it were a hardware problem, then formatting the partitions with ext3 (or 4) shouldn't help, but ext3/4 makes the filesystems virtually bulletproof. (ext2 also was corrupted over the few months I tried it; was supposed to have less writes so a longer life for flash drives, mainly from no journal).
So, Ubuntu should not physically damage USB drives themselves, but I still don't trust it 100% with FAT filesystems.
I think filesystem corruption can be best avoided by:

*

*Never just unplug a USB drive until after it's been unmounted/umount/ejected. Even if the drive's not currently writing anything (if it has a light it's not flashing) and even if you've done a sync the filesystem may still

*Wait at least a few seconds after umount/eject before unplugging it. It seems that even after umount the drive's activity light may sometimes keep flashing for a little while. Other users like this guy say it could go on for up to a minute.

*Don't only rely on only sync either, like this guy who got file corruption.

Related (generally) links:

*

*Answer to "Should I unmount a USB drive before unplugging it?"

*Is execution of sync(8) still required before shutting down linux?

*How to remove a USB drive without worrying if its been unmounted?

A: This has little to do with any operating system. This is a file system error, which in most cases indicates that the drive was not unmounted properly (user error). It is not an absolute indication of damage, it merely indicates a possibility of a damage. If present, the damage is usually limited to the last written file(s). Windows "Repair" command in this case scans the drive for sectors marked as "occupied", but not assigned to any file and then assigns this scraps and pieces to new files.
This error can be also created on Windows, if you just yank out the drive during write without unmounting it first (in Windows "Eject" performs the unmount).
Seeing this message means that the drive was not unmounted properly.
You can verify on your own if the file system was really damaged or is it just false positive: if after running "Repair" a new folder named like "found000" appears with some files in it, it means there really was an unfinished write that got interrupted. Some of your data were lost, and that is a concern.

A: I use several years ubuntu and windows with dual-boot, and when i unmount the drive the correct way, in windows always show up the error message, but never was error on my usb drive. In W10 you can turn off this pop-up error message.

A: As you suggested in a comment, this is possibly related to Ubuntu not completing the write process before you remove the flash drive. Ubuntu writes the files to RAM during the copying process, and writes these files from the buffer to the USB drive in the background after the copying dialog is closed. There's another answer that suggests this is especially a problem for machines with large amounts of memory, but it's likely that you're removing the drive before the background write is complete. When you eject a drive, this forces the buffer to be written to disk, but it is difficult to tell when the write is actually completed. There's a pop-up in newer versions (15.10 for certain, possibly 15.04) intended to remedy this -- a purple alert appears after some (generally short) time that says something along the lines of "[Drive] can now be removed" once the write is finished.
This is probably the reason your friend suggested sync. Running sync in terminal forces all buffered data to be written to disk, and should return only once the writes are completed (See this answer). See this answer for a utility that will help you determine if this is actually the problem.

A: No worries Ubuntu did not damage your USB drive. But we do not use poorly documented bit flags of a FAT32, FAT16, or NTFS filesystem. On Windows these flags indicate a possibly corrupted filesystem when we had not properly unmounted the drive or an I/O error had occured.
Those bits are located in a reserved entry of a FAT partition table. According to an internal Microsoft paper of 2004 the purpose of these bits are:

*

*ClnShutBitMask:
  If bit is 1, the volume is "clean". The volume can be mounted for
  access. If bit is 0, the volume is "dirty" indicating that a FAT file
  system driver was unable to dismount the volume properly (during a
  prior mount operation). The volume contents should be scanned for
  any damage to file system metadata.

*HrdErrBitMask:
  If this bit is 1, no disk read/write errors were encountered.
  If this bit is 0, the file system driver implementation encountered a
  disk I/O error on the volume the last time it was mounted, which is an
  indicator that some sectors may have gone bad. The volume
  contents should be scanned with a disk repair utility that does
  surface analysis on it looking for new bad sectors.

There was some discussion with the kernel file system developers some years ago on how to overcome this but I was unable to follow up the results. Apparently it did not make it into recent kernels.
As only a bit flag is involved but generally our data should be in perfect shape we can ignore the warning Windows issues on those drives we had previously used in Ubuntu.

A: There is almost no way for any OS could damage USB drive, after a normal format (not the quick), there should be no trace left that drive was ever used with Ubuntu.
Check the drives with "H2testw" or "USB Flash Drive Tester" - bad sectors might be source of many weird errors.

A: I can't say if the drive was "damaged", maybe it was and maybe it wasn't. But as someone who can say the same: "For 10+ years working with windows...", I can tell you that if you're running Windows 10 that could be the source of your new problems. I ran into a new problem my first day on 10: in 10 a database is created for external drives (it might be the indexing database, I don't remember). If that database doesn't match the drive it will tell you that your drive is damaged, sometimes you can ignore this warning and sometimes you can't (see anecdote). Running "repair" will fix the database.
Anecdote:

I can't remember where I found this information but I found out about it when I moved my Music folder. It complained that the drive was broken instead of just complaining about the folder it was looking for not existing anymore. Before I ran repair the new location appeared on Ubuntu and the old location on Windows 10...but all the files couldn't be opened on 10. After I ran repair the new location of the Music folder appeared in Windows, the old folder disappeared, and it worked on Windows again.

Running sync is also not a bad idea.


text:
Q: Flask SQLAlchemy login with postgresql So I have already created a database using the pgadmin3 in postgresql. I have a set of email-ids and passwords. The passwords which I have stored are hashed, i.e. by using pwd_context.hash(password) from the pass.libs.
I have stored them as shown below in the database. Now I have to create another login form in html to authenticate. I am new to flask, but I have seen something called as flask-login. How to compare the password entered in cleartext with the hashed password in database.

A: Flask-login provides a set of functions... for user login,logout and so on. More information on Flask-login can be found at https://flask-login.readthedocs.io/en/latest/.
For creating and checking a password hash: When working with Flask often werkzeug security is used to create/hash and check passwords. A snippet in which this is demonstrated can be found here : http://flask.pocoo.org/snippets/54/
Finally an internet search (I have not used any of these tutorial/pages before) retrieved following page: https://blog.miguelgrinberg.com/post/two-factor-authentication-with-flask with a quick browse of the page I found an example of using flask-login and werkzeug for user-login/logout under the title 'The First Factor: Password Authentication'. A quick pointer when using this tutorial is that there have been some changes in naming since the page has come online. For example flask.ext.login has been renamed to flask_login. The tutorial http://blog.sampingchuang.com/setup-user-authentication-in-flask/ also provides more information on flask-login and werkzeug. The pointer on renaming is also valid for this one.


text:
Q: Python: check if coordinates of values in a grid connect to one another Imagine I have a grid like this:
XXXOO
XXOOX
XXOXX
XXXXX
XXXXX

Which represents a 5x5 grid. The O's have the following coordinates.
dict = {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)}

The O's hang together, so if this grid all the O's "stick" together it should output True.
Following grid the O's don't stick together and should output False
XXXOO
XXOXO
XXOXX
XXXXX
XXXXX

with following coordinates:
dict = {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)}

Here you obviously notice the 2nd row, 3th column and 3th row 3th column aren't connected.
I'm trying out to configure a function that takes care of it, with as input a dictionary, list, tuple...
This is what I have so far the first function just translates my characters/numbers into coordinates. The second function is what I tried so far, but just fails.o I tried to count until a total of 5 if total = 5 (so 5 are connected) it should output True. What I have so far is it always outputs True... which is obvious if you go step by step through the code. But I have no clue how to check if the coords are connected. Taken in mind the coordinates can be given quite random, not from 1-2-3-4-5 but from 4-1-2-5-3
def groups(grid):

    groups = {}
    row = 1;

    for row in range(len(grid)):
        # Make coordinates
        #print("R: " + str(row))
        for column in range(len(grid[row])):
            #print("C: " + str(column))
            number = grid[row][column]
            if char in groups:
                groups[char].add((row,column))
            else:
                groups.update({char:{(row,column)}})

    return groups

def connected(group):
    total = 0;
    for position in groep:
        for position2 in groep:
            if not position == position2:
                if position[0] in position2:
                    total += 1
                    print(total)

    if total == 5:
        connected = True
    else:
        connected = False

    return connected

Any help would be greatly appreciated!

A: Here is a solution using DFS of the graph and a memory of visited nodes:
from random import choice

def test_if_connected(points):
    def neighbours((x, y)):
        candidates = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
        return [c for c in candidates if c in points]

    seen = set()

    # Pick any circle on the grid to start
    frontier = [choice(list(points))]

    while not len(frontier) == 0:
        # Pop the frontier for DFS
        element = frontier.pop()

        # Remember seeing the element to avoid cycles
        seen.add(element)

        # Add unseen neighbours to the search frontier
        frontier.extend([n for n in neighbours(element) if not n in seen])

    # Circles are connected if algorithm terminates having seen all
    return len(seen) == len(points)

# Points represented by circles
connected_points    = set([(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)])
disconnected_points = set([(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)])

print test_if_connected(connected_points) # => True
print test_if_connected(disconnected_points) # => False

It should be clear from the commented code how the answer is achieved, you may wish to become familiar how a depth-first/breadth-first search works elsewhere.

A: Use the label connected components function in skimage. If more than 1 number of components found, not all the O's are connected.
from skimage import morphology
import numpy as np

def connected(grid_size, O):
    grid = np.zeros((grid_size,grid_size))
    for i,j in O:
        grid[i,j] = 1
    numlabels = np.max(morphology.label(grid,4))
    if numlabels == 1:
        return True
    else:
        return False

Os = {(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)}
Os2 =  {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)}

print connected(5,Os)
print connected(5,Os2)

Output
True
False

docs for reference:
http://scikit-image.org/docs/0.8.0/api/skimage.morphology.html#skimage.morphology.label

A: I would implement a "flood fill" function which check each O and call itself recursively if there is an O above, below or an O to the left or right of the current O. You need to make sure you don't recheck O's that you have already checked or you will end up in an endless loop.
When your function returns (from the recursive loop) you may check if there are any unchecked O's left. If so they are not connected.

A: I can't figure out why your code seems so complex when it need to be, Utilizing List-comprehensions and the enumerate() function It didn't seem that complex to find the coordinates of O.
Try this instead:
grid = """
XXXOO
XXOOX
XXOXX
XXXXX
XXXXX
"""
def groups(grid):
    group_lst = [i for i in grid.split('\n') if i]

    coordinates = []
    for row,column in enumerate(group_lst):
        occurences = [i for i,k in enumerate(column) if k is 'O']
        coordinates.append([(row,i) for i in occurences])
    return [k for i in coordinates for k in i]

print groups(grid)

Output:
[(0, 3), (0, 4), (1, 2), (1, 3), (2, 2)]

A: Well thanks for the answers! I don't know skimage and all packages yet... still learning with the basics. My full solution became this, based on a lot of comments here.
First function finds coordinates from given grid as a list
Second function finds the connected item
Third function checks every item in the grid and checks if each character has the same number of occurrences inside the grid.
def groepen(rooster):

    groepen = {}
    rij = 1;

    for rij in range(len(rooster)):
        # Coordinaten bepalen
        #print("R: " + str(rij))
        for kolom in range(len(rooster[rij])):
            #print("K: " + str(kolom))
            getal = rooster[rij][kolom]
            if getal in groepen:
                groepen[getal].add((rij,kolom))
            else:
                groepen.update({getal:{(rij,kolom)}})

    return groepen

def samenhangend(groep):
    # Controle variabele
    samenhangend = False

    # originele_coord en rooster een set maken: moet unieke waarden bevatten
    originele_coord = set()
    rooster = set()
    # Lijst maken van de coordinaten die worden meegegeven aan de functie
    coordinaten = list(groep)
    # Eerste coordinaat toevoegen aan het rooster
    rooster.add(coordinaten[0])

    # Lus lopen zolang er coordinaten zitten in het rooster
    while rooster:
        # coordinaat uithalen uit het rooster
        coordinaat = rooster.pop()
        # coordinaat toevoegen in aanliggend
        originele_coord.add(coordinaat)

        # variabelen x en y aanmaken voor coordinaten
        (x,y) = coordinaat

        # Lijst van de mogelijke buren per coordinaat
        aanliggende_coord = [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]

        # Lus voor ieder coordinaat van de aanliggende coordinaten
        for coord in aanliggende_coord:
            # Controle als het coordinaat nog niet in de set originele_coord zit, en als het terug te vinden is in de
            # coordinaten, als het er nog niet inzit maar wel in de coordinaten het toevoegen aan het rooster.
            if not coord in originele_coord and coord in coordinaten:
                rooster.add(coord)

    # Als er evenveel coordinaten zijn als aanliggende dan is het een correcte evendeling.
    if len(originele_coord) == len(groep):
        samenhangend = True

    return samenhangend

def evendeling(rooster):
    # Standaard variabele evendeling
    evendeling = True
    # Variabele voor de lus de tellen
    teller = 0

    # Coordinaten getallen bepalen van het meegegeven rooster
    rooster_coord = groepen(rooster)

    # Voor iedere coordinaten set in het rooster, controleren als deze samenhangend zijn of niet
    for coord_set in rooster_coord:
        #print(evendeling)
        # Lengte controleren , als het aantal coordinaten niet hetzelfde is al de vorige klopt het ook niet
        if teller == 0:
            lengte_coord = len(rooster_coord[coord_set])
        if not lengte_coord == len(rooster_coord[coord_set]):
            evendeling = False
        teller += 1

        # Als het niet samenhangend is dan zetten we evendeling op False
        if samenhangend(rooster_coord[coord_set]) == False:
            evendeling = False

    return evendeling

rooster = [[1, 1, 1, 5, 5], [2, 1, 5, 5, 4], [2, 1, 5, 4, 4], [2, 2, 4, 4, 3], [2, 3, 3, 3, 3]]
evendeling(rooster)

rooster = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
print(groepen(rooster))

print(evendeling([['K', 'V', 'V'], ['K', 'K', 'V'], ['q', 'q', 'q']])) # Should be TRUE!


text:
Q: MongoDB inconsistent results with n > nscanned in explain Mongo 2.4.1, 2-member replica set with arbiter
I have what I think is a pretty simple query returning inconsistent results:
objects = db.collection.find({'field.id': my_id, 'field1': None, 'field2': 'value'})

I'm getting 77 objects back, but there are 248 objects in the collection that match that query.  My suspicion is that the query optimizer is doing something I don't expect.  None of the indexes on collection are sparse.
In the .explain() for the above query, I get
{cursor: 'BtreeCursor field.id_1', n: 283, nscanned: 77}

Why is nscanned less than 283?
I should also note that while the 77-length result is pretty consistent, occasionally the exact same query will return a result with 238 documents in it.
EDIT: full .explain() included below.  I noticed it looks at BtreeCursor field.id_1 twice.  Is that normal?
{
    "nYields": 0,
    "nscannedAllPlans": 1011,
    "allPlans": [
        {
            "cursor": "BtreeCursor field2_1",
            "indexBounds": {
                "field2": [
                    ["moment", "moment"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 0
        },
        {
            "cursor": "BtreeCursor field.id_1_field3_1_field2_1_field1_1_created_at_-1",
            "indexBounds": {
                "field1": [
                    [null, null]
                ],
                "created_at": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ],
                "field3": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field2": [
                    ["moment", "moment"]
                ],
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 78
        },
        {
            "cursor": "BtreeCursor field1_1_field3_1_field4_1_field5_-1_field2_1_created_at_-1",
            "indexBounds": {
                "field4": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field3": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field1": [
                    [null, null]
                ],
                "created_at": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ],
                "field5": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ],
                "field2": [
                    ["moment", "moment"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 0
        },
        {
            "cursor": "BtreeCursor field1_1_field3_1_field4_1_field2_1_created_at_-1",
            "indexBounds": {
                "field1": [
                    [null, null]
                ],
                "created_at": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ],
                "field4": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field2": [
                    ["moment", "moment"]
                ],
                "field3": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 0
        },
        {
            "cursor": "BtreeCursor field1_-1_created_at_-1",
            "indexBounds": {
                "field1": [
                    [null, null]
                ],
                "created_at": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 0
        },
        {
            "cursor": "BtreeCursor field.id_1_field3_1_field1_1_created_at_-1",
            "indexBounds": {
                "field1": [
                    [null, null]
                ],
                "created_at": [
                    [
                        {
                            "$maxElement": 1
                        },
                        {
                            "$minElement": 1
                        }
                    ]
                ],
                "field3": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 78
        },
        {
            "cursor": "BtreeCursor field.id_1_field6_1_field2_1",
            "indexBounds": {
                "field6": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field2": [
                    ["moment", "moment"]
                ],
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 76,
            "nscanned": 77,
            "n": 76
        },
        {
            "cursor": "BtreeCursor field.id_1_field7_1",
            "indexBounds": {
                "field7": [
                    [
                        {
                            "$minElement": 1
                        },
                        {
                            "$maxElement": 1
                        }
                    ]
                ],
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 71
        },
        {
            "cursor": "BtreeCursor field.id_1",
            "indexBounds": {
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 78,
            "nscanned": 78,
            "n": 77
        },
        {
            "cursor": "BtreeCursor field.id_1",
            "indexBounds": {
                "field.id": [
                    ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
                ]
            },
            "nscannedObjects": 77,
            "nscanned": 77,
            "n": 72
        },
        {
            "cursor": "BasicCursor",
            "indexBounds": {},
            "nscannedObjects": 77,
            "nscanned": 77,
            "n": 0
        }
    ],
    "millis": 14,
    "nChunkSkips": 0,
    "server": "c3:10003",
    "n": 283,
    "cursor": "BtreeCursor field.id_1",
    "oldPlan": {
        "cursor": "BtreeCursor field.id_1",
        "indexBounds": {
            "field.id": [
                ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
            ]
        }
    },
    "scanAndOrder": false,
    "indexBounds": {
        "field.id": [
            ["oid-50eba1a2256b4738d0e5254d", "oid-50eba1a2256b4738d0e5254d"]
        ]
    },
    "nscannedObjectsAllPlans": 1000,
    "isMultiKey": false,
    "indexOnly": false,
    "nscanned": 77,
    "nscannedObjects": 77
}

A: It's probably because you have a sparse index.

*

*n = number of documents that match the query selection criteria

*nscanned = number of documents or index entries scanned during the database operation

If you have a sparse index, the index will not contain any entry for objects that do not have the index keys.
From the looks of your query, mongodb is indeed using the index for field1 and your query is searching for null values for that field. So check if your index is sparse -- that's most likely the cause.


text:
Q: Pass operator as function template parameter I have to overload the basic arithmetic operators for some very complicated objects I've made.  So far, I've successfully implemented operator*; now I need operator+, etc.  The code for operator* is very large, but the only difference between operator* and operator+ will be one line where I use + instead of * on some complex numbers.  This line will be inside of a loop that gets called many many times, so I want it to be efficient, which would seem to imply no function pointers.  (Correct me if I'm wrong.)
This seems like a perfect use for templates.  But I'm at a loss as to the correct syntax.  I'm thinking something like this inside the ComplicatedObject class definition:
template <typename ComplexBinaryOp>
ComplicatedObject BinaryOp(const ComplicatedObject& B) const {
  // Do lots of stuff
  for(unsigned int i=0; i<OneBazillion; ++i) {
    // Here, the f[i] are std::complex<double>'s:
    C.f[i] = ComplexBinaryOp(f[i], B.f[i]);
  }
  // Do some more stuff
  return C;
}

inline ComplicatedObject operator*(const ComplicatedObject& B) const {
  return BinaryOp<std::complex::operator*>(B);
}

inline ComplicatedObject operator+(const ComplicatedObject& B) const {
  return BinaryOp<std::complex::operator+>(B);
}

This question is related: "function passed as template argument".  But the functions passed as the template arguments are not operators.
I've fiddled with the syntax every way I can think of, but the compiler always complains of bad syntax.  How should I do this?
Edit:
For clarity, I include the complete solution in terms of my code above, along with the additional generalizations people may need:
template <typename ComplexBinaryOp>
ComplicatedObject BinaryOp(const ComplicatedObject& B) const {
  // Do lots of stuff
  for(unsigned int i=0; i<OneBazillion; ++i) {
    // Here, the f[i] are std::complex<double>'s:
    C.f[i] = ComplexBinaryOp()(f[i], B.f[i]); // Note extra ()'s
  }
  // Do some more stuff
  return C;
}

inline ComplicatedObject operator+(const ComplicatedObject& B) const {
  return BinaryOp<std::plus<std::complex<double> > >(B);
}

inline ComplicatedObject operator-(const ComplicatedObject& B) const {
  return BinaryOp<std::minus<std::complex<double> > >(B);
}

inline ComplicatedObject operator*(const ComplicatedObject& B) const {
  return BinaryOp<std::multiplies<std::complex<double> > >(B);
}

inline ComplicatedObject operator/(const ComplicatedObject& B) const {
  return BinaryOp<std::divides<std::complex<double> > >(B);
}

A: I think std::plus<std::complex> and std::multiplies<std::complex> are what you're looking for, but I'm not 100% sure I understand your question (is your code snippet within a class you aren't showing us?)

A: You have two options. Pass the function at runtime:
#include <functional>

template <typename ComplexBinaryOp>
ComplicatedObject BinaryOp(const ComplicatedObject& B, ComplexBinaryOp op) const {
  // ...
    C.f[i] = op(f[i], B.f[i]);
  // ...
}

// functor wrapping member function pointer
BinaryOp(B, std::mem_fn(&std::complex<double>::operator+));

// standard-issue functor
BinaryOp(B, std::plus<std::complex<double>>());

Or pass it at compile-time:
// or another floating-point type
typedef double (*ComplexBinaryOp)(double, double);

template <ComplexBinaryOp op>
ComplicatedObject BinaryOp(const ComplicatedObject& B) const {
  // ...
    C.f[i] = op(f[i], B.f[i]);
  // ...
}

// non-member function
template<class T>
std::complex<T> add_complex(const std::complex<T>& a, const std::complex<T>& b) {
  return a + b;
}

// non-member function pointer
BinaryOp<add_complex<double>>(B);

I believe you can do the same with member function pointers as well by changing the definition of ComplexBinaryOp.


text:
Q: Filter out common words for search query Are there any easy ways to implement filtering a user's input (possibly a question) by extracting the meaningful data in the query?
I basically want to filter out any noise words so I can send a 'clean' query to Google's search api.

A: Um, won't Google do this for you?  Send all those dirty, filthy words to Google and let them clean them up for you.

A: Jeff talked about "stop words" in one of the previous stackoverflow podcasts.  You might try searching for that phrase on google.  The wikipedia page seems to have some overview and pointers to options.
http://en.wikipedia.org/wiki/Stop_words

A: You can try removing the top X most common English words, but you will always run into trouble with a naive approach like this.
This is because common English words can have special significance in the realm of Computer Science (or other areas). A recent SO podcast (#32) mentions this very issue.

A: I used the stop words approach when implementing a basic search engine and it worked fine.
Try a sample list like the one here
Based on feedback from your users, you can modify your stop word list accordingly.


text:
Q: Struggling with lists in Haskell I'm having trouble with a list of lists in Haskell.
Here's my function:
create_matrix :: (Read t, Integral t) => [String] -> t -> [[t]]
create_list_of_lists (x:xs) num = [read x `div`z | z <- [1..num]] : create_list_of_lists xs num

When i run it like this:
create_list_of_lists ["1212","3232"] 3

i get sort off the desired output, which is
[[1212,606,404],[3232,1616,1077]

but it misses the last ']' at the end, and presents me with this error:
Exception: hondt.hs:39:1-81: Non-exhaustive patterns in function create_list_of_lists

I guess it has to do with types, but i don't know what i'm doing wrong.

A: What is happening is that due to Haskell's laziness GHCi is printing out the first two sub-lists as it receives them, but then runs into an error.  This error is because you haven't defined all the possible inputs for create_list_of_lists, namely when the first argument is empty.  You'll need
create_list_of_lists [] num = ???
create_list_of_lists (x:xs) num = [read x `div`z | z <- [1..num]] : create_list_of_lists xs num

Without the clause for [], you'll end up calling create_list_of_lists [] num, which is currently undefined.


text:
Q: resample a pandas df within each group I have a df that has a MultiIndex of (id, date) and I would like to do 2 things:

*

*convert the DateTimeIndex named date to a PeriodIndex within each id group

*resample the frequency of the PeriodIndex to monthly from daily
My current (non-working) method is to (even before converting to PeriodIndex):
df = pd.DataFrame(data = {"val": np.arange(30),
                          "id": np.tile([1,2], 15),
                          "date": np.repeat(pd.date_range(start = "2000-01-01", periods = 15, name="date"), 2)
                         })

df = df.set_index(["id", "date"]).sort_index()
df.groupby("id")["val"].resample(rule = "M", closed = "right", label = "right").apply(lambda x: np.sqrt(sum(x)/10))

This raises:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'

What's the right way to do the whole procedure? I'm a bit confused about how to think about groupby: my mental model is that anything that follows a groupby operation will only receive the subframe corresponding to that group (ie the MultiIndex becomes a single index of just date within that particular group). Is this not correct?

A: If use DataFrameGroupBy.resample is necessary DatetimeIndex set before groupby, also apply is not necessary, faster is resample sum, then divide final Series by 10 and then use np.sqrt:
df = df.set_index(["date"]).sort_index()

df1 = (np.sqrt(df.groupby("id")["val"]
                 .resample(rule = "M", closed = "right", label = "right")
                 .sum()
                 .div(10)))

print (df1)
id  date
1   2000-01-31    4.582576
2   2000-01-31    4.743416
Name: val, dtype: float64


text:
Q: How to configure apple push notification for distribution I am successfully using APN with my app in developer mode, but I cannot get it to work in adhoc distribution mode.
i've followed faithfully the tutorial http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12 and I've read all the other posts on this issue that i could find on SO and elsewhere.
in developer mode I create the cer and p12 pem files and combine them: when i try:
openssl s_client -connect gateway.push.apple.com:2195 -cert aps_production.cer.pem -key MyPrivateKey.p12.pem, I get:
depth=1 /C=US/O=Entrust, Inc./OU=www.entrust.net/rpa is incorporated by reference/OU=(c) 2009 Entrust, Inc./CN=Entrust Certification Authority - L1C
verify error:num=20:unable to get local issuer certificate
verify return:0

-----BEGIN CERTIFICATE-----
(certificate deleted)
-----END CERTIFICATE-----
subject=/C=US/ST=California/L=Cupertino/O=Apple Inc./OU=iTMS Engineering/CN=gateway.push.apple.com
issuer=/C=US/O=Entrust, Inc./OU=www.entrust.net/rpa is incorporated by reference/OU=(c) 2009 Entrust, Inc./CN=Entrust Certification Authority - L1C
---
No client certificate CA names sent
---
SSL handshake has read 2723 bytes and written 2140 bytes
---
New, TLSv1/SSLv3, Cipher is AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID:
    Session-ID-ctx:
    Master-Key: (deleted)
    Key-Arg   : None
    Start Time: 1348332242
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)

I don't know what the "verify error:num=20:unable to get local issuer certificate" means or  if it is important. I get the very same thing when I use gateway.sandbox.push.apple.com:2195 with my developer cer and key, but it works fine.
when i then use simplepush.php with a developer version of app on phone. notifications work perfectly. when i use the same with adhoc distribution, and a adhoc distribution version of app on phone, i get nothing despite simplepush.php returning:
"Delivered Message to APNS"
i've queried the feedback service, and there are no errors reported.
Others have suggested that APNS doesn't work for adhoc mode if the app hasn't been approved by apple. Is that the problem? Our app is still under review.
Thanks for your help.

A: *

*Any in-house distribution profile gives out a same tokenID, how ever this tokenID varies across different devices.

*Make sure that the distribution provisioning profile is generated after creating aps_certificate. High changes the profile may miss out aps-environment key in the distribution certificate.

*Other only issue could be only with the ProductionURL.

*I have also notices that the push notification reception is delayed sometimes, mostly when used with production URL.


text:
Q: Cakephp core XML class String could not be parsed as XML I've tried below query and used Cake's core XML class but I get String could not be parsed as XML error...
$output = $this->Job->query("
            SELECT job.id, job.title, organisation.name, jobsboard.name
            FROM job
            LEFT JOIN portfolio_job_category pjc ON pjc.job_id = job.id
            LEFT JOIN category c ON c.id = pjc.category_id
            LEFT JOIN organisation ON organisation.id = job.organisation_id
            LEFT JOIN portfolio jobsboard ON jobsboard.id = pjc.portfolio_id
            WHERE job.end_date >= DATE( NOW( ) )
            AND pjc.portfolio_id = $portfolio
            ORDER BY c.id DESC
            ");
$jobs['jobs_feed'] = $output;
$jobs = Xml::fromArray($jobs);
$jobs = $jobs->asXML();

Below is my array output from model's custom query.
Array
(
    [0] => Array
        (
            [job] => Array
                (
                    [id] => 38459
                    [title] => UTS: Engineering Research Scholarships in Petroleum Remediation
                )

            [organisation] => Array
                (
                    [name] => University of Technology Sydney
                )

            [jobsboard] => Array
                (
                    [name] => Research Jobs
                )

        )

    [1] => Array
        (
            [job] => Array
                (
                    [id] => 44144
                    [title] => Associate Lecturer - Clinical Exercise Physiology
                )

            [organisation] => Array
                (
                    [name] => James Cook University
                )

            [jobsboard] => Array
                (
                    [name] => Research Jobs
                )

        )
)

Is there anything I can do to fix this?

A: Xml needs a root node:
change:
$jobs = Xml::fromArray($jobs);

to:
$jobs = Xml::fromArray(array('jobs' => $jobs));