text:
Q: Mysterious Voltage Bias I'm designing a color organ. My circuit so far:
Quick description: Input signal is .2V pk-pk. Voltage after amp is 4V pk-pk. 2N7000 needs 2V to turn on, so it should turn on when the frequency I want is passed through the filter, but any other frequencies are decreased in amplitude.
My problem lies after C2 at node Va. What I expect there would be an amplified wave of my input centered on the x axis (if the y axis was measuring voltage.) Instead what I find is my amplified input shifted up by 1 or 2 volts. So even though my AC signal decreases at node Vb as frequency increases, it is still biased by that +1 or +2 volts, so the MOSFET stays on at all frequencies.
I've tried a number of things so far. First, I tried discharging the caps, but that seemed to have no affect. I tried adding a large resistor in parallel with C3, but that didn't help much either. I really don't know what's going on here or how to fix it, so any help would be greatly appreciated. Thanks in advance!
EDIT: I also chose large values for my filter because previously it was too small and the lack of impedance was causing a voltage loss at higher frequencies. I am also aware of the nasty clipping my amplifier gives me at the moment. I plan on fixing it later.

A: 1000 µF is a ridiculously huge value to use as the coupling capacitor at the output of the amplifier, especially given the high input impedance of the filter(s). Assuming this is an electrolytic capacitor, its leakage current is undoubtedly enough to explain the bias you're getting.
Assuming that the net input impedance of your three filters together is on the order of 100 kΩ, a ceramic capacitor of 0.1 µF for C2 would give you a lower cutoff frequency of 16 Hz, which is plenty low enough for this application.

A: The node Va has no DC path to ground, therefore the voltage is not well defined. Usually a circuit simulator automatically inserts a conductance to resolve this problem and issues a warning.


text:
Q: Implementing web crawler in Python While I am trying to implement a simple web crawler code in Colab, and as I have written the following code, I got the syntax error as follows. Please advise me how to resolve the issue to run it:
import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page=1
    while page <= max_pages:
      url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=2%22+Butterfly+Valve&_sacat=0&_pgn='+ str(page)
      source_code= requests.get(url)
      plain_text=source_code.text
      soup = BeautifulSoup(plain_text)
        for link in soup.findALL('a', {'class':'s-item__title s-item__title--has-tags'})
          href = link.get('href')
          print(href)
        page+=1

trade_spider(1)

Error:
File "<ipython-input-4-5d567ac26fb5>", line 11
    for link in soup.findALL('a', {'class':'s-item__title s-item__title--has-tags'})
    ^
IndentationError: unexpected indent

A: There are a lot of wrong things about this code, but I can help. The for loop has an extra indent, so delete an indent from the start of and also add a : to the end of the for loop. Also, it seems like you just copied this from the internet but whatever. Anyways, here is the correct code:
import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page=1
    while page <= max_pages:
      url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=2%22+Butterfly+Valve&_sacat=0&_pgn='+ str(page)
      source_code= requests.get(url)
      plain_text=source_code.text
      soup = BeautifulSoup(plain_text)
      for link in soup.findALL('a', {'class':'s-item__title s-item__title--has-tags'}):
        href = link.get('href')
        print(href)
      page+=1

trade_spider(1)

Edit: after I ran this code, there is an error:
main.py:10: GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 10 of the file main.py. To get rid of this warning, pass the additional argument 'features="html5lib"' to the BeautifulSoup constructor.

So here's the correct code:
import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page=1
    while page <= max_pages:
      url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=2%22+Butterfly+Valve&_sacat=0&_pgn='+ str(page)
      source_code= requests.get(url)
      plain_text=source_code.text
      soup = BeautifulSoup(plain_text, features="html5lib")
      for link in soup.find_all('a', {'class':'s-item__title s-item__title--has-tags'}):
        href = link.get('href')
        print(href)
      page+=1

trade_spider(1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xcode single project without storyboard i was trying to read the big nerd ranch book for ios 7.
I know it's old but it has very interesting topic and i believe its one of the best written and the best book for learning.
The problem is that i use xcode 6.1 and the templates are totally different. I would also want to translate their Objective-c code into Swift.
The translation part was easy but i got a major issue in doing something probably silly.
This is my code
AppDelegate
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        var firstframe:CGRect = CGRectMake(160, 240, 100, 150)
        var firstView:HypnoView = HypnoView(frame:firstframe)

        firstView.backgroundColor = UIColor.redColor()
        self.window?.addSubview(firstView)

        return true
    }
}

HypnoView
import UIKit

class HypnoView: UIView {

    var frameView:CGRect = CGRectNull

    override init(frame: CGRect) {
        frameView = frame
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

This is the error i get
2014-11-07 20:32:41.408 Hypno[7987:450667] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle  (loaded)'
the app still look for the main storyboard file, but i can't find where it's linked... how can i fix this so i can just start with my own ViewController, without eventually using storyboard? where it's the code that should've been in the app delegate that loads everything? thanks

A: Remove "Main storyboard file base name" key from info.plist

A: Click on your project's root folder, General tab, Main Interface (the storyboard is listed here).


text:
Q: An alternative way to achieve data privacy in ES6 Class I was reading about data privacy in JavaScript and how to achieve that in ES6 Class. I notice this
class Person {
    constructor(name) {
        let _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }
    }
}

then we cannot access _name like
const p1 = new Person('bob');
p1._name = 'John';

because _name is not part of the properties of the object.
It seems like it can achieve data privacy.
But I was wondering if this is a good practice.

A: A large majority of developers are aware of a leading underscore being a private variable and not for general API usage. So it being visible or not shouldn't really matter. Where as having getters and setters for every single property can really be too much boilerplate and frankly a waste of time.
Furthermore, this.setName and this.getName are not attached to the prototype chain which removes the ability for pretty much any optimization to occur - such as being able to reuse class methods between multiple instances.
If you want true privacy, use a factory function rather than a class.
And in response to your question, no it generally isn't good practice to write out classes that way.


text:
Q: SSH tunnelling in Catalina to use Screen Sharing (VNC) I am using the following to try and ssh tunnel to a remote machine via a master one:
ssh -J username1@1.2.3.4 username2@5.6.7.8 -L 5900:localhost:5900
Password:
Password:
bind [::1]:5900: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 5900
Could not request local forwarding.

This works perfectly on Mojave (executing vnc://localhost afterwards in a new Terminal window). But in Catalina, no. I get: You cannot control your own screen.
About port 5900 already in use, I ran sudo lsof -i tcp:5900 and I can't see any process using that port.

A: I finally made tunnelling work in Catalina:
First ssh -J username1@1.2.3.4 username2@5.6.7.8 -L 5901:localhost:5900.
Then open 'vnc://localhost:5901' in a new Terminal window.


text:
Q: How to static list? I have this static list in my C# console application which includes different

A: There are various ways.
ex...
int maxCount= 4;
for(int i=0;i<maxCount && i< Mp3spelers.Count();i++)
{
    Console.WriteLine(list[i]); // Write whatever your need.
}

Or, using Linq
list.Take(maxCount)
     .ToList()
     .ForEach(x=> Console.WriteLine(x));

A: If you have overwritten ToString() in the MP3 class you could use the following code:
public static void Display() {
   Mp3spelers
       .Where(x => /* TODO e.g. x.Name.Contains("X")*/)
       .ForEach(entry => Console.WriteLine(entry));
}


text:
Q: How to create multiple C++ custom actions in single custom action project? Is there anyway to make multiple C++ custom actions in single C++ custom action project.
I'm using WiX Toolset v3.10 and Visual Studio 2015.
I guess it may be done with C# but i don't want to use C# and .Net for my custom actions.
I just want to create single .dll for all of my custom actions.
Is this even possible? If possible can you give me an example?
Any help would be appreciated. Thank you!

A: I would look through this WiX source code for examples on writing C++ custom actions.
https://github.com/wixtoolset/wix3/tree/develop/src
Look at: wix3 / src / ext / ca / wixca / dll /


text:
Q: Jordan basis of $\mathcal{M}_{\mathcal{T}}(A)$ Let $A\in M_{n\times n}(\mathbb{R})$ be a matrix. Let $\mathcal{B}$ be a basis of $\mathbb{R}^n$ and $X:=\mathcal{M}_{\mathcal{B}}(A)$. If $\mathcal{S}$ is the basis for which $\mathcal{M}_{\mathcal{S}}(X)$ is the Jordan Canonical Form of $X$, which is the basis $\mathcal{T}$ for which $\mathcal{M}_{\mathcal{T}}(A)$ is the JCF of $A$?
My Proof. Let $\mathcal{E}$ be the canonical basis of $\mathbb{R}^n$. Let $J:=\mathcal{M}_{\mathcal{S}}(X)$. We know that
$$A=\mathcal{M}_{\mathcal{E},\mathcal{B}}(Id)\cdot X\cdot\mathcal{M}_{\mathcal{E},\mathcal{B}}(Id)^{-1},$$
$$X=\mathcal{M}_{\mathcal{S},\mathcal{E}}(Id)\cdot J\cdot\mathcal{M}_{\mathcal{S},\mathcal{E}}(Id)^{-1}.$$
Therefore, $A=\mathcal{M}_{\mathcal{E},\mathcal{B}}(Id)\mathcal{M}_{\mathcal{S},\mathcal{E}}(Id)\cdot J\cdot(\mathcal{M}_{\mathcal{E},\mathcal{B}}(Id)\mathcal{M}_{\mathcal{S},\mathcal{E}}(Id))^{-1}=\mathcal{M}_{\mathcal{S},\mathcal{B}}(Id)\cdot J\cdot\mathcal{M}_{\mathcal{S},\mathcal{B}}(Id)^{-1}$.
We conclude that $\mathcal{T}$ is the basis $\mathcal{S}$ written in basis $\mathcal{B}$.
Can you tell me if my proof is correct? Thanks in advance.


text:
Q: Conditional Routing in React based on API calls So I'm trying to create a React web app with multiple pages and connecting it to Flask to fetch data using the fetch API. Here is what I want to achieve:
If the user submits a Form, React does a POST request to the Flask API which returns a JSON object, which is received by React and I render the predict route. This is handled using the Forms.jsx component, which has the following code:
const Form = () => {
  const [title, setTitle] = useState("");

  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefault();
    const movie_submit = {title};
    console.log(movie_submit);

    fetch('/predict', {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(movie_submit)
    }).then(() => {
      (navigate("/predict"));
    })

  }
  return (

        <form className='form' onSubmit={handleSubmit}>
          <input type='text' placeholder='Movie Name' autoFocus
          autoComplete='off' value={title} onChange={(e)=>setTitle(e.target.value)}/>
          <button className='button'>Recommend!</button>
        </form>

  )
}

export default Form

Now I want to perform a GET request to the Flask API to get what should be put into the Predict.js page (/predict route), and the show it.
Predict.js is as:
const Predict = () => {
  const [movies, setMovies] = useState([]);
  useEffect(() => {
    fetch('/predict').then(response =>
      response.json().then(data =>
        {
        setMovies(Object.values(data));
    }))

  }, []);
  const movie_name = movies.map((movie) =>
{movie}
);
  return (

        <Navbar />

Predictions

<Movies movie={movie_name}/>

  )
}

export default Predict

But I want this to be such that if the user hasn't submitted the form, then it navigates to /apology route, and if the FLASK API GET request returns an empty object, even then it navigates to /apology route. How do I do this? I understand this is conditional routing of some sort, but I havent been able to quite achieve where I should do this. Here <Movies /> is simply a component that helps in showing the movie names

A: You can pass a data to the state prop of the location object.
fetch('/predict', {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(movie_submit)
}).then(() => {
  (navigate('/predict', { state: { wasFetched: true } }));
})

then in your Predict Component:
const { state } = useLocation();
const { wasFetched } = state;
useEffect(() => {
  if (wasFetched) {
    // user submited the form
  } else {
    // user hasn't submited the form
  }
}, [wasFetched]);


text: Q: How can I switch back from KDE to Cinnamon modifying some Ubuntu configuration files I've installed KDE full on my Jetson Nano, but I made a huge mistake. On the screen I see the error failed to start kernel modules and it gets stuck before to show the login screen (I'm using an HDMI monitor attached); so nothing works and I don't know what I can do to switch back to my previous desktop manager, Cinnamon, which worked great. What I think I can do is to remove the SD card, change some parameters in the proper config files,but I don't know what files could be. Can someone of you point me to the right direction? I don't want to reinstall Ubuntu from scratch. Thanks.


text:
Q: Export data to multiple Excel sheets? How can I export data from Visual FoxPro into Excel file I know. I something like this:
USE tableName
EXPORT TO (fileName) TYPE XL5 AS CPDBF()

I get Excel file with one sheet. Does anybody know how can export second table to the same excel file but in different sheet? I prefer Visual FoxPro code but you can write me example in C#, for example how to export each data table to different Excel sheet but in the same Excel file.
Kind regards,
Ozren Sirola

A: You can't do that with the EXPORT or COPY TO commands. To put data into multiple sheets in Excel, you need to use Automation. The fastest approach is probably to use EXPORT or COPY TO to create multiple workbooks, and then use Automation to consolidate the data into a single workbook.
The Automation part would look something like:
oXL = CREATEOBJECT("Excel.Application")
oBook = oXL.Workbooks.Open("<the file containing the sheet you want first>")
* Copy second sheet to first workbook
oBook2 = oXL.Workbooks.Open("<the file containing the sheet you want second>")
oBook2.Sheets[1].Copy(, oBook.Sheets[1])
oBook2.Close()
* Copy third sheet to first workbook
oBook2 = oXL.Workbooks.Open("<the file containing the sheet you want third>")
oBook2.Sheets[1].Copy(, oBook.Sheets[2])
oBook2.Close()
* Etc.

oBook.Save()
oBook.Close()
oXL.Quit()


text:
Q: Consistency of linear equations in 3 variables Which condition $p$, $q$ and $r$  should satisfy so that the following system of linear simultaneous equations has at least one solution, such that $p+q+r\neq0?$
$x+2y-3z=p$
$2x+6y-11z=q\\x-2y+7z=r$
I approached this problem using Gauss Elimination method by creating an augmented matrix and reducing it to row echelon form. I got something like this :-
$$
  \left[\begin{array}{rrr|r}
    1 & 2 & -3 & p \\
    2 & 6 & -11 & q \\
    1 & -2 & 7 & r
  \end{array}\right] =
  \left[\begin{array}{rrr|r}
    1 & 2 & -3 & p \\
    0 & 2 & -5 & q-2p \\
    0 & 0 & -11 & r+2q-5p
  \end{array}\right]
$$
Now we can see that the co-efficient matrix and augmented matrix, both has rank of 3 which equals the number of variables present i.e. $3$. So in this condition there must be unique solution to this system of simultaneous linear equations.
I am getting confused by the language of the question which says that there must be "at least one solution". So does this mean that this system of simultaneous linear equations should have more than 1 solutions? How can this be possible if the Gauss Elimination method is telling that there should be a unique solution?
Also what can we say about the relationship between $p$,$q$ and $r?$ As per my understanding, in order to keep the rank 3 because then only we will have a unique solution, so is the relationship between $p$,$q$ and $r$ will be $r+2q-5p = 0?$ My confusion here is that it is not necessary to have $r+2q-5p = 0$ because even if this is not equal to $0$ then also the rank will remain as $3$ as $-11$ will be there in the $3rd$ row.
Please clarify me on my doubts!

A: Your restriction is on the last row. If $r + 2q - 5p \neq -11z$ there is no solution.
EDIT: Upon double checking, I believe you made an error on your Gaussian Elimination. The last row should have $0 = r + 2q - 5p$.  So that is your restriction.


text:
Q: run-time error '-2147221080 (800401a8)': Automation error I'm getting the above error message trying to run this macro:
(Sorry about the size and messy state)
* <- means data removed for protection
Private Sub CommandButton1_Click()

' Button to select one client from "Search Result" and fill their information in "Client Details"

'On Error GoTo CloseDataPool

' Make sure the Client Number cell is empty

If Range("B2") = "" Then
MsgBox ("Please enter valid client number")
Exit Sub
End If

' Give row value to Client Number
Search_Result = 4 + Range("B2")
If Cells(Search_Result, 1) <> Range("B2") Then
MsgBox ("Please enter valid client number")
Exit Sub
End If

' Find client in Data Pool via Broker Reference, then find their row number

Workbooks.Open "C:\Users\*\Dropbox\Shared Folder AT TH DH\Savant\*\Data Pool.xlsx"

Dim RC As Workbook
Dim DPW As Workbook
Dim DP As Worksheet
Dim SR As Worksheet
Dim CD As Worksheet
Dim PFDP As Worksheet
Set DPW = Workbooks("Data Pool")
Set DP = DPW.Worksheets("Data Pool")
Set RC = Workbooks("*")
Set SR = RC.Worksheets("Search Results")
Set CD = RC.Worksheets("Client Details")
Set PFDP = DPW.Worksheets("Prospect Fleet Data Pool")
Set PLDP = DPW.Worksheets("Prospect Liability Data Pool")

' Protect workbook and worksheets
CD.Protect Password:="*", UserInterfaceOnly:=True
SR.Protect Password:="*", UserInterfaceOnly:=True
DP.Protect Password:="*", UserInterfaceOnly:=True
PFDP.Protect Password:="*", UserInterfaceOnly:=True
PLDP.Protect Password:="*", UserInterfaceOnly:=True
RC.Protect Password:="*", Structure:=True
DPW.Protect Password:="*", Structure:=True

Search_Result = SR.Range("B2") + 4
x = DP.Cells(Rows.count, 1).End(xlUp).Row + 1
For Each Rowcheck In DP.Range("B2:B" & x)
If Rowcheck = SR.Range("B" & Search_Result) Then
y = Rowcheck.Row

CD.Range("E16") = DP.Cells(y, 1) 'Company Name
CD.Range("F38") = DP.Cells(y, 4) 'User added by
CD.Range("L38") = DP.Cells(y, 5) 'Date added on
End If
Next Rowcheck

Search_Result = CD.Range("F8")

Polcol = 2
Polrow = 45
x = PFDP.Cells(Rows.count, 1).End(xlUp).Row + 1
For Each Rowcheck In PFDP.Range("A2:A" & x)
If Rowcheck = Search_Result Then
y = Rowcheck.Row
CD.Cells(Polrow, Polcol) = Polrow - 44
CD.Cells(Polrow, Polcol + 2) = PFDP.Cells(y, 3)
Polrow = Polrow + 1
End If
Next Rowcheck

x = PLDP.Cells(Rows.count, 1).End(xlUp).Row + 1
For Each Rowcheck In PLDP.Range("A2:A" & x)
If Rowcheck = Search_Result Then
y = Rowcheck.Row
CD.Cells(Polrow, Polcol) = Polrow - 44
CD.Cells(Polrow, Polcol + 2) = PLDP.Cells(y, 3)
Polrow = Polrow + 1
End If
Next Rowcheck

'Add to history log
Set HLD = DPW.Worksheets("History Log")
HLD.Protect Password:="*", UserInterfaceOnly:=True
HLDR = HLD.Cells(Rows.count, 1).End(xlUp).Row + 1
HLD.Cells(HLDR, 1) = CD.Range("F8")

GoTo EndSub
CloseDataPool:
MsgBox ("An error has occurred")
EndSub:
Workbooks("Data Pool.xlsx").Save
Workbooks("Data Pool.xlsx").Close

End Sub

The line that's showing the error is:
Set HLD = DPW.Worksheets("History Log")

I've attempted to move this line near the start where I set the other Worksheets instead. I also move the protection line near the start as well. When I do this, the error reoccurs but on the next line down:
HLDR = HLD.Cells(Rows.count, 1).End(xlUp).Row + 1

I've also added a line just above to open the Data Pool workbook as whilst googling, I saw the error can occur by looking for items in a closed workbook. However, the error still persists.
I've looked around and I cannot find a solution. Can someone assist me in understanding this error?

A: You have posted too much code to get a tailored answer. Instead I will try to explain the problem in a more general way. Lines like these are the reason for your problem:
Workbooks.Open "C:\Users\*\Dropbox\Shared Folder AT TH DH\Savant\*\Data Pool.xlsx"
...
...
Workbooks("Data Pool.xlsx").Save

Do like this instead:
Dim DataPool as Workbook
Set DataPool = Workbooks.Open("...\Data Pool.xlsx")
...
...
DataPool.Save

All other references to that object should be via the object variable, not the class.


text:
Q: Difference between Execute Task and Submit Job? When I compare my GPServer with sample service from ESRI. I notice difference.
In esri
Supported Operations:   Execute Task
my GPServer:
Supported Operations:    Submit Job
What is the difference between Task and Job??

A: Execute Task for synchronous GP services and Submit Job for asynchronous GP services.
From Esri Help:

Asynchronous and synchronous define how the client (the application
  using the task) interacts with the server and gets the result from the
  task. When a service is set to synchronous, the client waits for the
  task to finish. Typically, a synchronous task executes quickly—five
  seconds or less. An asynchronous task typically takes longer to
  execute, and the client must periodically ask the server if the task
  has finished and, if it has finished, get the result. A web
  application using an asynchronous task must have logic implemented to
  check the status of a task and handle the result once execution is
  finished. ArcGIS Desktop clients handle both execution types natively.


text:
Q: How To maintain the aspect ratio of image? How To maintain the aspect ratio of image like 3:4 show on portrait then this image should be convert 9:16 when move device in landscape and image should not be stretched.
Hoe can maintain this please help me thanks advance.
My code are
And this image i want to set on image switcher. How to maintain every image that is set on imageswicher should be aspect ratio.
public View makeView() {

        ImageView imageView = new ImageView(this);

        imageView.setAdjustViewBounds(true);
        WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = window.getDefaultDisplay();

        imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                display.getWidth(), LayoutParams.FILL_PARENT));
        imageView.setBackgroundResource(R.drawable.border);
            imageView.setPadding(8, 8, 8, 8);
        imageView.setImageBitmap(image);
        imageView.setScaleType(ScaleType.FIT_XY);
}

A: ScaleType.FIT_XY does not preserve aspect ratio. It's not for photos, but usefull for decorative images. Try ScaleType.CENTER_CROP - your image will cropped to fit view bounds, or ScaleType.CENTER_INSIDE - your image will scaled to fit view bounds maintain the image's aspect ratio.

A: Instead of using:
    imageView.setBackgroundResource(R.drawable.border);

Use :
    imageView.setImageResource(R.drawable.border);

Also see this answer.


text:
Q: System of equations from weighted Gaussian Quadrature I've been working on a weighted Gaussian Quadrature problem for a Numerical Analysis class and have been having the hardest time.  The problem boils down to solving a system of four equations:
$$
  \left\{ \begin{array}{l}
  1 = a_0 + a_1 \\
  \frac{1}{4} = a_0 x_0 + a_1 x_1 \\
  \frac{1}{9} = a_0 x_0^2 + a_1 x_1^2 \\
  \frac{1}{16} = a_0 x_0^3 + a_1 x_1 ^3 \\
  \end{array}
  \right.
$$
I know that we can write this in matrix form as
$$
  \left( \begin{matrix}
  1 & 1 \\
  x_0 & x_1 \\
  x_0^2 & x_1^2 \\
  x_0^3 & x_1^3  \\
  \end{matrix} \right)
  \left( \begin{matrix}
  a_0 \\
  a_1 \\
  \end{matrix} \right)
   = \left( \begin{matrix}
   1 \\
   1/4 \\
   1/9 \\
   1/16 \\
   \end{matrix} \right)
$$
My Professor sold it as solvable because it's a system of four equations in the four unknowns $a_0 , a_1 , x_0, x_1$, but I'm not sure how to proceed given that we have higher powers of $x_0$ and $x_1$.  This seems like it should be a relatively easy linear algebra question, but I'm stumped.  Any help would be greatly appreciated!

A: Considering the equations$$\left\{ \begin{array}{l}
  1 = a_0 + a_1 \\
  \frac{1}{4} = a_0 x_0 + a_1 x_1 \\
  \frac{1}{9} = a_0 x_0^2 + a_1 x_1^2 \\
  \frac{1}{16} = a_0 x_0^3 + a_1 x_1 ^3 \\
  \end{array}
  \right.$$
use the first and second to eliminate $a_0$ and $a_1$ as functions of $x_0$ and $x_1$; this leads to $$a_0=-\frac{4 {x_1}-1}{4 ({x_0}-{x_1})}$$ $$a_1=1-\frac{4 {x_1}-1}{4 ({x_0}-{x_1})}$$ Plug these into the third equation which becomes $$\frac{1}{36} ({x_0} (9-36 {x_1})+9 {x_1}-4)=0$$ from which $x_0$ can be eliminated $$x_0=\frac{9 {x_1}-4}{9 (4 {x_1}-1)}$$ Now, the fourth equation becomes $$\frac{36 {x_1} (7 {x_1}-5)+17}{1296 (4 {x_1}-1)}=0$$ that is to say $$252 {x_1}^2-180 {x_1}+17=0$$ for which the roots are $$\frac{1}{42} \left(15 \pm\sqrt{106}\right)$$
I am sure that you can take from here and finally get
$$\left\{a_0=\frac{1}{2}-\frac{9}{4 \sqrt{106}},a_1=\frac{1}{2}+\frac{9}{4
   \sqrt{106}},x_0=\frac{1}{42} \left(15+\sqrt{106}\right),x_1=\frac{1}{42}
   \left(15-\sqrt{106}\right)\right\}$$ $$\left\{a_0=\frac{1}{2}+\frac{9}{4 \sqrt{106}},a_1=\frac{1}{2}-\frac{9}{4
   \sqrt{106}},x_0=\frac{1}{42} \left(15-\sqrt{106}\right),x_1=\frac{1}{42}
   \left(15+\sqrt{106}\right)\right\}$$


text:
Q: Is it possible to switch the format of date picker header? I am trying to change the header on material design date picker as you select a date to a different format than default. Current default is Month , year : ex: june 22, 2021, but I want it such that its Mon, June 22. It's shown on material design document as the first design, but there's no indication of how to go about changing this format?
Any ideas?

material designs : https://material.io/components/date-pickers
what I want to achieve is this :

A: Unfortunately, you can NOT change Date Format and Local of MaterialDatePicker.
Since MaterialDatePicker is very restricting, so as many other Material Design Components, I recommend you to use an alternate Date Picker Library such as MaterialDateTimePicker.
It basically fulfills all your needs:

*

*Change date format: setLocale(Locale locale) ✅

*Choose from multiple date UIs ✅

*Very flexiable and easily customizlbe to fit your needs ✅

PS: There is one more popular alternative: android-betterpickers
Let me know if you have any other questions.

A: After looking into the source, and trying some things, I did find a solution. Unfortunately, it's not that simple to implement and I guess switching to  MaterialDateTimePicker is still the best solution here.
The conversion from date to text for the header is done by the DateSelector via getSelectionDisplayString(Context context). See getHeaderText() inside of MaterialDatePicker here.
Sadly, MaterialDatePicker is final, so you can not simply create your own and override this method. But, with the given Builder, you can use MaterialDatePicker.Builder.customDatePicker(DateSelector selector) to place your own DateSelector (source).
Material uses their SingleDateSelector (source) for a simple date selection. But again, it's not possible to build upon this selector and write a custom getSelectionDisplayString method, because the class is restricted. Knowing this, it's needed to write your own DateSelector.
Building your own DateSelector is a bigger task on its own. It may be possible to copy from SingleDateSelector, but it's using some private classes and methods you need to copy, too.
To cut a long story short, I guess this is too much for "simply" changing the date format.


text:
Q: build.gradle no where to found after successful export in Eclipse Hi guys I'm new in android development and I found it strange why I can't find the build.gradle in my project after successfully exported the project. This is what I did.

*

*Update SDK to revision 22.0.5.

*Update my Eclipse Plugin to adjust in 22.0.5 build.

*Open my eclipse then Export.

*Select Generate Gradle build files.

*Click next, then next

*Then it tells me that successfully exported and give the location of the build.gradle but going to the said directory the file is no where to found.


text:
Q: Conditional Column Header in Power Query I have a situation where my Header titles are as missing for some columns due to the fact that my data has KEY and TEXT format where there is a column header is available for KEY but nut for TEXT. An EXAMPLE below.

I would like to get header defined for every columns in such a way that the logic works even if I change the position of the data set. In excel I do it as in the image 2.

And the result as in image 3
.
Currently I am playing around with PowerQuery and I am quite new to this tool. Does anyone know the steps that could work around so even if the position of data source change, column header remain as it works in the excel. I would be very glad.

A: Here a possible solution:
In Excel load the table to Power Query uncheck My table has headers:

In the Power Query editor look for Advanced Editor and copy and paste this lines:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type any}, {"Column2", type text}, {"Column3", type text}, {"Column4", type text}, {"Column5", type text}, {"Column6", type text}, {"Column7", type text}, {"Column8", type any}, {"Column9", type any}, {"Column10", type any}}),
    #"Transposed Table" = Table.Transpose(#"Changed Type"),
    #"Added Conditional Column" = Table.AddColumn(#"Transposed Table", "Custom", each if [Column1] = null then [Column2] else [Column1]),
    #"Duplicated Column" = Table.DuplicateColumn(#"Added Conditional Column", "Custom", "Custom - Copy"),
    #"Filled Down" = Table.FillDown(#"Duplicated Column",{"Custom"}),
    #"Added Conditional Column1" = Table.AddColumn(#"Filled Down", "Custom.1", each if [#"Custom - Copy"] = null then [Custom] & " Name" else [Custom]),
    #"Reordered Columns" = Table.ReorderColumns(#"Added Conditional Column1",{"Custom.1", "Column1", "Column2", "Column3", "Column4", "Column5", "Custom", "Custom - Copy"}),
    #"Removed Columns" = Table.RemoveColumns(#"Reordered Columns",{"Column1", "Custom", "Custom - Copy"}),
    #"Transposed Table1" = Table.Transpose(#"Removed Columns"),
    #"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table1", [PromoteAllScalars=true]),
    #"Changed Type1" = Table.TransformColumnTypes(#"Promoted Headers",{{"StudentID", type any}, {"Country", type text}, {"Country Name", type text}, {"Department", type text}, {"Department Name", type text}, {"Mayor", type text}, {"Mayor Name", type text}, {"AGE", type any}, {"WEIGHT", type any}, {"HEIGHT", type any}})
in
    #"Changed Type1"

Load as table in Excel:


text:
Q: Drawing 4 squares inside each other I want to draw 4 squares, each square get smaller by 10 pixel and goes inside the other square(centered)
this is what I have for now
square.py
def drawSquare(myTurtle,sideLength,x,y):
    myTurtle.setx(x)
    myTurtle.sety(y)
    for i in range(4):
        myTurtle.forward(sideLength)
        myTurtle.right(90)

main.py
>>> from square import *
>>> import turtle
>>> t = turtle.Turtle()
>>> side = 200
>>> x = 60
>>> y = 60
>>> for i in range(4):
    drawSquare(t,200,x,y)
    side = side - 10
    x = x- 5
    y = y - 5

Unfortunately the way this works is 4 different squares are on top of each other
any suggestions ?

A: I approached this question using recursion as it is probably the most simple way.
myTurtle = turtle.Turtle()
def drawSquares(myTurtle,sideLength, x, y, nSquares, distanceApart):
    if nSquares > 0:
        myTurtle.pu()
        myTurtle.setx(x)
        myTurtle.sety(y)
        myTurtle.pd()
        for i in range(4):
            myTurtle.forward(sideLength)
            myTurtle.right(90)
        drawSquares(myTurtle, sideLength - distanceApart*2, x+10, y-10, nSquares-1, distanceApart)

drawSquares(myTurtle, 200, 60, 60, 4, 10)

A: This problem can be approached several different ways using turtle.  Although the obvious answer seems to be nested loops to draw the squares, below are some other ways to think about it.
First, using turtle.circle(steps=4).  The circle routine can draw arbitrary regular polygons including squares though you have to make adjustments with respect to positioning:
import turtle

def drawSquares(myTurtle, sideLength, nSquares, distanceApart):

    myTurtle.penup()
    x, y = myTurtle.position()
    myTurtle.goto(x - sideLength/ 2, y - sideLength / 2)  # adjust so current x, y is center
    myTurtle.pendown()

    myTurtle.setheading(-45)  # by default square would be sitting on corner instead of on side

    for _ in range(nSquares):
        radius = sideLength * 2**0.5 / 2
        myTurtle.circle(radius, steps=4)
        sideLength -= 10

        myTurtle.penup()
        x, y = myTurtle.position()
        myTurtle.goto(x + distanceApart / 2, y + distanceApart / 2)
        myTurtle.pendown()

yertle = turtle.Turtle()
yertle.penup()
yertle.goto(60, 60)
yertle.pendown()
drawSquares(yertle, 200, 4, 10)

turtle.done()

For my remaining examples, I'm going to assume the same calling code and just present modified drawSquares() routines.  I believe @PVNRT's recursive solution was excellent though I'd adjust it slightly as follows:
def drawSquares(myTurtle, sideLength, nSquares, distanceApart):
    if nSquares < 1:
        return

    for _ in range(4):
        myTurtle.forward(sideLength)
        myTurtle.left(90)

    myTurtle.penup()
    x, y = myTurtle.position()
    myTurtle.goto(x + distanceApart / 2, y + distanceApart / 2)
    myTurtle.pendown()

    drawSquares(myTurtle, sideLength - distanceApart, nSquares - 1, distanceApart)

My personal favorite way to go about this sort of problem is to use stamping instead of drawing.  It's an extremely fast solution:
def drawSquares(yourTurtle, sideLength, nSquares, distanceApart):
    myTurtle = yourTurtle.clone()  # clone turtle so we don't have to restore changes

    myTurtle.shape("square")  # modify turtle shape for stamping
    myTurtle.fillcolor(turtle.bgcolor())  # modify turtle fill color for stamping

    for _ in range(nSquares):
        myTurtle.turtlesize(sideLength / 20)  # magic number 20 is default stamp size
        myTurtle.stamp()
        sideLength -= distanceApart

And finally, the obvious solution using nested loops which shouldn't be as obvious going forward now that you've seen there are other approaches:
def drawSquares(myTurtle, sideLength, nSquares, distanceApart):

    for n in range(nSquares):

        for _ in range(4):
            myTurtle.forward(sideLength)
            myTurtle.left(90)

        myTurtle.penup()
        x, y = myTurtle.position()
        myTurtle.goto(x + distanceApart / 2, y + distanceApart / 2)
        myTurtle.pendown()

        sideLength -= distanceApart

One weakness in the OP's specification was the meaning of the x & y arguments.  I've left them out with the understanding that the squares are drawn at the current x & y.  The OP treated them as the upper right corner of the drawing which isn't consistent with anything in turtle.  I've chosen to make them either the lower left or the center (for the circle and stamping-based solutions.)


text:
Q: Meteor - New user created after validating login is not recognized I have a login validation function setup to check if a new user registered outside of the app. That users info is stored in a temporary collection. If the users info validates I want to be able to use Accounts.createUser on the Client side, but I can't figure out how to do that. The documentation says that "registered validate login callbacks are called with a single argument, the attempt info object", but I can't find any examples of how to do this.
environment.js
Accounts.config({
 forbidClientAccountCreation : true
});

server.js
    Accounts.validateLoginAttempt(function(info){
    if (!info.allowed)
    {
        var userEmail = info.methodArguments[0].user['email'].toLowerCase();
        var userPass = info.methodArguments[0].password['digest'];

        // check if this is a temp user
        if (tmpUsers.find({'email': userEmail}).count() == 1)
        {
            var user = tmpUsers.findOne({'email': userEmail})
            // check for active
            if (user.active == "Yes")
            {
                // check password
                if (userPass == user.password)
                {
                    var accountId = Accounts.createUser({
                        'password': userPass,
                        'email': userEmail,
                        'profile': ({'acctType': user.type})
                    });
                    return true;
                } else {
                    throw new Meteor.Error(403, "Incorrect password.");
                    return false;
                }
            } else {
                throw new Meteor.Error(403, "Your account has yet to be activated.);
                return false;
            }
        } else {
            throw new Meteor.Error(403, "Can not find user " + userEmail);
            return false;
        }
    } else {
        return true;
    }
});

Update:
I ended up putting the Account.userCreate part on the server side and now it does get the user created but when I try to login I get "Email already exists." So it appears as though it doesn't expect the login to be successful and tries to create the user again.
{ // This user works
 "_id" : "hCBLo3AJJwmtR6s62",
 "createdAt" : ISODate("2014-12-26T20:27:58.44Z"),
 "services" : {
   "password" : {
    "bcrypt" : "$2a$10$pxlEy.JFomgwQwV2cpm72.TBG4.llP98BF9ssTCptC4WsekLzJO9G"
   },
 "resume" : {
  "loginTokens" : []
 }
},
"emails" : [{
  "address" : "demo@demo.com",
  "verified" : false
}]
}

{ // This one does not
 "_id" : "w6SGuqJJPs5LoCTTj",
 "createdAt" : ISODate("2015-01-10T20:54:16.032Z"),
 "services" : {
  "password" : {
   "bcrypt" : "$2a$10$VJFj0UOrQiLs7djfGWAeMeruDactDFrl1nlEsXh/r5Z/895C5ubAW"
  }
 },
  "emails" : [{
    "address" : "demo2@demo.com",
    "verified" : false
  }],
 "profile" : {
   "acctType" : null
 }
}

A: Would something like this work for you?

var options = {
  username: "username",    // you'll need to fill this in
  email:    userEmail,
  password: userPass,
  profile:  {name: "name"} // you'll need to fill this in
};

Accounts.createUser(options, function (error) {
  if (error) {
    console.log("Cannot create user");
  }
});


text:
Q: Passing params on promise.done? I have a promise, and when it's done I wish to run my getContentAll method:
p_numContentTotal.done(getContentAll);

I also wish to pass in a param to that method (the context of the script as I wish to access global vars in the method):
 p_numContentTotal.done(getContentAll(ctx));

But by adding this, the method gets run straight away, how can I get round this?

A: Wrap it in anonymous function:
p_numContentTotal.done(function () { getContentAll(ctx) });

Or explicitly push ctx as a context of a function and use this to access ctx variable inside it:
function getContentAll() {
   console.log(this); //will print your ctx variable
}
p_numContentTotal.done(getContentAll.bind(ctx));

A: Usually you'll want your entire script enclosed anyway, to control the namespace. Once you've done so, accomplishing your goal of accessing the current context of your script is already done. This 'javascript closure' is what provides the "anonymous function" capability Artyom mentioned.
How you wrap it is up to you. Simply, your entire script may be an object, a function, a block, or a callback from document ready. Ultimately, this is what allows the magic to happen in other methods anyway.
function main() {
    var ctx = 'current state';
    $("button").click(showContext);
    function showContext() {
        alert(ctx);
    }
}
$(main);

example here: http://jsfiddle.net/s6VDE/1/
note that this preserves reference access (which may or may not be what you want), as demonstrated here: http://jsfiddle.net/s6VDE/5/


text:
Q: View shift problem with UIImagePickerController with datasource as UIImagePickerControllerSourceTypeCamera In my aplication I'm providing two options for user for uploading photos:

*

*Take a photo

*Choose from library

I'm presenting this photo in a modalViewController in delegate method - imagePickerController: didFinishPickingImage editingInfo: by creating a viewController with an imageview and loading the selected image in it.
Working with photo library goes fine, but while taking photo from camera, whenever I launch my modalViewController in delegate method after taking the photo, the view shifts down by almost 20 pixels. And thereafter all the views get shifted whenever I navigate back.
EDIT:
    - (void)imagePickerController:(UIImagePickerController *)_picker1_ didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {

imageUploadView = [[UIViewController alloc]initWithNibName:nil bundle:nil];
imageUploadView.view.frame = CGRectMake(0, 0, 320, 480);
[imageUploadView.view setBackgroundColor:[UIColor blackColor]];
imageUploadView.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

image = [[UIImageView alloc]init];
image.frame = CGRectMake(0, 60, 320, 270);

   //I'm Adding different views like toolbar and barbuttons here

[_picker1_ presentModalViewController:imageUploadView animated:YES];

[image setImage:img];
   }

I'm really stuck here.
Can anybody please help? This' really urgent.
Thanx in advance.

A: Hide the status bar before presenting your modalViewcontroller and try it.


text:
Q: 18.04 upgrade does not install desktop my upgrade finished but when I log on all I get is the cmd prompt. there is not a desktop installed. How do I fix this?

A: Try pressing Ctrl-Alt-F1.
If there is still no GUI type: sudo apt install ubuntu-desktop to install GUI programs that come with Ubuntu. Wait until it downloads reboot and that should solve it I guess.


text:
Q: Update SeekBar in Fragment with value from SharedPreferences I have an app with action bar. It has a "Main" fragment and a "Preferences" fragment.
    final Main main = new Main();
    final Preferences preferences = new Preferences();
    drawer.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            Fragment fragment= null;
            FragmentManager fragmentManager = getSupportFragmentManager();
            switch(position) {
                case 0:
                    fragment = main;
                    break;
                case 1:
                    fragment = preferences;
                    break;
            }
            fragmentManager.beginTransaction()
                .replace(R.id.fragment1, fragment)
                .commit();
            drawerLayout.closeDrawers();
            }
        });

The "Preferences" fragment has a seekBar that is updated with a value from SharedPreferences. This is the relevant code that makes this within the "Preferences" fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    container.removeAllViews();

    View view = inflater.inflate(R.layout.preferences, container, false);

    fontSizeBar = (SeekBar) view.findViewById(R.id.fontSizeBar);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Preferences.this.getActivity().getBaseContext());
    final int fontSize = preferences.getInt("fontSize", 10);

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            fontSizeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,
                        boolean fromUser) {
                    Log.v("Progress changed", "Font size: " + progress);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.v("Start touching", "Font size: " + seekBar.getProgress());
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub
                    Log.v("Stop touching", "Font size: " + seekBar.getProgress());
                }

            });
            fontSizeBar.setMax(10);
            fontSizeBar.setProgress(fontSize);
        }
    });

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.preferences, container, false);

}

The method onProgressChanged() is called, because I can see the output "Progress changed", "Font size: 10" in LogCat, but the SeekBar is not visually updated. Additionally,the SeekBar does not responds to the methods onStartTrackingTouch() and onStopTrackingTouch().
I will appreciate any information that could shed some light about the problem.

A: You're doing everything right, inflating the views and setting up the logic but at the end you do this:
return inflater.inflate(R.layout.preferences, container, false);

which will return a newly inflated layout(so you drop everything you previously done). Instead you need to return the view which you previously inflated:
return view;


text:
Q: Wrong computation with PGF math all.
I'm trying to draw an incircle to a regular pentagon. Here's my code:
\documentclass[tikz,border=1.5mm]{standalone}

\usetikzlibrary{calc, math}

\begin{document}
\begin{tikzpicture}[rotate=90]
\pgfmathsetmacro{\R}{2}
\node[draw, circle, fill=black, thick, inner sep=0pt, outer sep=0pt] (0,0) (O) {};
%\draw (O) circle (\R);
\draw[fill=blue!10!white] %
(0:\R) %node[fill=black, thick, inner sep=1pt, outer sep=1pt] {}
\foreach \x in {72,144,...,360} {
    -- (\x:\R)
}
-- cycle;% (90:\R);
\foreach \x in {0,72, 144, ..., 360} {
\draw[thick, densely dashed, %rotate=90
] (O) -- (\x:\R);
}
\draw[dotted] (O) -- (180:{0.8*\R}) node[label={below:$l$}] (B) {};
\node[anchor=north west] at (180:{0.4*\R}) {$a$};
\node[anchor=south] at (216:{0.6*\R}) {$r$};
\coordinate (c) at (B);
\draw[%rotate around={72:(c)}
] ($ (c) + (0.15,-0.01) $) -- ($ (c) + (0.15,0.15) $) -- ($ (c) + (0,0.15) $);
\pgfmathsetmacro{\ap}{cos(pi/5)*\R}
\draw[thin, densely dotted] (O) circle (\ap);
\end{tikzpicture}
\end{document}

The whole problem lies in the last two lines. The computation cos(pi/5)*\R should give around 1.618, but when drawing a circle with that radius it gives the radius of the circumcircle (see attached picture). Perhaps I have a syntax error in using the PGF math library, but I cannot see it. Naturally, when I manually input 1.618 into the radius, it draws what I want.
Thanks!

A: The pgfplots manual (pp. 52) recommends to use deg if you want to use radians inside a trigonometric function.
Thus, the code becomes:
\documentclass[tikz,border=1.5mm]{standalone}

\usetikzlibrary{calc, math}

\begin{document}
\begin{tikzpicture}[rotate=90]
\pgfmathsetmacro{\R}{2}
\node[draw, circle, fill=black, thick, inner sep=0pt, outer sep=0pt] (0,0) (O) {};
%\draw (O) circle (\R);
\draw[fill=blue!10!white] %
(0:\R) %node[fill=black, thick, inner sep=1pt, outer sep=1pt] {}
\foreach \x in {72,144,...,360} {
    -- (\x:\R)
}
-- cycle;% (90:\R);
\foreach \x in {0,72, 144, ..., 360} {
\draw[thick, densely dashed, %rotate=90
] (O) -- (\x:\R);
}
\draw[dotted] (O) -- (180:{0.8*\R}) node[label={below:$l$}] (B) {};
\node[anchor=north west] at (180:{0.4*\R}) {$a$};
\node[anchor=south] at (216:{0.6*\R}) {$r$};
\coordinate (c) at (B);
\draw[%rotate around={72:(c)}
] ($ (c) + (0.15,-0.01) $) -- ($ (c) + (0.15,0.15) $) -- ($ (c) + (0,0.15) $);
\pgfmathsetmacro{\ap}{cos(deg{pi/5})*\R};
\draw[thin, densely dotted] (O) circle (\ap);
\end{tikzpicture}
\end{document}

And here's the output:


text:
Q: Unable to import after declarations I'm trying to import some modules after the declarations in Go.
For instance, I've tried importing the time time after declaring a variable but that doesn't work , can someone please tell me why that happens in Go?
This works:
package main

import (
       "fmt"
)
import "time";

var test = "testing"

func main() {
    currtime := time.Now()

    fmt.Println(test)
    fmt.Println(currtime)//Output: 16:44:53

}
But thid doesn't:
package main

import (
       "fmt"
)

var test = "testing"
import "time"

func main() {
    currtime := time.Now()

    fmt.Println(test)
    fmt.Println(currtime)//Output: 16:44:53

}

The error is "non-declaration statement outside function body".
Why does that happen in Go?

A:
The error is "non-declaration statement outside function body". Why does that happen in Go?

Because this is how Go is defined to work.  From the spec:

Each source file consists of a package clause defining the package to which it belongs, followed by a possibly empty set of import declarations that declare packages whose contents it wishes to use, followed by a possibly empty set of declarations of functions, types, variables, and constants.

This means that the only valid place for import statements is between the package clause, and declarations of functions, types, variables, and constants.
In your case, you have a variable declaration, so the Go compiler knows there will be no more import statements. Then it sees your erroneous import statement, sees that it is a non-declaration, and correctly generates the error you observe.

A:
why does that happen in go lang ?

Because it is disallowed by the language spec. Pretty simple, or?

A: You usually have two ways to import packages in Go:
import "fmt"
import "time"

Or
import (
    "fmt"
    "time"
)

The trick is that you cannot have a mix of import and something else like in your second example.
package main

import (
       "fmt"
)

var test = "testing" //<-- This does not comply with the definition of a Go file
import "time"

func main() {
    currtime := time.Now()

    fmt.Println(test)
    fmt.Println(currtime)//Output: 16:44:53

}

Here you can find a well done documentation of the Anatomy of .go file.
Structure of every .go file is the same.

*

*First is package clause optionally preceded with comments usually describing the purpose of the package.

*Then zero or more import declarations.

*3rd section contains zero or more top-level declarations


text:
Q: Identify first character in a string Hello I need help in identifying the first character of a string. if the string contains a forward slash "/" or no forward slash in php.
Thanks in advance

A: Try this code:
<?php
function containSlash($str)
{
  return substr($str, 0, 1) == "/";
}

// TEST
echo (containSlash("/hello") ? "TRUE" : "FALSE"); // TRUE
echo (containSlash("hello") ? "TRUE" : "FALSE"); // FALSE
?>

A: Try this
function getSlashes($str)
    {
        return $str[0] ==  '/' || $str[0] ==  '\\';
    }

A: You're asking two different questions here.
You can examine the first character of a string using
$str[0]

You can check whether a string contains no / by using
strpos($str, '/') === FALSE


text:
Q: assign a reserved word of sql as a variable in a sql query I would like to know how to put a reserved word of sql as a variable in a sql query (I use postgresql)
def requeteDB(sql_request):
    with connection.cursor() as cursor:
        cursor.execute(*sql_request)
        row = cursor.fetchall()
    return row

def query1(choice, limit):
    return('''
           SELECT col1, SUM(col2) as nb
           FROM Table
           GROUP BY col1
           ORDER BY nb %s
           LIMIT %s
           ''', [choice, limit])

requeteDB(query1(choice="DESC", limit="5"))
> *** django.db.utils.ProgrammingError: ERROR: Type 'nb' does not exist
LINE 10: ORDER BY nb 'DESC'
------------------^

A: Likely the reason this fails is because of the second AS, so you can fix this with:
def query1(choice, limit):
    return (
        '''
           SELECT col1, SUM(col2) as nb
           ORDER BY nb %s
           LIMIT %s
           ''',
        [choice, limit],
    )
In case you do use a reserved keyword, you can escape the variable name. For postgresql, this is with double quotes, so:
def query1(choice, limit):
    return (
        '''
           SELECT col1, SUM(col2) as "nb"
           ORDER BY "nb" %s
           LIMIT %s
           ''',
        [choice, limit],
    )


text:
Q: How to format a float with a comma as decimal separator in an f-string? For some machine control in python, I write the results to a text-file, that someone else can copy into Excel (this is the most convenient way in this situation). However, in the Netherlands, Excel has a comma as decimal separator and thus I want to have the result "position" in the text-file as 123,456, but when I use the f-string method like this:
    resultfile.write(f"Position\t{position:.5}")

This will obviously result in a dot decimal separator.
How can I change this to a comma without iterating through the whole file int the end and replace the dots with commas?

A: As @michel-de-ruiter mentioned, the f format does not work with locale. On the other hand, you can't set the precision using n format. For example, if you want 4 digits after decimal separator:
import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')

position = 123.45678999
print(f'{position:.4n}')  # output: 123,4 (not quite what we wanted!)

However, you can round the number with the desired precision before formatting it:
print(f'{round(position, 4):n}')  # output: 123,4567 (that's it!)

A: If you prefer to avoid dependencies, the following simple function might fit your needs:
def comma_num(n,f=''):
    return ('{'+f+'}').format(n).replace('.',',')

n = 1.23

f'Whatever {comma_num(n)}'
'Whatever {}'.format(comma_num(n))
>>>'Whatever 1,23'

f'Whatever {comma_num(n,":6.4f")}'
'Whatever {}'.format(comma_num(n,':6.4f'))
>>>'Whatever 1,2300'

A: If you want to format floats with a comma within the f-string, you can either use replace after casting the float to a string:
position = 123.456
f"Position\t{str(position).replace('.',',')}"

A second option is to use the Python standard library module locale (but it is not thread-safe):
import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')
f"Position\t{locale.format('%.3f', position)}"

A third option is to use the library babel (preferred in case of library routines):
from babel.numbers import format_decimal
f"Position\t{format_decimal(position, locale='nl_NL')}"

All three options return the same result for the given example:
'Position\t123,456'

A: If the g format is good enough for you, use n instead:
resultfile.write(f"Position\t{position:.7n}")

While n works (uses the current locale setting when used) instead of both d and g, there is no such thing for the f format unfortunately...

A: A simpler solution might be:
f"Position\t{position:,.5f}"


text:
Q: MVC 4 - Compiler Error Message: CS1061 I have created an image gallery upload which works fine with just the Image Description and Upload image. now i am adding a drop down to categories the images into a specific group folder.
My Database table is as follows:
CREATE TABLE [WebsitePhotosGallery] (
    [PhotoId]         UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [Decription]      NVARCHAR (150)   NOT NULL,
    [ImagePath]       NVARCHAR (200)   NOT NULL,
    [ThumbPath]       NVARCHAR (200)   NOT NULL,
    [CreatedOn]       DATETIME         NOT NULL,
    [GalleryCategory] NVARCHAR (50)    NOT NULL,
    PRIMARY KEY CLUSTERED ([PhotoId] ASC)
);

Note: I added [GalleryCategory] NVARCHAR (50)    NOT NULL now because of the drop down needed.
My Database Model Looks like this:
namespace T.Database
{
    using System;
    using System.Collections.Generic;

    public partial class WebsitePhotosGallery
    {
        public System.Guid PhotoId { get; set; }
        public string Decription { get; set; }
        public string ImagePath { get; set; }
        public string ThumbPath { get; set; }
        public System.DateTime CreatedOn { get; set; }
        public string GalleryCategory { get; set; }
    }
}

I also have this model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace T.WebsitePhotosGallery
{
    public class Photo
    {
        [Key]
        public int PhotoId { get; set; }

        [Display(Name = "Decription")]
        [Required]
        public String Decription { get; set; }

        [Display(Name = "Image Path")]
        public String ImagePath { get; set; }

        [Display(Name = "Thumb Path")]
        public String ThumbPath { get; set; }

        [Display(Name = "Created On")]
        public DateTime CreatedOn { get; set; }

        [Display(Name = "Gallery Category")]
        [Required]
        public String GalleryCategory { get; set; }

    }
}

My Controller looks like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using T.Database;
using T.Models.WebsitePhotosGallery;

namespace T.Controllers
{
    public class GalleryController : Controller
    {
        //
        // GET: /PhotosGallery/
        DatabaseEntity db = new DatabaseEntity();
        public ActionResult Index(string filter = null, int page = 1, int pageSize = 18)
        {
            var records = new PagedList<WebsitePhotosGallery>();
            ViewBag.filter = filter;

            records.Content = db.WebsitePhotosGalleries.Where(x => filter == null || (x.Decription.Contains(filter)))
                    .OrderByDescending(x => x.Decription)
                    .Skip((page - 1)*pageSize)
                    .Take(pageSize)
                    .ToList();

            //Count
            records.TotalRecords = db.WebsitePhotosGalleries.Where(x => filter == null || (x.Decription.Contains(filter))).Count();

            records.CurrentPage = page;
            records.PageSize = pageSize;

            return View(records);

        }

        [HttpGet]
        public ActionResult Create()
        {
            var photo = new Photo();
            return View(photo);
        }
        public Size NewImageSize(Size imageSize, Size newSize)
        {
            Size finalSize;
            double tempval;
            if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
            {
                if (imageSize.Height > imageSize.Width)
                    tempval = newSize.Height / (imageSize.Height * 1.0);
                else
                    tempval = newSize.Width / (imageSize.Width * 1.0);

                finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
            }
            else
                finalSize = imageSize; //image is already small size

            return finalSize;
        }

        private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
        {
            //Get new resolution
            Size imgSize = NewImageSize(img.Size, newSize);
            using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
            {
                newImg.Save(Server.MapPath(pathToSave), img.RawFormat);

            }
        }

        [HttpPost]
        public ActionResult Create(WebsitePhotosGallery photo, IEnumerable<HttpPostedFileBase> files)
        {
            if (!ModelState.IsValid)
                return View(photo);
            if (files.Count() == 0 || files.FirstOrDefault() == null)
            {
                ViewBag.error = "Please choose a file";
                return View(photo);
            }

            var model = new WebsitePhotosGallery();
            foreach (var file in files)
            {
                if (file.ContentLength == 0) continue;

                model.Decription = photo.Decription;
                var fileName = Guid.NewGuid().ToString();
                var s = System.IO.Path.GetExtension(file.FileName);
                if (s != null)
                {
                    var extension = s.ToLower();

                    using (var img = System.Drawing.Image.FromStream(file.InputStream))
                    {
                        model.ThumbPath = String.Format("/GalleryImages/Thumbs/{0}{1}", fileName, extension);
                        model.ImagePath = String.Format("/GalleryImages/{0}{1}", fileName, extension);

                        //Save thumbnail size image, 240 x 159
                        SaveToFolder(img, fileName, extension, new Size(240, 159), model.ThumbPath);

                        //Save large size image, 1024 x 683
                        SaveToFolder(img, fileName, extension, new Size(1024, 683), model.ImagePath);
                    }
                }

                //Save record to database
                model.CreatedOn = DateTime.Now;
                model.PhotoId= Guid.NewGuid();
                model.GalleryCategory = photo.GalleryCategory;
                db.WebsitePhotosGalleries.Add(model);
                db.SaveChanges();
            }

            return View();
        }

    }
}

And finally my View looks like this which is where the error now comes is, I hard coded the drop down list:
@using T.Database
@model T.WebsitePhotosGallery.Photo

@{
    var galleryCategories = new List<SelectListItem>
    {
        new SelectListItem {Text = "Group 1", Value = "Group 1"},
        new SelectListItem {Text = "Group 2", Value = "Group 2"}
    };
}

Create

Upload Images

        @using (Html.BeginForm("Create", "Gallery", FormMethod.Post, new { id = "photogallery", enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()

                    @Html.LabelFor(m => Model.Decription, new { @class = "control-label col-sm-3", required = ""})

                        @Html.TextBoxFor(m => m.Decription, new { @class = "form-control required" })
                        @Html.ValidationMessageFor(model => model.Decription)

                    @Html.LabelFor(m => Model.GalleryCategory, new { @class = "control-label col-sm-3", required = "" })

                         @Html.DropDownListFor(m => m.Product, productCategory, "-- Select Product --", new {@class = "form-control", required = ""})
                        @Html.ValidationMessageFor(model => model.GalleryCategory)

                    @Html.Label("Choose Image(s)", new { @class = "control-label col-sm-3", required = "" })

                        <input type="file" name="files" multiple="multiple" accept=".jpg, .png, .gif" required />

                        <input type="submit" value="Save" class="btn btn-primary" />

                            @ViewBag.error

        }

So now immediately when i want to view the Create page i am now getting this error:

Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource
  required to service this request. Please review the following specific
  error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'T.Models.WebsitePhotosGallery.Photo'
  does not contain a definition for 'GalleryCategory' and no extension
  method 'GalleryCategory' accepting a first argument of type
  'T.Models.WebsitePhotosGallery.Photo' could be found (are you missing
  a using directive or an assembly reference?)
Source Error:
Line 30:              Line 31:
  Line 32:                 @Html.LabelFor(m => Model.GalleryCategory,
  new { @class = "control-label col-sm-3", required = "" }) Line 33:
   Line 34:                     @Html.TextBoxFor(m
  => m.GalleryCategory, new { @class = "form-control required" })
Source File: c:\Users\Huha\Source\Workspaces\Panel\panel\Gallery
  Panel\Views\Gallery\Create.cshtml    Line: 32

Your help is much appreciated, thank you.

A: From here, it looks like your view and htmlhelper are a little off. You should be referencing the property via lambda and not via the Model. Basically, you're view goes from:

    @Html.LabelFor(m => Model.GalleryCategory, new { @class = "control-label col-sm-3", required = "" })

        @Html.TextBoxFor(m => m.GalleryCategory, new { @class = "form-control required" })
        @Html.ValidationMessageFor(model => model.GalleryCategory)

To the following (note change to @Html.LabelFor(...) call):

    @* Reference m. not Model. *@
    @Html.LabelFor(m => m.GalleryCategory, new { @class = "control-label col-sm-3", required = "" })

        @Html.TextBoxFor(m => m.GalleryCategory, new { @class = "form-control required" })
        @Html.ValidationMessageFor(model => model.GalleryCategory)

A: Did you split the solution into multiple projects? If so, try force building the project that contains the class Photo. It sounds like the WebApplication only sees an outdated DLL, in which the Photo.GalleryCategory property is not yet present.
If build fails (or is skipped) for the Photo project, then the last-built version of the DLL will be used.


text:
Q: How do I restore default settings and configuration, but keep local data, installed apps, and PPAs? I'm fairly new to Ubuntu and while messing around with different things and trying out some shells, I've managed to mess my system up. Specifically I really messed up my GNOME session and can't get it to run really at all.
Is there a way to backup my apps but reinstall or just "restore" Ubuntu to its original condition?  I had tons of updates installed, downloaded and setup my machine for Android development, and a few other things with a very slow internet connection.

A: Open a terminal and try this command:
rm -r ~/.config/ ~/.cache/

and relogin. In a perfect world, this would restore a stock environment without any data loss. The world is good enough that it may work for you. However, not all software is standards compliant, so... if your login is still borked, backup everything and run:
rm -rf ~/.[^.]*

This will delete configuration for all applications. It will also delete some user information, such as your browser login information, your email credentials, save game files, etc.


text:
Q: Is there a way to find if path exists in a Directed acyclic graph in constant time (O(1))? I have some directed acyclic graph. I want to find if path exists between two vertices in O(1).
Also, I want to add and remove edges between two vertices in O(n^2).
I think, I need to store information, how many path exists between two nodes. But I don't come up full algorithm.

A: Let's assume that f(i, j) is the number of paths from i to j vertex. Initially(I assume that the graph is empty, if it is not the case you can add all edges using the add operation) f(i, j) = 1 if i = j and 0 otherwise.
To add an edge from a to b, you can use the following procedure:
for i = 1 .. n
    for j = 1 .. n
        new_f(i, j) = f(i, j) + f(i, a) * f(b, j) //add the number of paths that contain a new edge

where n is the number of vertices.
Removing an edge can be done in a similar way:
for i = 1 .. n
        for j = 1 .. n
            new_f(i, j) = f(i, j) - f(i, a) * f(b, j) //subtract the number of paths that contian this edge

Removing/adding an edge obviously takes O(n ^ 2) time. A path from a to b exists if and only if f(a, b) != 0.
However, there is one issue with this solution: the number of paths can be very large(larger than a standard integer type can hold) and using arbitrary-precision arithmetic can increase time complexity. To avoid this issues, you can compute the number of paths modulo some large prime number(but small enough to fit into standard integer type) p. This solution can yield an incorrect result(the number of paths can be 0 modulo p even if it is actually non-zero), but the probability of a failure is low. To reduce it even more, you can compute f modulo several different prime numbers.

A: Great place to read about this is "Algorithms, 4th ed." by Robert Sedgewick and Kevin Wayne.http://algs4.cs.princeton.edu/home/ . They also present study course "Algorithms" at Coursera.org. It is free and there is material there to answer your question. Have a look.https://www.coursera.org/course/algs4partI


text:
Q: Can two integer polynomials touch in an irrational point? We define an integer polynomial as polynomial that has only integer coefficients. Here I am only interested in polynomials in two variables.
Example:

*

*$P = 5x^4 + 7 x^3y^4 + 4y$

Note that each polynomial P defines a curve by considering the set of points where it evaluates to zero. We will speak about this curve.
Example:
The circle can be described by

*

*$x^2 + y^2 -1 = 0$

We say two polynomials $P,Q$ are touching in point $(a,b)$ if $P(a,b) = Q(a,b) = 0$ and the tangent at $(a,b)$ is the same. Or more geometrically, the curves of $P$ and $Q$ are not crossing.

(The Figure was created with IPE - drawing editor.)
We also need a further technical condition. For this let $D$ be a ''small enough'' disk around $(a,b)$. Then $Q$ and $P$ define two regions indicated green and yellow. Those regions must be interior disjoint.  Without this condition for $P = y-x^3$ and $Q=y$ the point $(0,0)$ would be a touching point as well. See also the right side of the figure.
(I know that I am not totally precise here, but I don't want to be too formal, so that I can reach a wide audience.)
(Thanks for the comment from Jeppe Stig Nielsen.)
Example:

*

*$P = y - x^2$  (Parabola)

*$Q = y$  ($x$-axis)

They touch at the origin $(0,0)$.
My question:
Does there exist two integer polynomials $P,Q$ that touch in an irrational point $(a,b)$?
(It would be fine for me if either $a$ or $b$ is irrational)
Many thanks for answers and comments.
Till

A: What about $(x^2-2)^2$ and $0$?

If you want both coordinates to be irrational, you can add something like $x^3$ to both.

I hope this helps $\ddot\smile$

Images courtesy of WolframAlpha.

A: Here's a general way to find such examples where both curves are of the form $y=f(x)$.  Notice that $y=f(x)$ and $y=g(x)$ meet at a given value of $x$ iff that value of $x$ is a root of the polynomial $h(x)=f(x)-g(x)$, and they have the same tangent line iff that value is a root of $h(x)$ of multiplicity greater than $1$.
So this means that to find an example, we just need a polynomial $h(x)$ with integer coefficients that has a double root at some irrational value of $x$ (we can then take $g(x)$ to be any polynomial with integer coefficients at all, and $f(x)=h(x)+g(x)$).  This is easy to do: just take any polynomial $p(x)$ with integer coefficients and an irrational root, and let $h(x)=p(x)^2$.

A: If you have an irrational tangent point between your curves, it must have at least another conjugate, and since tangent points are double points, by Bézout's theorem, the product of the degrees of the curves must be at least $4$.
Since dtldarek gave an example of a degree $4$ curve and a degree $1$ curve, let me give an example between two degree $2$ curves :
The circle $x^2+y^2= 1$ and the ellipse $17x² + 8y² + 12x = 4$ are tangent at $(-2/3, \pm \sqrt {5}/3)$


text:
Q: Data binding check if not null in xml I am using data binding to trigger onClick with ImageView.
<androidx.appcompat.widget.AppCompatImageView
            android:onClick="@{(view) -> listener.zoomImage(view, connectedItem.largeImage)}"
           />

The problem is connectedItem.largeImage can be sometimes null, and I need that the onClick will no trigger if its null.
I tried:
android:onClick="@{(view) -> connectedItem.largeImage?? listener.zoomImage(view, connectedItem.largeImage)}"

But the sitax is wrong.
How can I accomplish that?

A: you can check it inside the zoomImage function, change type of large image to nullable and check it in the function:
if we consider that your function is :
fun zoomImage(view:View, largeImage:String){
    //your function logic
}

change it to:
fun zoomImage(view:View, largeImage:String?){
    if(largeImage != null){
        //your function logic
    }
}


text:
Q: Some space between elements without any reason I can figure out

 TEXT TEXT TEXT

This is HTML structure of related to issue document.
CSS:
#colorscheme{
    width:25%;
    display:inline-block;
    height: 50px;
    background:green;
}
#content{
    width:50%;
    display:inline-block;
    background: gray;
     box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}
#display_saved{
    border: solid 1px red;
    padding: 20px;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    width:100%;

}

JSfiddle
As you can see from the feedle, there is some space between #colorscheme and #content, despite there is no margins, and there is border-box property. How can I reduce it?

A: Inline block can cause whitespace issues and I would recommend floating the elements.
Have a look at this forked example - http://jsfiddle.net/DkhDm/1/
It's also worth noting that display inline-block lacks support in some browsers - which is another reason to always use floats ahead of it! You do however have the small added complication of clearing the floats but this is easily achieved.
#colorscheme{
    width:25%;
    float: left;
    height: 50px;
    background:green;
}
#content{
    width:50%;
    float: left;
    background: gray;
     box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}
#display_saved{
    border: solid 1px red;
    padding: 20px;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    width:100%;
}

A: It's just whitespace, which is logical because you've reduced your blocklevel elements to inline blocks explicitly. Eliminate the whitespace and it'll go away:

TEXT TEXT TEXT

A: DEMO
CSS:
#colorscheme{
    width:25%;
    display:block;
    height: 50px;
    background:green;
    float:left;
}

i have added float:left; and changed to display:block;

A: You can move the elements back into place with negative 4px of margin. (Not in IE6,7). inline-block do cause whitespace, i don't think it's a bug and it's rather nice to have when using inline-block on text-elements.
#colorscheme{
    margin-right: -4px;
    width:25%;
    display:inline-block;
    height: 50px;
    background:green;
}

A: You can also use html comments to eliminate the whitespace.

Content

More content


text:
Q: urllib2.URLError:  when trying to write .ics file I am trying to write the contents of a calendar (.ics) off a webpage (such as https://careers.unc.edu/calendar) into a file. Below is my code attempt:
def write_file(ics_url, set_calendar_name):

    url = ics_url

    response = urllib2.urlopen(url)
    webContent = response.read()

    f = open(set_calendar_name, 'w')
    f.write(webContent)
    f.close

    print 'File saved as: ' + set_calendar_name
    print
    return set_calendar_name

However, I keep getting the following error:
Traceback (most recent call last):
File "get_calendar.py", line 99, in <module>
  write_file(get_ics_url('https://careers.unc.edu/calendar'), 'carolina.ics')
File "get_calendar.py", line 36, in write_file
  response = urllib2.urlopen(url)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
  return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 429, in open
  response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 452, in _open
  'unknown_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 407, in _call_chain
  result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1266, in unknown_open
  raise URLError('unknown url type: %s' % type)
urllib2.URLError: <urlopen error unknown url type: webcal>

Does anyone have any ideas on what is causing it in my code? My program ran fine when I ran it with, for example, this URL: https://meded.hms.harvard.edu/calendar but not with the one mentioned earlier.

A: SOLUTION: I ended up figuring out what was wrong. The
link.get('href')

contained
'webcal:'

instead of
'https:'

at the beginning, so I had to replace it. The fixed code should be:
if link.get('href') != None and '.ics' in link.get('href'):
        endout = link.get('href')

        if endout[:6] == 'webcal':
            endout ='https' + endout[6:]


text:
Q: incrementally create arrays at compile time Inspired by this post
https://stackoverflow.com/a/6730362
I'm trying to set up a compile-time Sequence of similar (integral) types that may be stored in ROM only using template metaprogramming.
The idea is to define an array incrementally by adding elements line by line using the variadic scheme of template metaprogramming
Currently I'm here:
template<typename T, T... values> struct Seq
{
    static const T value[sizeof...(values)];
    static const uint16 n;
};
template<typename T, T... values> const T       Seq<T, values...>::value[]  = { values };
template<typename T, T... values> const uint16  Seq<T, values...>::n        = sizeof...(values);

template<sint32 idx, typename T, T... values> struct IncSeq;
template<sint32 idx, typename T, T... values> struct IncSeq<-1, T, values...> : Seq<T, values...> {};

I'm fairly new to template metaprogramming. So I basically have no clue what I'm doing here. But the VS-compiler complains about some partial specialization issues:
'idx' : template parameter not used or deducible in partial specialization 'IncSeq<-1,T,values...>'

Can you help me out here? Why isn't it deducible? I wrote '-1'!
the ovedrall idea is to have index variable decrement during each call until -1 is reached which causes the IncSeq to inherit from Seq using the provided types. Usage like so:
template<sint32 idx, typename T, T... values> struct IncSeq<0, uint8, values...> : IncSeq<-1, uint8, 42, values..>{};
template<sint32 idx, typename T, T... values> struct IncSeq<1, uint8, values...> : IncSeq<0, uint8, 43, values..>{};
template<sint32 idx, typename T, T... values> struct IncSeq<2, uint8, values...> : IncSeq<1, uint8, 44, values..>{};
typedef IncSeq<2, uint8> myStaticArray;

I realize this looks like a lot of hazzle but the idea of having an array in ROM being constructed line by line in source code may pose some advantages to some of us.

A:
Can you help me out here? Why isn't it deducible? I wrote '-1'!

The compiler cannot deduce idx exactly because you wrote -1. Since you're explicitly specifying what idx should be, you should get rid of it from the template parameters:
template<typename T, T... values> struct IncSeq<-1, T, values...> : Seq<T, values...> {};

You also need to expand values here:
template<typename T, T... values>
const T Seq<T, values...>::value[] = { values... };

Your code will now compile. (I have not tested the correctness of your solution.)
live wandbox example


text:
Q: Do quantum states contain exponentially more information than classical states? Do quantum states contain exponentially more information than classical states? It might seem so at first sight, but what about in light of this talk?

A: Joe's earlier answer is even-handed in a way which reflects the ambivalence of a number of  computer scientists about the meaning of the mathematical operators involved in quantum information. So, as a computer scientist, I feel free to answer on a somewhat different basis.
What does it mean to store information in a quantum state?
Quantum states are not linear operators (neither vectors of numbers, nor trace-1 square matrices). We represent quantum states by such mathematical objects, but that isn't what quantum states are; and those notations are terribly inefficient space-wise in the sense that the state of an electron requires no more space than the electron itself. Though we have no better representations ourselves, we may as well recognize that the notation is not the state itself. If you want to ask how much information a quantum state contains, looking at the way we represent those states is the wrong answer; you have to consider what information can actually be extracted from the physical system.
The amount of information contained by a state is that which is available to be retrieved, and which you can reliably retrieve from it by physical procedures. The question you have to ask is: "What do you mean by reliably?" This is perhaps subject to interpretation, but if what you're interested in is extracting information in polynomial time (i.e. in an amount of time which scales like a polynomial in the size of your storage system) with at least some threshold probability of success (say p > 0.9, but any constant larger than 0.5 will be about the same), then the answer is NO: the amount of information you can reliably extract will not scale exponentially as the system size.
You might think that you can get around this by also asking "What do you mean by extract?" Perhaps by being very sneaky, you can find alternative ways of squeezing an exponential amount of information into a system in a way that you can use later. And the study of quantum communication complexity has some excellent examples! But none of them enable an exponential information to be reliably obtained from a state.
For example: quantum fingerprinting
For instance, suppose you want to store an m-bit string x, but all you really care about being able to do is to compare it against some other m-bit string y some time in the future, and see if x = y (possibly destroying the state by making the comparison). In that case, you can squeeze m ~ 2n bits into an n-qubit state, and successfully make the comparison with constant probability! (This is called quantum fingerprinting.) Is this not squeezing an exponential amount of information into a handful of qubits? The answer is no: because although this is a clever use of coding which allows you to compare an exponential number of possible entities, in the end

*

*you are getting only one bit out: is the coded state equal to y, or not? If "not", you're barely any wiser as to what x was, and the state no longer contains the same information after the comparison. It might have changed only slightly if it hasn't been destroyed — and indeed, for the probability of success of the comparison to be high, two coded states must be "close" to orthogonal, we would expect it to have changed only little — but the state will degrade with each comparison until it contains essentially no information about x.

*you can't retrieve an arbitrary bit from x individually from the coded state; as I commented on Joe's answer, that would make the state a random access code† in which m ~ 2n bits of information are squeezed into n bits of space. But there is a well-established relationship to the success probability in this case: we have H(p) ≥ 1 − n/m , where H(p) is the entropy of the success probability p of extracting any single bit from x. For a success probability of p ≈ (1 + ε)/2 — so that the chance of getting the correct value for the single bit is ε/2 better than the random chance of a coin-flip — we have H(p) ≈ 1 − ε/ln(2); so that if m = 2n, for example, we obtain
$$ \varepsilon \approx n \ln(2) / 2^n $$
which is a pretty miserably small margin above pure chance, and nothing that you can amplify to a constant probability with only polynomially many repetitions.
† Random access codes are sometimes, but now it seems quite rarely, referred to as a "dense code". However, superdense coding refers to something else: a communication protocol with two bits of communication between Alice and Bob (one qubit in each direction). This protocol is also interesting, but a different sort of thing to random access codes.
Summary.
If you want to talk about the information stored in a quantum state, you have to talk about how you're going to get that information out of the state. In the end, Holevo puts a bound of one bit per qubit, of the amount of information you can extract with near certainty, out of a quantum state on a very large number of qubits; and any attempts to do better than this will come at a cost of diminishing success probability.
So in the end, no, you cannot squeeze an exponential amount of information into a quantum state.

A: The answer depends on what you mean by the information contained in a quantum state.
If you think of the wavefunction itself as a real physical entity then the answer is yes.
The problem with this view is that the information in a wavefunction is not accessible to us. We can only learn a small fraction of it through a measurement, while destroying the rest of it in the process. In fact the Holevo bound states that the amount of information accessible to us is the same as a classical system of the same size. If this is your criteria for the information contained in a quantum state then the answer to your question is no.
The problem with the second view is that under some conditions it is possible to choose in advance which part of the information in the wavefunction we want (see this paper for example). For example, imagine storing a whole phone book in a single quantum state, for which the accessible information is only the size of a single phone number. After retrieving a phone number of our choice, the phone book is destroyed.
On the one hand, we only got one phone number. On the other hand, we could have chosen any number we wanted, so in some sense the quantum state contained the entire phone book.
It is up to you to choose the view you prefer.

A: Look, classical information and processing devices can be of two types: analog and digital.
Analog information has a disadvantage: every time analog information is copied it decreases in quality. Some of the information gets lost. Thus analog information is not suitable for any extensive information processing that involves repeated copying.
But digital information also has its own limitation: unlike an analog device, digital device can only manipulate with quantities of information that are no smaller than one bit. If you have a variable that carries less than a bit of information, you still have to use a whole bit to store it (you can manipulate with quantities of information that represent non-integer number of bits, say a trit which is about 1.6 bits but it is still greater than a bit with bit remaining the smallest unit).
The main feature of quantum information in this respect is that it allows to digitally (i.e., without loss) independently manipulate with quantities of information that are less than one bit.
Suppose you have a database with 1000 variables that take 1/1000 of a bit each. In a classical digital computer you would have to employ 1000 bit to store this database. In a quantum device, conversely, you would need only one bit register to store the same information.
The disadvantage with the quantum information devices is that while you can freely manipulate with quantities of information below one bit, if you want to copy the information from quantum device into a classical digital medium, only one variable gets copied from one bit register and other variables stored in that register get lost.
That means that if you want to avoid information loss in this process you have to lead the quantum information in your device to such a state, before the reading, in which one variable occupies one register (and as the number of quantum registers is usually less than the number of variables used in the process, this usually means that unnecessary variables will be lost).
The art of quantum programming is to invent a process in which the result of a quantum computation includes much less number of variables than is used in the process, so that the result to fit in a quantum register in such a way so that each variable to occupy one qubit, which allows to read the result by a classical device without loss.
Not necessary to say that simulating a quantum device on a classical digital computer also requires allocating at least one bit per variable which may require much excess memory.
So to answer your question directly, a quantum register of n qubits stores exactly the same amount of information as a classical register of n bits. But it can store more than n independently-controllable variables of less than one bit capacity each, which a classical register cannot do.

A: This is exactly the question to which I was seeking with a colleague of mine to give some sort of answer. We considered a game played by a team of two - say Alice and Bob - in which the value of a random variable $x$ is revealed to Alice only, who cannot freely communicate with Bob. Instead, she is given a quantum $n$-level system, respectively a classical $n$-state system, which she can put in possession of Bob in any state she wishes. We thought about evaluating how successfully they managed to store and recover the value of $x$ in the used system by requiring Bob to specify a value $z$ and giving a reward of value $f(x,z)$ to the team.
Now Holevo's bound in itself does not imply that the expected reward in the quantum case could not be larger than in the classical case. (One can easily give an example of 2 channel matrices such that the first one has a greater capacity, yet in a certain game - if it is played only a few times - it is better to use the second channel.)
Nevertheless, we've managed to show that whatever the probability distribution of $x$ and the reward function $f$ are, when using a quantum $n$-level system, the maximum expected reward obtainable with the best possible team strategy is equal to that obtainable with the use of a classical $n$-state system.
See the details in my article on the arXiv:

P.E. Frenkel and M. Weiner, Classical information storage in an $n$-level quantum system, arXiv:1304.5723.

A: Experts agree that one qubit stores no more information than one bit.
But a zillion identical qubits (which you can prepare or manufacture to your specifications, even though you can not clone an unknown qubit)  contains about a zillion times more information than a zillion identical bits which still contains only a single bit of information.


text:
Q: Type not as polymorphic as suggested I'm trying to make a Functor instance for the following data type:
data Event t a = Event { runEvent :: t -> ([a], Event t a) }

instance Functor (Event t) where
    fmap :: (a -> b) -> Event t a -> Event t b
    fmap f e = Event go
        where
            go t = (fmap f x, e')
                where
                    (x, e') = Event.runEvent e t

But compilation fails with the following errors:
E FRP.fr:11: type `γ` is not as polymorphic as suggested in
    the annotation where just `β` is announced.
E FRP.fr:11: type error in expression go
    type is : ([γ],Event α β)
    expected: ([γ],Event α γ)

I tried adding some type annotations to generalise the let bindings but this didn't work.

A: So we have incoming e::Event t a
Applying runEvent to e gives us still an Event t a in the second element of the tuple, is it not so? But it should rather be Event t b , right?
(The error is quite confusing because it arises resp. go and uses the fresh type variables that have been used in type checking go)


text:
Q: Pointer to own data type in VBA I want to make a pointer to my own data type in VBA and then use something like myDataType.vbString, but I'm doing it in the wrong way. I couldn't find the solution, does anyone know what I'm doing wrong?
Type myDataType
    exampleString As String
    exampleInteger As Integer
End Type

Dim exampleType As myDataType
exampleType.exampleString = "Example"
exampleType.exampleInteger = 0

Dim examplePointer As LongPtr
examplePointer = VarPtr(exampleType)

' This is what I want to (or something like it)
' But it gives an error on the dot exampleString
If examplePointer.exampleString = "Example" Then
' Do something
Else: 'Do something else
End If

A: In VBA, the LongPtr data-type is not really a pointer, but a utility that represents the memory address of a variabe, in order to call external API's (DLL's) that require such pointers.
Therefore, in VBA you cannot explicitly dereference a pointer a la C or C++. However, pointers exist implicitly, similarly to Java: when you declare an object variable, you are imlicitly declaring a pointer. Example:
Dim sh as Excel.Worksheet '<~~ sh is a pointer, so far null because the object is not created yet.
Set sh = Application.Worksheets.Add '<~~ sh now points to the newly created worksheet object.

You can also create you own Class, but it needs to be in its own class module that has its name. For example, you can create a class module called MyDataType
' Class module MydataType
   Public exampleString As String
   Public exampleInteger As Integer

and you can instanciate it in another module
Dim exampleType As myDataType '<~~ null pointer declared
Set exampleType = new myDataType '<~~ now pointer is valid
exampleType.exampleString = "Example"
exampleType.exampleInteger = 0

Again, the LongPtr data type is just a utility to call external API's, not a real VBA data type. I hope this helps clarifying the concept.


text:
Q: Laravel elixir - more specific error messages from gulp I'm receiving the following error when trying to compile the less files for a theme that I purchased that was packaged with less files.  Here's the output I'm seeing:
$ gulp
[22:53:49] Using gulpfile ~/path/to/gulpfile.js
[22:53:49] Starting 'default'...
[22:53:49] Starting 'less'...
[22:53:49] Running Less: resources/assets/less/style.less
[22:53:49] Finished 'default' after 524 ms
[22:53:50] gulp-notify: [Laravel Elixir] Less Compilation Failed!: no writecb in Transform class
[Error: no writecb in Transform class]

How can I obtain a more specific error message?  Googling this error message yielded no useful results.

A: From : http://irclogs.laravel.io/2015-04-20/21:52#log-5535750377c0282818000bdd

so yeah, if anyone comes in with the same question as i do, the current >version of laravel-elixir is broken since gulp-less@3.0.3 seems to be broken. >you'd first have to install gulp-less@3.0.2 and then laravel-elixir

So when this solution helps you, credits should go to @madwasp at irclogs.laravel.io.
I also think: https://github.com/plus3network/gulp-less/issues/166 confirms the issue with gulp-less@3.0.3


text:
Q: Jboss shows error with datasource on startup On starting jboss I am getting the following error :
--- MBEANS THAT ARE THE ROOT CAUSE OF THE PROBLEM ---
ObjectName: jboss.jca:service=DataSourceBinding,name=DefaultDS
  State: NOTYETINSTALLED
  Depends On Me:
    jboss.ejb:service=EJBTimerService,persistencePolicy=database
    jboss:service=KeyGeneratorFactory,type=HiLo
    jboss.mq:service=StateManager
    jboss.mq:service=PersistenceManager

And for all database connections in the servlet I get the following exception :
 org.postgresql.util.PSQLException: FATAL: password a
uthentication failed for user "poll"

It was working fine and all of a sudden I started getting these errors. My password is correct. I even tried changing the password and then tried again it showed the same exception. What is happening here?

A: The DefaultDS data source is what the name suggests; the default datasource. It ships with JBoss and is configured to use the Hypersonic (ie in-memory) database. JBoss uses the DefaultDS datasource to read/write internal queues, timed events, etc
Check the file ../conf/standardjbosscmp-jdbc.xml to see what you've got configured for the DefaultDS datasource. It sounds like you've edited that file unintentionally. Unless you need to persist internal queues etc across boots, just leave it as shipped using Hypersonic.
See the JBoss doc for more.