Q:

RingCentral Meetings API Error - "user needs to have [Meetings] permission for requested resource"

I have created an app for reading meeting list and I'm getting this error below although I have set permission for Meetings.
API:
GET /restapi/v1.0/account/{accountId}/extension/{extensionId}/meeting

Error:
{
  "errorCode":"CMN-408",
  "message":"In order to call this API endpoint, user needs to have [Meetings] permission for requested resource.",
  "errors":[
    {
      "errorCode":"CMN-408",
      "message":"In order to call this API endpoint, user needs to have [Meetings] permission for requested resource.",
      "permissionName":"Meetings"
    }
  ],
  "permissionName":"Meetings"
}

Ref: https://developer.ringcentral.com/api-docs/latest/index.html#!#RefMeetingsList.html

A:

User vs App Permissions
When an app requests access to a user resources like Meetings via the REST API, it uses an access token which is associated with both the app and user that authorized the app. An API may require both an app and a user permission. When the permission returns with the error user needs to have as shown below, it means the user permission is needed.
In order to call this API endpoint, user needs to have [Meetings] permission \
for requested resource.

There are three components to resolving this:

Checking the User Permission
Finding the Display Name of the Permission
Adding the Permission to the User

1. Checking User Permission
The text within the brackets is the permissionId. You can check whether your user has this permission by calling the permission check API as follows:
GET /restapi/v1.0/account/~/extension/~/authz-profile/check?permissionId=Meetings

You will get a response like the following. The successful property will show true or false depending on whether the user has the specific permission. If you are seeing this error, successful should be set to false.
{
  "uri":"https://platform.ringcentral.com/restapi/v1.0/account/11111111/extension/22222222/authz-profile/check?permissionId=Meetings&targetExtensionId=11111111",
  "successful":true,
  "details":{
    "permission":{
      "uri":"https://platform.ringcentral.com/restapi/v1.0/dictionary/permission/Meetings",
      "id":"Meetings",
      "assignable":true,
      "readOnly":false,
      "siteCompatible":"Independent"
    },
    "effectiveRole":{
      "uri":"https://platform.ringcentral.com/restapi/v1.0/dictionary/user-role/3",
      "id":"3"
    },
    "scopes":[
      "Self"
    ]
  }
}

Ref: https://developer.ringcentral.com/api-docs/latest/index.html#!#RefCheckUserPermissions

2. Finding the Display Name of the Permission
To add this permission to the user, it is necessary to get the Display Name of the permission which will be used in adding this permission via the Online Account Portal (https://service.ringcentral.com for production).
You can get this info by calling the permission's dictionary endpoint where permissionId is Meetings as shown below.
GET /restapi/v1.0/dictionary/permission/{permissionId}
GET /restapi/v1.0/dictionary/permission/Meetings

The response will have a displayName property indicating "Meetings App Access" is the UI permission in the Online Account Portal.
Alternately, you can make an API call to get a list of permissions and look for the permissionId which is Meetings here. In the response excerpt below, the "displayName":"Meetings App Access" is set for "id":"Meetings".
GET /restapi/v1.0/dictionary/permission

You will get a response like the following. I've removed all other permissions for brevity:
{
  "uri":"https://platform.ringcentral.com/restapi/v1.0/dictionary/permission?page=1&perPage=100",
  "records":[
    {
      "uri":"https://platform.ringcentral.com/restapi/v1.0/dictionary/permission/Meetings",
      "id":"Meetings",
      "displayName":"Meetings App Access",
      "assignable":true,
      "readOnly":false,
      "siteCompatible":"Independent",
      "category":{
        "uri":"https://platform.ringcentral.com/restapi/v1.0/dictionary/permission-category/Meetings",
        "id":"Meetings"
      },
      "includedPermissions":[

      ]
    }
  ]
}

Ref: https://developer.ringcentral.com/api-docs/latest/index.html#!#RefDictionaryPermissionList.html

3. Adding the Permission to the User
Now go to the RingCentral Online Account Portal and ensure the user has this permission in their role.
The Online Account Portal is at:

Production environment: https://service.ringcentral.com
Sandbox environment: https://service.devtest.ringcentral.com

After you log in, use the following instructions to find the user's role and ensure the role has the "Meetings App Access" permission:

KB: How do I set up User Roles and Permissions? How do I assign a specific role to Users?

It will look like the following in the UI:


Q:

Motion detection by eliminating constant movements

I am trying to implement a motion detection in OpenCV C++. I tried various methods like MOG, Optical flow which work fine but is there a way we can eliminate constant movements in the scene like a constant fan motion etc ? I have opencv accumuateWeighted() in mind but not sure if it works. Is there any better way we can do it ?

A:

I have not got full robust solution and also i don't have any experience with video processing but i would put my idea whatever till now i have got in to this problem:
First consider a few pairs of consecutive image frames from the video and convert them to gray scale for more robust comparison.
Raster scan the image pairs and find the difference of image pairs by comparing corresponding pairs.
The resultant image will give the pixel location where there is a change in image to image in a pair, cluster these pixels locations and make a bounding box over them. So that this bounding box region will mark an object which is translating/rotation.
Now as we have applied the above image difference operation over several pairs. We will have rotating/translating bounding box in each image pair difference.
Now check in each resultant image difference with pixels having bounding box over them.
Compare bounding box central location in a difference image with other difference images. If bounding box with a very slight variation in its central location exists across all difference images then object contained in that bounding box will be having rotational motion like Fan,leaves and remaining bounding boxes will represent the actual translating objects in the video.


Q:

Eclipse CDT: Symbol 'cout' could not be resolved

The error is as above. I have what should be all the necessary files include in the eclipse project:
/usr/include/c++/4.6
/usr/include
/usr/include/linux
/usr/local/include

etc.
I tried std::cout and using namespace std; cout but it still says unresolved.
I have imported iostream and cstdlib.
Also, I'm on Ubuntu 12.04 with eclipse 3.7.2.
Code snippet:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "XPLMDisplay.h"
#include "XPLMGraphics.h"

int XPluginStart(char * outName,  char * outSig,  char * outDesc) {
    /* ... */
    std::cout << "test" << std::endl;
    /* ... */
}

using namespace std;

UPDATE: I had created the eclipse project from existing code. Creating a new c++ project fixes it. I'll accept an answer that explains what setting in the existing project could cause this (so I don't have to cut & paste all my projects).

A:

Most likely you have some system-specific include directories missing in your settings which makes it impossible for indexer to correctly parse iostream, thus the errors. Selecting Index -> Search For Unresolved Includes in the context menu of the project will give you the list of unresolved includes which you can search in /usr/include and add containing directories to C++ Include Paths and Symbols in Project Properties.
On my system I had to add /usr/include/c++/4.6/x86_64-linux-gnu for bits/c++config.h to be resolved and a few more directories.
Don't forget to rebuild the index (Index -> Rebuild) after adding include directories.

A:

To get rid of symbol warnings you don't want, first you should understand how Eclipse CDT normally comes up with unknown symbol warnings in the first place. This is its process, more or less:

Eclipse detects the GCC toolchains available on the system
Your Eclipse project is configured to use a particular toolchain
Eclipse does discovery on the toolchain to find its include paths and built-in defines, i.e. by running it with relevant options and reading the output
Eclipse reads the header files from the include paths
Eclipse indexes the source code in your project
Eclipse shows warnings about unresolved symbols in the editor

It might be better in the long run to fix problems with the earlier steps rather than to override their results by manually adding include directories, symbols, etc.
Toolchains
If you have GCC installed, and Eclipse has detected it, it should list that GCC as a toolchain choice that a new C++ project could use, which will also show up in Window -> Preferences -> C/C++ -> New CDT Project Wizard on the Preferred Toolchains tab's Toolchains box on the right side. If it's not showing up, see the CDT FAQ's answer about compilers that need special environments (as well as MinGW and Cygwin answers for the Windows folk.)
If you have an existing Eclipse C++ project, you can change the associated toolchain by opening the project properties, and going to C/C++ Build -> Tool Chain Editor and choosing the toolchain you want from the Current toolchain: pulldown.  (You'll have to uncheck the Display compatible toolchains only box first if the toolchain you want is different enough from the one that was previously set in the project.)
If you added a toolchain to the system after launching Eclipse, you will need to restart it for it to detect the toolchain.
Discovery
Then, if the project's C/C++ Build -> Discovery Options -> Discovery profiles scope is set to Per Language, during the next build the new toolchain associated with the project will be used for auto-discovery of include paths and symbols, and will be used to update the "built-in" paths and symbols that show up in the project's C/C++ General -> Paths and Symbols in the Includes and Symbols tabs.
Indexing
Sometimes you need to re-index again after setting the toolchain and doing a build to get the old symbol warnings to go away; right-click on the project folder and go to Index -> Rebuild to do it.
(tested with Eclipse 3.7.2 / CDT 8)

A:

Thanks loads for the answers above.  I'm adding an answer for a specific use-case...
On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration as well as to add /usr/include/c++/4.7, /usr/include and /usr/include/c++/4.7/x86_64-linux-gnu to Project Properties -> C/C++ General -> Paths and Symbols and then to rebuild the index.


Q:

R issue on optim() with a function depending on a loop

it's a simple issue about optim() function on R. I am trying to find the mimimum of a function depending on a loop's variable.
f<-function(x,i){
  i*x
}

M<-matrix(0,10,1)

  for (i in 1:5) {
    M[i,1]<-optim(c(1),f,lower=-2,upper=2,method="L-BFGS-B")
  }
M

R answers me :
Erreur dans i * x : 'i' est manquant

I really don't understand how to deal with this one....

A:

You have to pass i to the optim call:
optim(1,f,i=i,lower=-2,upper=2,method="L-BFGS-B")

...and optim returns a list, so you need to pick which element in the list you want to store in M.  I assume you want par:
M[i,1] <- optim(1,f,i=i,lower=-2,upper=2,method="L-BFGS-B")$par

UPDATE:
As Justin pointed out in the comments, the more R-like way to do this would be:
L <- list()
for (i in 1:5) {
    L[[i]] <- optim(1,f,i=i,lower=-2,upper=2,method="L-BFGS-B")
}
V <- sapply(L, `[[`, "par")


Q:

ProgressBar not updating

I have a WPF form containing a button and a progress bar element. When I click the button it calls a function from another class that begins a background worker which is responsible for reading/writing data through a serial port to a device I am programming a windows interface for.
Previously I was using a new thread, but I decided to try a background worker, but still no luck.
What is happening is I click the button and the progress bar stays at 0% until my time consuming (10+ seconds) for loop is finished, and then the progress jumps to 100%
Any help is appreciated, thanks in advance. Below is the code for my interface logic:
private void connectButton_Click(object sender, RoutedEventArgs e) //Connect button clicked
    {
        if (!Global.isConnected)
        {
            device.readValues((string)portsOpen.SelectedValue, connectProgress);

            portsOpen.IsEnabled = false;
            connectButton.Content = "Disconnect";
        }
        else
        {
            device.disconnect();

            portsOpen.IsEnabled = true;
            connectButton.Content = "Connect";
        }
    }

And below is the code for my additional class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Controls;
using System.ComponentModel;

namespace lookoutSecurity
{
    class agentRadioRead
    {
    /*Local Variable Declarations*/
    SerialPort sp;
    BackgroundWorker worker;
    int attempt = 0;

    public string[] populateAvailablePorts() //Returns string array of open ports
    {
        String[] portsAvailable = SerialPort.GetPortNames();
        return portsAvailable;
    }

    public void readValues(string selectedPort, ProgressBar progressBar) //Function that sets up serial port and background worker
    {
        sp = new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);

        worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.RunWorkerAsync(progressBar);
    }

    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) //Update user interface with current percentage
    {
        ProgressBar progressBar = e.UserState as ProgressBar;

        App.Current.Dispatcher.Invoke(
            System.Windows.Threading.DispatcherPriority.Send,
                new Action(
                    delegate()
                    { progressBar.Value = e.ProgressPercentage; }));
    }

    private void worker_DoWork(object sender, DoWorkEventArgs e) //Initial starting point for reading data
    {
        startRead((ProgressBar)e.Argument);
    }

    private string sendInitial() //Sends ? and returns init ASUTTON
    {
        string init = "";
        sp.Write("?");

        for (int i = 0; i < 7; i++)
        {
            try
            {
                init += sp.ReadByte().ToString();
            }
            catch
            {
                break;
            }
        }

        return init;
    }

    private void startRead(ProgressBar progressBar) //Initializes data send and receive
    {
        sp.ReadTimeout = 5000;
        sp.Open();

        string init = sendInitial();

        if (init == Global.AGENT_RADIO)
        {
            sp.Write(Global.READ_VALUES, 0, Global.READ_VALUES.Length);

            byte key = (byte)sp.ReadByte();

            if (Global.START_COMMAND == key)
            {
                for (int i = 1; i < 2247; i++)
                {
                    object progressBarObject = new object();
                    progressBarObject = progressBar;
                    int progress = (i / 2246) * 100;
                    worker.ReportProgress(progress, progressBarObject);

                    readData(i, progressBar);
                    sp.Write(Global.GO_AHEAD, 0, Global.GO_AHEAD.Length);

                    sp.DiscardInBuffer();
                    sp.DiscardOutBuffer();
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Connection Failed - Invalid Key: " + key);
                sp.Close();
            }
        }
        else
        {
            sp.Close();

            if (attempt < 3)
            {
                attempt++;
                startRead(progressBar);
            }
            else
            {
                System.Windows.MessageBox.Show("Connection Failed - Not Agent Radio: " + init);
            }
        }
    }

    private void readData(int iteration, ProgressBar progress) //Reads data for current iteration
    {
        byte value = 0;

        try
        {
            value = (byte)sp.ReadByte();
        }
        catch
        {
            sp.Close();
            Global.isConnected = false;

            if (attempt < 3)
            {
                attempt++;
                startRead(progress);
            }
            else
            {
                System.Windows.MessageBox.Show("Read Timeout - Value Number: " + iteration);
                App.Current.Shutdown();
            }
        }

        if (iteration > 0 && iteration < 385) //read schedule
        {
            double pos = (iteration - 1) / 48;

            int i = (int)Math.Floor(pos);
            int j = (iteration - 1) - (i * 48);

            Live.schedule[i, j] = value;
        }

        if (iteration > 384 && iteration < 1285) //read alarm history
        {
            double pos = (iteration - 385) / 9;

            int i = (int)Math.Floor(pos);
            int j = (iteration - 385) - (i * 9);

            Live.alarms[i, j] = value;
        }

        if (iteration > 1284 && iteration < 1345) //read error log
        {
            double pos = (iteration - 1285) / 6;

            int i = (int)Math.Floor(pos);
            int j = (iteration - 1285) - (i * 6);

            Live.errors[i, j] = value;
        }

        if (iteration > 1344 && iteration < 1945) //read voltage history
        {
            double pos = (iteration - 1345) / 6;

            int i = (int)Math.Floor(pos);
            int j = (iteration - 1345) - (i * 6);

            Live.voltage[i, j] = value;
        }

        if (iteration > 1944 && iteration < 1973) //read holidays
        {
            Live.holidays[iteration - 1945] = value;
        }

        if (iteration > 1972 && iteration < 2168) //read message sequences
        {
            double pos = (iteration - 1973) / 15;

            int i = (int)Math.Floor(pos);
            int j = (iteration - 1973) - (i * 15);

            Live.messages[i, j] = value;
        }

        if (iteration > 2167 && iteration < 2196) //read message info
        {
            Live.recordings[iteration - 2168] = value;
        }

        if (iteration > 2195 && iteration < 2246) //read sysval
        {
            Live.sysval[iteration - 2196] = value;
        }

        if (iteration == 2246 && value == Global.FINISH_COMMAND)
        {
            System.Windows.MessageBox.Show("All values from the device have been received.", "Data Received", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);

            Global.isConnected = true;
        }
    }

    public void disconnect() //Disconnects device
    {
        if (Global.isConnected == true)
        {
            sp.Write(Global.EXIT_PROGRAM, 0, Global.EXIT_PROGRAM.Length);
            Global.isConnected = false;
        }
    }
}
}

A:

Your problem is here:
int progress = (i / 2246) * 100;

i/2246 will give an int, which will be truncated to zero (because i runs from 0 to < 2246), which * 100 gives zero. Until your loop ends, when i = 2246 and 2246 / 2446 * 100 = 100.
I've fallen for that before myself. You need to cast i to a float (or double) so that it does floating point division instead of integer division. Then you'll need to cast everything back to an int since progress is an int.
Something like:
int progress = (int)((float)i/2246.0) * 100;

A:

That is mainly due to the following:
int progress = (i / 2246) * 100;

progress is always 0 until i>2246 and that is why you get a progress value of 0 until the last loop iteration where progress is equal to 1*100=100
You should do this instead:
int progress = (int)(((double) i / 2246.0) * 100);


Q:

How can I donate to Ubuntu without PayPal?

When I wanted to download Ubuntu 12.10 from ubuntu.com, I was asked to make a donation. However, there is only a PayPal option to make the payment. But I don't use PayPal. Is there any other option to make the payment?

A:

Currently you can only donate to Canonical directly with PayPal. According to Jono Bacon, "other payment mechanisms are currently being explored as we speak."
Another option for you is to donate to the projects behind applications that you often use or would like to support. Simply contact the software developers directly and ask them about it.
Or send a real physical postcard to a developer where you thank him for his work, i am sure many open source developers appreciate some kind words just as much as money.

A:

You do not have to actually have a PayPal account in order to donate using PayPal.  You can use your credit/debit card to donate.  After clicking the "Pay with PayPal" button, you'll get another screen.  Click "Pay with your debit or credit card as a PayPal guest."

Now, if you just hate PayPal, and refuse to use it at all, I can't help you there! :)


Q:

Netbeans Including XML and Properties when building Spring projects with Maven

I am new to Maven and Spring.  I'm using Netbeans 7 as my IDE, and setting up a Spring 3 project using Maven.
Everything seemed to set up smoothly, and I began running through the Spring User Guide.  However, I'm getting a file not found exception when trying to load my context.xml file.
I have an App class located at com.myproject and the context.xml file is located at com.myproject.conf
I'm using the following line of code in App.java to try and load the context.xml file:
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

But when I run the application, it results in:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [context.xml]; nested exception is java.io.FileNotFoundException: class path resource [context.xml] cannot be opened because it does not exist

Looking at the NetBeans output, it also looks like it's not picking up the log4j.properties file which is also located in com.myproject.conf
I looked at the jar that the build process created, and the entire com.myproject.conf package is missing, meaning the .xml and .properties are missing as well.  I've tried moving these config files to the com.myproject package as well as just putting them at the root of the project which don't yield any different results.
So I'm making the assumption that my maven project isn't set up entirely correctly, or maybe a setting isn't correct within NetBeans.

A:

It seems like you need to learn about resources in Maven projects (such as XML, bitmaps, etc...). These are stored in separate directories. See here.


Q:

Show that the function is well-defined and find its derivative and a closed form

Explain why the function
   $$f(x):=\int_0^x{\sin t \cdot \cos (xt) \over t }dt$$
  is well-defined and compute its derivative $\;f'(x)$ in a closed form.

I am a bit confused and don't know where I should start at. Seems to me, that calculating this integral is not an option to explain that the function is well-defined.
I have tried to find its derivative using differentiation under an integral sign. However I am not sure if it is allowed, since $x$ stays not only under the integral sign, but also is an integration border.
How do I tackle the problem?

A:

The functions $f(t)=\frac{\sin t}{t}$ and $g(t)=\cos(xt)$ are both continuous and bounded, hence $f(x)$ is a $C^1$ Lipschitz function. Moreover, you can remove the $x$ from appearing in the integral by substituting $xw$ in place of $t$:
$$\begin{eqnarray*}\int_{0}^{x}\frac{\sin(t)\cos(xt)}{t}\,dt &=& \int_{0}^{1}\frac{\sin(xw)\cos(x^2 w)}{w}\,dw\\ &=& \frac{1}{2}\int_{0}^{1}\frac{\sin((x-x^2)w)+\sin((x+x^2)w)}{w}\,dw.\end{eqnarray*}$$


Q:

Does excessive sugar intake cause diabetes?

Assuming no weight gain, does a large amount of refined sugar intake increase the risk of diabetes?
To put it another way: In theory, if you took two identical subjects, and they each consumed the same amount of calories, but Subject A received 5% of their calories from refined sugar, while Subject B received 25% of their calories from refined sugar, would Subject B have an increased risk of diabetes?

A:

A common conclusion from studies is that high intake of sugars is associated with increased risk of diabetes type 2, but it is not clear if this is due to sugar intake itself or due to associated weight gain.
1. Malik VS et al, 2010, Sugar-Sweetened Beverages and Risk of Metabolic Syndrome and Type 2 Diabetes, a meta analysis (PubMed Central)

In addition to weight gain, higher consumption of SSBs is associated
  with development of metabolic syndrome and type 2 diabetes.

Comment: It is not clear, if this effect is due to weight gain or sugar intake itself.
2. Greenwood DC et al, 2014, Association between sugar-sweetened and artificially sweetened soft drinks and type 2 diabetes: systematic review and dose-response meta-analysis of prospective studies (PubMed)

The intake of sugar-sweetened soft drinks has been reported to be
  associated with an increased risk of type 2 diabetes, but it is
  unclear whether this is because of the sugar content or related
  lifestyle factors, whether similar associations hold for artificially
  sweetened soft drinks, and how these associations are related to BMI.

3. Schulze MB et al, 2004, Sugar-Sweetened Beverages, Weight Gain, and Incidence of Type 2 Diabetes in Young and Middle-Aged Women (JAMA)

Higher consumption of sugar-sweetened beverages is associated with a
  greater magnitude of weight gain and an increased risk for development
  of type 2 diabetes in women, possibly by providing excessive calories
  and large amounts of rapidly absorbable sugars.

4. Imamura F et al, 2015, Consumption of sugar sweetened beverages, artificially sweetened beverages, and fruit juice and incidence of type 2 diabetes: systematic review, meta-analysis, and estimation of population attributable fraction (The BMJ)

Habitual consumption of sugar sweetened beverages was associated with
  a greater incidence of type 2 diabetes, independently of
  adiposity. None the less, both artificially sweetened beverages and
  fruit juice were unlikely to be healthy alternatives to sugar
  sweetened beverages for the prevention of type 2 diabetes.

5. Scientific Report of the 2015 Dietary Guidelines Advisory Committee:
What is the relationship between the intake of added sugars and the risk of type 2 diabetes? (Health.gov)

Strong evidence shows that higher consumption of added sugars,
  especially sugar-sweetened beverages, increases the risk of type 2
  diabetes among adults and this relationship is not fully explained by
  body weight.


Q:

Error in function mssql_connect()

Possible Duplicate:
mssql_connect in php does not exist

How to solve the following error

Fatal error: Call to undefined function mssql_connect() in /var/www/delhunt/MSSQLTest.php on line 8

A:

You have to enable msssql functions from the php.ini file and check for php_mssql.dll  in the php extensions folder


Q:

Print user input using python

I am trying to print the user input of a package name. I have the following code.
packageList = []
package = input("Enter name: ")
while package == '' :
    print("Package name cannot be blank")
    packagename = input("Enter name: ")
    packageList.append(packageName)

print ((packageName) + "added")

I'm not sure what I'm doing wrong. An error is being displayed: UnboundLocalError: local variable 'packageName' referenced before assignment

A:

Your code is giving you errors because you're mixing up the use of variables package and packageName, when it looks like you should be using the same variable in both places.
The code in aj8uppal's answer corrects most of this (by replacing most references to both variables with packagename), but he never clearly describes that this is the problem (and he still leaves one reference to package in the while condition).
Here's some actually fixed code:
packageList = []
package = input("Enter name: ")

while package == '' :
    print("Package name cannot be blank")
    package = input("Enter name: ")               # assign to package variable here

packageList.append(package)                       # unindent, and use package again

print ((package) + "added")                       # use package rather than packageName


Q:

Object-Oriented Programming with Attribute Error

This is my first non-MATLAB programming language so I am having some trouble with object-oriented programming. Specifically, I am working on a program that simulates a blackjack game. It was functioning but I have tried adding some new functionality in allowing players to make bets
To surmise, BJ Player is an object that was a collection of card objects.  Def_init used to just have self and names as parameters, but I added startingmonies (starting money that the player is wagering.) The superclass of BJ player is ultimately BJ hand. I am now getting an error when calling a method to add a card to that hand. Below is where the error o
class BJ_Game(object):
""" A Blackjack Game. """
def __init__(self, names, startingmonies):
    self.players = []
    for name in names:
        player = BJ_Player(name)
        spot = names.index(name)
        startingscratch = startingmonies[spot]
        player_with_money = (name, startingscratch,0)
        self.players.append(player_with_money)

This is where the error originates (cards module that is imported into the BJ module used above):
class Hand(object):
""" A hand of playing cards. """
def __init__(self):
    self.cards = []

def __str__(self):
    if self.cards:
       rep = ""
       for card in self.cards:
           rep += str(card) + "\t"
    else:
        rep = "<empty>"
    return rep

def clear(self):
    self.cards = []

def add(self, card):
    self.cards.append(card)

def give(self, card, other_hand):
    self.cards.remove(card)
    other_hand.add(card)

This is the error that I get.:
 line 47, in give
    other_hand.add(card)
AttributeError: 'tuple' object has no attribute 'add'
I get this error when trying to deal cards. Everything else worked before so the only real change that I made is adding the bet parameter. I researched this issue and was not able to gain a strong understanding. Any assistance would be greatly appreciated. Thank you!
Here is some more information. I think the error is happening because I changed self.players to be a list of tuples. I am not sure how to fix this though.
for index, player in enumerate(self.players):
        flag = 1
        while flag:
            try:
                (name, players_cache,bet) = player
                print(players_cache)
                print("Current player:",name)
                bet = int(input("Please select how much this player would like to wager: "))
                if bet <= 0:
                    print("Bet must be greater than 0")
                elif bet <= players_cache:
                    flag = 0
                    players_cache-=bet
                    player = (name,players_cache,bet)
                    self.players[index] = player
                else:
                    print("Insufficient funds. PLayer only has",players_cache,"dollars available")
            except ValueError:
                print("Input must be a number\n")

    # deal initial 2 cards to everyone
    self.deck.deal(self.players + [self.dealer], per_hand = 2)

I get another part of the error here.
line 169, in play
    self.deck.deal(self.players + [self.dealer], per_hand = 2)
Here is the full error block. Sorry for not showing all of it before:
line 262, in
    main()
  line 258, in main
    game.play(max_Cards)
   line 169, in play
    self.deck.deal(self.players + [self.dealer], per_hand = 2)
   line 65, in deal
    self.give(top_card, hand)
   line 47, in give
    other_hand.add(card)
AttributeError: 'tuple' object has no attribute 'add'

A:

You are passing a tuple object to give method, instead of a Hand instance explaining why add method is not defined. Since you haven't mentioned the call to give method in your code, I couldn't give the pointer to the exact line.


Q:

Broadcom NetLink BCM5906M driver

I have bought a laptop today, but I'm not able to find the ethernet controller driver.
The drivers from Broadcom and Google are not the same version and are not compatible.
Can someone tell me where can I download BCM5906M driver for Windows XP, please ?

A:

This is a question for Superuser.com, not Stack Overflow.
Knowing the make and model of the laptop would be useful, since Broadcom products may be customized by the OEM that integrates them into their system. A Dell laptop with this chip in it may require different drivers than a ASUS laptop with the same chip due to implementation details.


Q:

read only certain fields in firebase

If I have a database like
users: {
  user1: {
    name:'qwert',
    id: 123,
    num: 9999
  },
  user2: {
    name:'zxcvb',
    id: 456,
    num: 8888
  }
}

How can I read only name of all the users?
My expected result:
{
  user1:{
    name:'qwert'
  },
  user2:{
    name:'zxcvb'
  }
}

If I use this in JavaScript:
ref('users').once('value').then((snap)=>{console.log(snap.val())})

I get all the users with that all their data (but I only want name of each)
What changes should I make in my query to get the expected result?
Any suggestions would be highly appreciated and really helpful. I tried searching through the docs but didn't get what I was trying to look for.

My ultimate aim is to cut down the costs of reading unnecessary data.

A:

There is no way to select only the names from your current data model, Firebase always retrieves full nodes. So you will either have to do what Peter answered, reading all data but extracting the user name client side, or you will have to modify you data model to allow the use-case.
The latter is quite simple. If you want to load a list of user names, you should store a list of user names in the database:
users: {
  user1: {
    name:'qwert',
    id: 123,
    num: 9999
  },
  user2: {
    name:'zxcvb',
    id: 456,
    num: 8888
  }
},
usernames: {
  user1: 'qwert',
  user2: 'zxcvb'
}

With this structure, it is trivial to read only the names.
Also see:

Fetch particular fields from Firebase database
How to pull the data partially from firebase database
More efficient way to retrieve Firebase Data? (a more complex scenario of nesting data)


Q:

Access database runtime error 13 type mismatch

First time posting... I'm sure this is probably something simple so I apologize in advance. This is actually my first time ever working with the VBA and I've come to a problem. I've searched and tried multiple things but still the same problem despite anything I try.
I've moved database to another machine and now I get runtime error 13. Debugger says it's at line 28:
Me!odf = CVDate("01.01.1800")

It's when you click on button which opens new window for searching the database with specific criteria set by user.
Here is the code:
    VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Form_Pregledt"
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Option Compare Database
Private Sub Angioloski_Click()
  Forms!PREGLEDT!Pregledf.Form!Idpregleda.RowSource = "SELECT [Qpregledt].[Idpregleda], [Qpregledt].[Datum], [Qpregledt].[Prezime i ime], [Qpregledt].[Godina rodjenja], [Qpregledt].[Adresa], [Qpregledt].[Telefon], [Qpregledt].[Faks], [Qpregledt].[e-mail] FROM [Qpregledt] WHERE [VRSTA PREGLEDA]=FORMS!PREGLEDT!VRSTA AND [ANGIOLOSKI]=FORMS!PREGLEDT!ANGIOLOSKI  and datum>=forms!pregledt!odf  and datum<=forms!pregledt!dof "
  Forms!PREGLEDT!Pregledf.Form!Idpregleda.Requery
  Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
  Me.Refresh
End Sub

Private Sub do_AfterUpdate()
If IsNull(Me!od) = True Then
Me!odf = CVDate("01.01.1800")
Else
Me!odf = Me!od
End If
If IsNull(Me!do) = True Then
Me!dof = CVDate("01.01.2800")
Else
Me!dof = Me!do
End If
Forms!PREGLEDT!Pregledf.Form!Idpregleda.Requery
Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
Me.Refresh
End Sub

Private Sub Form_Load()
Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
Me!odf = CVDate("01.01.1800")
Me!dof = CVDate("01.01.2800")
Forms!PREGLEDT!Pregledf.Form!Idpregleda.Requery
Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
Me.Refresh
End Sub

Private Sub od_AfterUpdate()
If IsNull(Me!od) = True Then
Me!odf = CVDate("01.01.1800")
Else
Me!odf = Me!od
End If
If IsNull(Me!do) = True Then
Me!dof = CVDate("01.01.2800")
Else
Me!dof = Me!do
End If
Forms!PREGLEDT!Pregledf.Form!Idpregleda.Requery
Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
Me.Refresh
End Sub

Private Sub vrsta_Click()
If Me!vrsta = 1 Then
 Me!Angioloski.Enabled = True
 Else
 Me!Angioloski.Enabled = False
 Me!Angioloski = Null
End If
If IsNull(Me!vrsta) = False Then
 If IsNull(Me!Angioloski) = True Then
  Forms!PREGLEDT!Pregledf.Form!Idpregleda.RowSource = "SELECT [Qpregledt].[Idpregleda], [Qpregledt].[Datum], [Qpregledt].[Prezime i ime], [Qpregledt].[Godina rodjenja], [Qpregledt].[Adresa], [Qpregledt].[Telefon], [Qpregledt].[Faks], [Qpregledt].[e-mail] FROM [Qpregledt] WHERE [VRSTA PREGLEDA]=FORMS!PREGLEDT!VRSTA and datum>=forms!pregledt!odf  and datum<=forms!pregledt!dof "
 Else
  Forms!PREGLEDT!Pregledf.Form!Idpregleda.RowSource = "SELECT [Qpregledt].[Idpregleda], [Qpregledt].[Datum], [Qpregledt].[Prezime i ime], [Qpregledt].[Godina rodjenja], [Qpregledt].[Adresa], [Qpregledt].[Telefon], [Qpregledt].[Faks], [Qpregledt].[e-mail] FROM [Qpregledt] WHERE [VRSTA PREGLEDA]=FORMS!PREGLEDT!VRSTA AND [ANGIOLOSKI]=FORMS!PREGLEDT!ANGIOLOSKI  and datum>=forms!pregledt!odf  and datum<=forms!pregledt!dof"
 End If
End If
Forms!PREGLEDT!Pregledf.Form!Idpregleda.Requery
Forms!PREGLEDT!Pregledf.Form!ukupno.Caption = "Ukupno: " & Forms!PREGLEDT!Pregledf.Form!Idpregleda.ListCount
Me.Refresh
End Sub

Private Sub izlaz_Click()
'On Error GoTo Err_izlaz_Click
On Error Resume Next

    DoCmd.Close

Exit_izlaz_Click:
    Exit Sub

Err_izlaz_Click:
    MsgBox Err.Description
    Resume Exit_izlaz_Click

End Sub

A:

Like Tim says in the comments, your date separator is wrong. However, personally I'd avoid the ambiguities of strings in the first place (what date is 01/03/02?) and use the DateSerial function:
Me!odf = DateSerial(1800, 1, 1)


Q:

Domain of $f(g(x)),g(f(x)),f(f(x))$ in composite function

If $\displaystyle f(x)=4/x$ and $g(x)=4x+1$. Then domain of $f(g(x)),g(f(x)),g(g(x)),f(f(x))$ are

What i try: $$f(g(x))=\frac{4}{g(x)}=\frac{4}{4x+1}$$
So domain is $\displaystyle x\in\mathbb{R}-\{\frac{1}{4}\}$
$$g(f(x))=4f(x)+1=\frac{16}{x}+1$$
So domain is $x\in\mathbb{R}-\{0\}$
$$f(f(x))=\frac{4}{f(x)}=x$$
So domain is $x\in\mathbb{R}$
But domain not matched with answer.
Please tell me where i am missing
Thanks

A:

In general, if you have two functions $F$ and $G$, the "largest domain" to $G\circ F$ is
$$\{x \in \mbox{dom}(F) : F(x)\in\mbox{dom}(G)\} \ ,$$
which is simply $\mbox{dom}(F)\cap F^{-1}(\mbox{dom}(G))$.
In that way, we always have $\mbox{dom}(G\circ F) \subseteq \mbox{dom}(F)$.


Q:

vector subscription out of range c++

I am working on a program that reads integers from file, stores it in vector and use count sort to sort the integers and write them in new file. My problem ocurs when i run Countsort function, the breakpoint happens at this for loop:
for (int i = 0; i < C.size(); i++) {
    C[A[i]] = C[A[i]] + 1;
}

my code looks like this:
    //COUNT SORT
void countsort() {

    int max = A[0];

    for (int i = 1; i < A.size(); i++) {
        if (A[i] > max) {
            max = A[i];
        }
    }
    //cout << "NAJVECJE STEVILO JE: " << max << endl; SAMO ZA TEST
    vector<int> C(max + 1);
    vector<int> B(A.size());

    for (int i = 0; i < C.size(); i++) {
        C[A[i]] = C[A[i]] + 1;
    }

    for (int i = 1; i < C.size(); i++) {
        C[i] = C[i] + C[i + 1];
    }

    for (int i = C.size() - 1; i >= 0; i--) {
        B[C[A[i]] - 1] = A[i];
        C[A[i]] = C[A[i]] - 1;
    }

    for (int i = 0; i < A.size(); i++) {
        A[i] = B[i];
    }
}

A:

Before you write something to B vector you should probably initialize it firt like you did with C.
B = vector<int>(A.size());

Also I don't see any point of printing B[i] as it may not be assigned any value when you print it.
Edit #1
Your loop is not correct. Take a look at this:
for (int i = 1; i < C.size(); i++) {
    C[i] = C[i] + C[i - 1];
}

Edit #2
Try this code.
vector<int> A, B;
//COUNT SORT
void countsort() {
    int max = A[0];
    for (int i = 1; i < A.size(); i++) {
        if (A[i] > max) {
            max = A[i];
        }
    }
    vector<int> C(max + 1);
    B = vector<int>(A.size());

    for (int i = 0; i < C.size(); i++) C[i] = 0;
    for (int i = 0; i < A.size(); i++) C[A[i]] = C[A[i]] + 1;
    for (int i = 1; i < C.size(); i++) C[i] = C[i] + C[i - 1];

    for (int i = A.size() - 1; i >= 0; i--) {
        B[C[A[i]] - 1] = A[i];
        C[A[i]] = C[A[i]] - 1;
    }

    for (int i = 0; i < B.size(); i++) cout << B[i];
}

int main(void) {
    A.push_back(1);
    A.push_back(2);
    A.push_back(3);
    A.push_back(4);
    A.push_back(2);
    A.push_back(2);
    A.push_back(1);
    countsort();
}


Q:

using getline instead of cin >>

Hey guys so my program is as follows, but when i input a word starting with w,d, b, or q like for example deposit instead of the letter d the program just keeps repeating the initial question of "would you like to withdraw , deposit etc." I tried to convert the cin>> to getline( cin, user_request) but that gave me an error. i am pretty sure the way to fix this is to convert the cin to getline but im not sure how to properly. if anyone can help out. and is there a way to do this program with the cin statements?  :
#include <iostream>
#include <string>
using namespace std;

int main ()
{
   char user_request;
   string user_string;
   double account_balance, dollars_withdraw, dollars_deposit;

   account_balance = 5000;
   user_request= user_string[0];

   while(account_balance =>0)
     {
        cout << "Would you like to Withdraw, Deposit, Check your balance or Quit?"
           << endl;
        cin >> user_request;
        if (user_request == 'w' || user_request== 'W')
        {
           cout << "How much would you like to withdraw?" << endl;
           cin >> dollars_withdraw;
        if (dollars_withdraw > account_balance)
           cout << "Invalid transaction" << endl;
        else
           account_balance = account_balance - dollars_withdraw;
           cout << "Your new balance is $" << account_balance << endl;
        }

        if (user_request == 'd' || user_request== 'D')
        {
           cout << "How much would you like to deposit?" << endl;
           cin >> dollars_deposit;
           account_balance= account_balance + dollars_deposit;
           cout << "Your new balance is $" << account_balance << endl;
        }
        if (user_request == 'b' || user_request == 'B')
      {
           account_balance= account_balance;
           cout << "Your available balance is $" << account_balance << endl;
      }
        if (user_request == 'q' || user_request == 'Q')
           break;
   }

   cout << "Goodbye" << endl;

  return 0;
}

A:

While user_request is a char, then each non-space character in the input will satisfy another cin >> user_request; statement, so entering "deposit" will loop through 7 times, with only the 'd' matching an if statement, but the prompt message being printed each time.
You should change user_request to be a std::string, then getline(cin, user_request) will work, but you'll need to compare user_request's first character (i.e. [0]) to e.g. "w" (a string literal) instead of 'w' (a character literal).
It's also considered good practice to check whether the input request worked - an end-of-file condition would cause your loop to "spin" forever.
It's also a good idea to change your prompt so it mentions the letters you'd like them to type, otherwise they'd probably type e.g. 'c' rather than 'b' for "check balance".  Just cout something like:
Would you like to [W]ithdraw, [D]eposit, Check your [b]alance or [Q]uit?

So, all up:
std::string user_request;

if (not getline(cin, user_request))    // or !getline(...) if your compiler lacks "not"
    break;

if (user_request.empty())
    continue;  // avoid [0] on an empty line, which may crash the program

if (user_request[0] == "w" || user_request[0] == "W")
    ...


Q:

Qt must construct QApplication before a QWidget

Qt recently started crashing without having a reason for it. The most recent one which is currently grinding my nerves down to a pulp is crashing due to starting another form programmatically. The "must construct QApplication before a QWidget" apparently is a common issue with Qt 5.7.* versions and the solutions I have found so far in StackOverflow haven't helped me.
This is a screenshot of the error message I got after the application crashed:

And here is the bit of the code that I remove which allows me to restart the application without any noticeable problems:
#include "operations.h"
Operations o;
void mainWindow::on_thisButton_clicked()
    {
        o.show();
        this->hide();
    }

----
The main.cpp as requested :)
#include "mainWindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mainWindow w;

    w.show();

    return a.exec();
}

A:

Try this:
#include "operations.h"

void mainWindow::on_thisButton_clicked()
{
    Operations *o = new Operations();
    o->show();
    this->hide();
}

You might want to declare Operations *o as a member of mainWindow and initialize it the the constructor if you don't want to create a new one each time the button is clicked.


Q:

How to enable MultipleActiveResultSets

I have the following connection string in my code:
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);

My webconfig for this looks like this:
    <connectionStrings>
<add name="RaiseFantasyLeagueConnectionString" connectionString="Data Source=MATT-PC\SQLEXPRESS;Initial Catalog=Raise;Integrated Security=True" providerName="System.Data.SqlClient"/>

Can somebody tell me where I can enable MultipleActiveResultSets for my connection?

A:

It is really simple, just add
MultipleActiveResultSets=true;

so change, in your web.config, the connection string in this way:
connectionString="Data Source=MATT-PC\SQLEXPRESS;" +
                 "Initial Catalog=Raise;Integrated Security=True;" +
                 "MultipleActiveResultSets=true;"

A:

Try this code
<connectionStrings>
<add name="RaiseFantasyLeagueConnectionString" connectionString="Data Source=MATT-PC\SQLEXPRESS;Initial Catalog=Raise;Integrated Security=True ;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient";/>

Must refer this Msdn article


Q:

Embedding Python in MATLAB

I am trying to embed Python 2.6 into MATLAB (7.12).  I wanted to embed with a mex file written in C.  This worked fine for small simple examples using scalars.  However, if Numpy (1.6.1) is imported in anyway MATLAB crashes.  I say anyway because I have tried a number of ways to load the numpy libraries including

In the python module (.py):
from numpy import *

With PyRun_SimpleString in the mex file:
PyRun_SimpleString(“from numpy import *”);

Calling numpy functions with Py_oBject_CallObject:
pOut  = PyObject_CallObject(pFunc, pArgs);

Originally, I thought this may be a problem with embedding Numpy in C.  However, Numpy works fine when embedded in simple C files that are compiled from the command line with /MD (multithread) switch with the Visual Studios 2005 C compiler.   Next, I thought I will just change the make file in MATLAB to include the /MD switch.  No such luck, mexopts.bat compiles with the /MD switch.  I also manually commented out lines in the Numpy init module to find what was crashing MATLAB.  It seems that loading any file with the extension pyd crashes MATLAB.  The first of such files loaded in NumPy is multiarray.pyd.   The MATLAB documentation describes how to debug mex files with visual studios which I did and placed the error message below.  At this point I know the problem is a memory problem with the pyd’s and some conflict with MATLAB.  Interestingly, I can use a system command in MATLAB to kick off a process in python that uses numpy and no error is generated.  I will paste below the error message from MATLAB followed by the DEBUG output in visual studios of the processes that crash MATLAB.  However, I am not pasting the whole thing because the list of first-chance exceptions is very long.   Are there any suggestions for solving this integration problem?
MATLAB error
Matlab has encountered an internal problem and needs to close
MATLAB crash file:C:\Users\pml355\AppData\Local\Temp\matlab_crash_dump.3484-1:

------------------------------------------------------------------------
       Segmentation violation detected at Tue Oct 18 12:19:03 2011
------------------------------------------------------------------------

Configuration:
  Crash Decoding  : Disabled
  Default Encoding: windows-1252
  MATLAB License  : 163857
  MATLAB Root     : C:\Program Files\MATLAB\R2011a
  MATLAB Version  : 7.12.0.635 (R2011a)
  Operating System: Microsoft Windows 7
  Processor ID    : x86 Family 6 Model 7 Stepping 10, GenuineIntel
  Virtual Machine : Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
  Window System   : Version 6.1 (Build 7600)

Fault Count: 1

Abnormal termination:
Segmentation violation

Register State (from fault):
  EAX = 00000001  EBX = 69c38c20
  ECX = 00000001  EDX = 24ae1da8
  ESP = 0088af0c  EBP = 0088af44
  ESI = 69c38c20  EDI = 24ae1da0

  EIP = 69b93d31  EFL = 00010202

   CS = 0000001b   DS = 00000023   SS = 00000023
   ES = 00000023   FS = 0000003b   GS = 00000000

Stack Trace (from fault):
[  0] 0x69b93d31 C:/Python26/Lib/site-packages/numpy/core/multiarray.pyd+00081201 ( ???+000000 )
[  1] 0x69bfead4 C:/Python26/Lib/site-packages/numpy/core/multiarray.pyd+00518868 ( ???+000000 )
[  2] 0x69c08039 C:/Python26/Lib/site-packages/numpy/core/multiarray.pyd+00557113 ( ???+000000 )
[  3] 0x08692b09                           C:/Python26/python26.dll+00076553 ( PyEval_EvalFrameEx+007833 )
[  4] 0x08690adf                           C:/Python26/python26.dll+00068319 ( PyEval_EvalCodeEx+002255 )

This error was detected while a MEX-file was running. If the MEX-file
is not an official MathWorks function, please examine its source code
for errors. Please consult the External Interfaces Guide for information
on debugging MEX-files.

If this problem is reproducible, please submit a Service Request via:
    http://www.mathworks.com/support/contact_us/

A technical support engineer might contact you with further information.

Thank you for your help.

Output from Visual Studios DEBUGGER
First-chance exception at 0x0c12c128 in MATLAB.exe: 0xC0000005: Access violation reading location 0x00000004.
First-chance exception at 0x0c12c128 in MATLAB.exe: 0xC0000005: Access violation reading location 0x00000004.
First-chance exception at 0x0c12c128 in MATLAB.exe: 0xC0000005: Access violation reading location 0x00000004.
First-chance exception at 0x751d9673 in MATLAB.exe: Microsoft C++ exception: jitCgFailedException at memory location 0x00c3e210..
First-chance exception at 0x751d9673 in MATLAB.exe: Microsoft C++ exception: jitCgFailedException at memory location 0x00c3e400..
First-chance exception at 0x69b93d31 in MATLAB.exe: 0xC0000005: Access violation writing location 0x00000001.
> throw_segv_longjmp_seh_filter()
throw_segv_longjmp_seh_filter(): invoking THROW_SEGV_LONGJMP SEH filter
> mnUnhandledWindowsExceptionFilter()
MATLAB.exe has triggered a breakpoint

A:

Try to approach the problem from the Python side: Python is a great glue language, I would suggest you to have Python run your Matlab and C programs. Python has:

Numpy
PyLab
Matplotlib
IPython

Thus, the combination is a good alternative for almost any existing Matlab module.


Q:

Induced isomorphism of homology implies isomorphism with coefficients in any group?

If $\alpha\colon C \to C'$ is a map of chain complexes (of free abelian groups) that induces an isomorphism  on homology $a_{*} \colon H_n(C) \simeq H_n(C')$, then I know that $\alpha$ induces an isomorphism on cohomology $a^{*} \colon H^n(C;G) \simeq H^n(C';G)$ with coefficients in any abelian group $G$. But is it also true that $\alpha$ induces an isomorphism on homology $a_{*} \colon H_n(C;G) \simeq H_n(C';G)$ with coefficients in any abelian group $G$ or (more likely) is there some counterexample?

A:

Here is an answer assuming that $\alpha$ is a chain map; without this assumption I do not see how you can talk about induced maps of integer homology groups. Then the answer to your question is positive and follows from the Universal coefficient Theorem (UCT). Indeed, since $\alpha$ is a chain map, it induces maps $\alpha_{i*}: H_i(C; G)\to H_i(C'; G)$ for arbitrary abelian groups $G$. Since the statement of the UCT provides a natural short exact sequence, we get isomorphisms
$$
\beta_i: H_i(C)\otimes G \to H_i(C')\otimes G
$$
$$
\gamma_i: Tor(H_{i-1}(C), G)\to Tor(H_{i-1}(C'), G)
$$
which (together with $\alpha_{i*}$) make a commutative diagram with UCT sequences for $C, C'$ on the top and on the bottom. (Sorry, I am not very good at drawing diagrams in the version of TeX used at MSE.) Now, the fact that $\alpha_{i*}$ is an isomorphism follows from the diagram chasing in this commutative diagram. For instance, to see injectivity, note that an element $x$ of the kernel has to project to zero in $Tor(H_{i-1}(C), G)$. Hence, it belongs to $H_i(C; {\mathbb Z})\otimes G$, but then injectivity of $\beta_i$ implies that $x=0$.


Q:

Filter non-digits from string

Using only swift code I cant figure out how to take "(555) 555-5555" and return only the numeric values and get "5555555555".  I need to remove all the parentheses, white spaces, and the dash.  The only examples I can find are in objective-C and they seem to all use the .trim() method.  It appears as though swift doesn't have this method but it does have the .stringByTrimmingCharacters method, but that only seems to trim the white spaces before and after the data.

A:

Swift 3 & 4:
extension String {
    var digits: String {
        return components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined()
    }
}

A:

Split the string by non-digit characters to an array of digits and the join them back to a string:
Swift 1:
let stringArray = origString.componentsSeparatedByCharactersInSet(
    NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = NSArray(array: stringArray).componentsJoinedByString("")

Swift 2:
let stringArray = origString.componentsSeparatedByCharactersInSet(
    NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = stringArray.joinWithSeparator("")

Swift 3 & 4:
let newString = origString
    .components(separatedBy:CharacterSet.decimalDigits.inverted)
    .joined()

A:

I like regular expressions:
var s = "(555) 555-5555"
s = s.stringByReplacingOccurrencesOfString(
    "\\D", withString: "", options: .RegularExpressionSearch,
    range: s.startIndex..<s.endIndex)


Q:

Save custom timestamp column to db after the row has been created

I have a table in my db that includes a nullable timestamp column.
$table->timestamp('custom_timestamp')->nullable();

When the row in the db is created this column will be null. Later when the user does this specific thing I want to update this column with the timestamp when the user did this.
My question: What is the syntax for adding the custom timestamp to this column?
Pseudo code explanation:
$myObject->custom_timestamp = *AD THE CURRENT TIME*;
$myObject->save();

EDIT:
If you downvote a seemingly legit question please explain your concerns in the comments

A:

You can generate the timestamp like so:
Carbon
use Carbon\Carbon;
$myObject->custom_timestamp = Carbon::now()->toDateTimeString();

Eloquent
$myObject->custom_timestamp = $myObject->freshTimestampString();


Q:

Dispose doesn't dispose completely

I noticed something strange, quite probably because maybe I don't understand the concept.
I am listening to cloud message from firebase. I have 2 dart files A and B.
A looks like:
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  FirebaseMessaging firebaseMessaging = new FirebaseMessaging();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  @override
  void initState() {

    super.initState();
    firebaseMessaging.configure(
      onLaunch: (Map<String, dynamic> msg) {
        print(" onLaunch called $msg");
      },
      onResume: (Map<String, dynamic> msg) {
        print(" onResume called ${(msg)}");
      },
      onMessage: (Map<String, dynamic> msg) {
        //showNotification(msg);
        print(" onMessage called in Activity A ${(msg)}");//--!!!!!-------!!!!->notice this
      },
    );
    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print('IOS Setting Registered');
    });
    firebaseMessaging.getToken().then((token) {
      print("token: "+token);
    });
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin.initialize(initSetttings);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: (){
              Navigator.push(context, MaterialPageRoute(builder: (context)=>Sample() ));// calling screen B from action of app bar
            },
          )
        ],
      ),
      body: new Container(),
    );
  }
}

Notice the line where I print in console if a new message is called in "Activity A"..
Now B looks like:
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class Sample extends StatefulWidget {

  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {

  @override
  void dispose(){
    super.dispose();
  }

  FirebaseMessaging firebaseMessaging1 = new FirebaseMessaging();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin1;
  @override
  void initState() {

    super.initState();
    firebaseMessaging1.configure(
      onLaunch: (Map<String, dynamic> msg) {
        print(" onLaunch called $msg");
      },
      onResume: (Map<String, dynamic> msg) {
        print(" onResume called ${(msg)}");
      },
      onMessage: (Map<String, dynamic> msg) {
        //showNotification(msg);
        print(" onMessage called in Activity B ${(msg)}");//----!!!---!!!!---Notice this
      },
    );
    firebaseMessaging1.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    firebaseMessaging1.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print('IOS Setting Registered');
    });
    firebaseMessaging1.getToken().then((token) {
      print("token: "+token);
    });
    flutterLocalNotificationsPlugin1 = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin1.initialize(initSetttings);
    print(firebaseMessaging1.toString());

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(),
    );
  }
}

So the aim is simple. When the notification arrives depending on the activity we are in, it should perform different actions.
If in A, print notification arrived in A
If in B, print notification arrived in B
But the problem is, when I switch back to A from B (B was called from A using Navigator push), it still prints Notification arrived in B
Either the dispose doesn't dispose completely or I am missing something

A:

dispose doesn't do anything fancy. It is your job to handle custom dispose behaviors.
More specifically, you have to explicitly clean all the mess you possibly made. In your situation, this translates into unsubscribing to firebase's stream.
This translates into the following:
StreamSubscription streamSubscription;
Stream myStream;

@override
void initState() {
  super.initState();
  streamSubscription = myStream.listen((foo) {
    print(foo);
  });
}

@override
void dispose() {
  super.dispose();
  streamSubscription.cancel();
}

You'll have to do the same thing for all listened streams and similar objects (such as Listenable)


Q:

Minkowski's complex Euclidean space vs. the real pseudo-Euclidean version

The SR invariance formula makes space-like intervals imaginary (e.g., the distance $x$ in a given frame has interval $ix$). Yet modern physicists consider it bad form to define the distance itself as $ix$, as Minkowski did. It seems to me that this distinction is trivial—what’s wrong with defining the distance as the value of its interval? An answer to a previous question of mine on this topic referred to a paper by Visser showing that there is a way to do this that can be generalized to GR.  So what’s the fuss about? Even if there weren’t such a way, I don’t see how that would invalidate Minkowski’s definition for SR. Since the interval measure is what’s important, what fundamental difference can it make whether one defines the distance as x or as the imaginary interval $ix$?
The whole idea of a LT being an imaginary rotation (important, because phi is additive) depends on the use of the invariant measure, which is the complex length between two points in C2, the space in which complex rotations exist, and so the space in which the x-t plane is being considered to be embedded when we talk of complex rotations. In C2 it can easily be shown that the angle between any two axes, real or imaginary, is a real right angle, and this explains the invariance formula—it is simply the Pythagorean theorem for that complex triangle. So all this ‘invariant interval geometry’ is an integral part of special relativity. If you insist that distances are real and use a Pseudo-Euclidean metric, which would imply entirely different values for these angles, you are throwing out an enormous portion of SR. It is hard to see how that can be billed as an advance in our understanding.

A:

Misner, Thorne, & Wheeler (MTW) offer arguments in"Farewell to ict" on Gravitation, p.51.
[updated with summary of their argument]
Reasons for using ict:

It makes spacetime geometry look like Euclidean geometry.
It make a Lorentz transformation look like a rotation.
It allows one to avoid distinguishing components of a vector from its metric-dual one-form.

Reasons NOT to use ict:

A vector is a very different geometric object from a one-form.
The Euclidean angle is periodic, whereas the Minkowski-angle, better known as the rapidity ("velocity parameter"), increases monotonically without bound.
Hiding the Lorentzian signature (- + + +) hides the light-cones that encode the causal structure.
No one has discovered a way to use this in general relativity for a general curved spacetime manifold.
and thus conclude:
"If '$x^4 = ict$' cannot be used there, it will not be used here" [in this book Gravitation].

[end of update]
See page 19 of this 20-page excerpt at http://laplace.physics.ubc.ca/000-People-matt/200/gravitation.pdf.


Q:

Confused in a very complex sentence

I am not sure whether the last part of this sentence is grammatically right:

My dream is to see an innovation of mine is one day being used inside automotive industry, such as General Motors or NASA, so that I would have [played an important role / made and important contribution] in the high-end technologies.

What I mean by the above sentence is that: "I want to invent something that will be used by those famous companies, and if that happens, then I have made an important contribution."

A:

My dream is to see one day, that an innovation of mine is being used inside automotive industry, such as General Motors or NASA, so that I would have played a made and important contribution in the high-end technologies.

That first comma doesn't need to be there.
I have a hard time thinking of NASA as automotive industry — they used to do space exploration and stuff. Have they diversified?
A “made and important” contribution makes little sense. Yes, you can use made as an adjective, but in this context the meaning is unclear.
You make a contribution or you play a role. Playing a contribution can maybe happen at a concert, but you do not seem to be talking about music.
“The high-end technologies” make me wonder how many there are. Simply using “high-end technology” is fine.

So, maybe something like this comes closer to what you mean:

My dream is to see one day that an innovation of mine is being used by a major company, such as General Motors or NASA, so that I would have made and important contribution to  high-end technology.


Q:

Does anybody know how to get Sun-Jupiter Lagrangian points L4 and L5 RA and Dec?

I wanted to point at the L4 and L5 of Sun-Jupiter to find Trojan asteroids but I don't know how to calculate the RA and Dec of these.
Do you know of any software that does it for you or how to calculate them?

A:

The L4 and L5 points are unstable orbits. The Trojans move in perturbed (ie slightly non-keplerian) orbits that move them around the L4 and L5 points. At any time you will find Trojans in a pair of lobes between about 30 and 90 degrees ahead of Jupiter.
You can find individual asteroids using NASA Horizons ephemeris
For example 624 Hektor, the largest Trojan (and placed in the Greek Camp around L4) will be found at RA 20 47 54.08, Dec -28 04 20.1 on Feb 10 2018. And 884 Piramus (in the Trojan Camp, L5) will be at RA 10 43 51.39 Dec +01 04 11.3.
(Jupiter is between them at RA 15 18 55.32 Dec -17 07 47.1)
Neither are easy to find, with a Magnitude of 15 or 16, due to their greater distance than main belt asteroids, and very dark colour. The image below shows the distribution of Trojans around Jupiter.


Q:

Keyboard interrupt tensorflow run and save at that point

Is there a way to break a tensorflow session by keyboard interrupt and have the option to save the model at that point? I currently leave the session running overnight but need to stop it so I can free memory for pc use during the day. As the training progresses each epoch gets slower so there are times when I may have to wait hours for the next scheduled save in the program. I'd like the functionality of being able to break into the run at any time and save from that point. I can't even find if that's possible. Would appreciate a pointer.

A:

One option is to subclass the tf.Session object and create an __exit__ function that saves out the current state as the keyboard interrupt passes through.  This would only work when the new object is called as part of a with block.
Here is the subclass:
import tensorflow as tf

class SessionWithExitSave(tf.Session):
    def __init__(self, *args, saver=None, exit_save_path=None, **kwargs):
        self.saver = saver
        self.exit_save_path = exit_save_path
        super().__init__(*args, **kwargs)

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is KeyboardInterrupt:
            if self.saver:
                self.saver.save(self, self.exit_save_path)
                print('Output saved to: "{}./*"'.format(self.exit_save_path))
        super().__exit__(exc_type, exc_value, exc_tb)

Example usage from the TensorFlow mnist walkthrough.
import tensorflow as tf
import datetime as dt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('U:/mnist/', one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)

saver = tf.train.Saver()

with SessionWithExitSave(
        saver=saver,
        exit_save_path='./tf-saves/_lastest.ckpt') as sess:
    sess.run(tf.global_variables_initializer())
    total_epochs = 50
    for epoch in range(1, total_epochs+1):
        for _ in range(1000):
            batch_xs, batch_ys = mnist.train.next_batch(100)
            sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        # Test trained model
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        print(f'Epoch {epoch} of {total_epochs} :: accuracy = ', end='')
        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
        save_time = dt.datetime.now().strftime('%Y%m%d-%H.%M.%S')
        saver.save(sess, f'./tf-saves/mnist-{save_time}.ckpt')

I let this run for 10 epochs before sending an interrupt signal from the keyboard.  Here is the output:
Epoch 1 of 50 :: accuracy = 0.9169
Epoch 2 of 50 :: accuracy = 0.919
Epoch 3 of 50 :: accuracy = 0.9205
Epoch 4 of 50 :: accuracy = 0.9221
Epoch 5 of 50 :: accuracy = 0.92
Epoch 6 of 50 :: accuracy = 0.9229
Epoch 7 of 50 :: accuracy = 0.9234
Epoch 8 of 50 :: accuracy = 0.9234
Epoch 9 of 50 :: accuracy = 0.9252
Epoch 10 of 50 :: accuracy = 0.9248
Output saved to: "./tf-saves/_lastest.ckpt./*"
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
...
--> 768   elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    769     return item[1]._is_present_in_parent
    770   else:
KeyboardInterrupt:

And indeed, I do have all of the saved files include the save from the keyboard interrupt that was sent to the system.
import os

os.listdir('./tf-saves/')
# returns:
['checkpoint',
 'mnist-20171207-23.05.18.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.18.ckpt.index',
 'mnist-20171207-23.05.18.ckpt.meta',
 'mnist-20171207-23.05.22.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.22.ckpt.index',
 'mnist-20171207-23.05.22.ckpt.meta',
 'mnist-20171207-23.05.26.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.26.ckpt.index',
 'mnist-20171207-23.05.26.ckpt.meta',
 'mnist-20171207-23.05.31.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.31.ckpt.index',
 '_lastest.ckpt.data-00000-of-00001',
 '_lastest.ckpt.index',
 '_lastest.ckpt.meta']


Q:

SQL job result in c#

I have this small code using SQL Server Agent to Run a Remote Package Programmatically on the Server. But the problem with the code is that even if the job out come is failure, but job was executed successfully. so this program always works fine.
I want to know if I can actually capture the job result in C#.. Any thoughts?
namespace LaunchSSISPackageAgent_CS
{
  class Program
  {
static void Main(string[] args)
{
  SqlConnection jobConnection;
  SqlCommand jobCommand;
  SqlParameter jobReturnValue;
  SqlParameter jobParameter;
  int jobResult;

  jobConnection = new SqlConnection("Data Source=(local);Initial Catalog=msdb;Integrated Security=SSPI");
  jobCommand = new SqlCommand("sp_start_job", jobConnection);
  jobCommand.CommandType = CommandType.StoredProcedure;

  jobReturnValue = new SqlParameter("@RETURN_VALUE", SqlDbType.Int);
  jobReturnValue.Direction = ParameterDirection.ReturnValue;
  jobCommand.Parameters.Add(jobReturnValue);

  jobParameter = new SqlParameter("@job_name", SqlDbType.VarChar);
  jobParameter.Direction = ParameterDirection.Input;
  jobCommand.Parameters.Add(jobParameter);
  jobParameter.Value = "RunSSISPackage";

  jobConnection.Open();
  jobCommand.ExecuteNonQuery();
  jobResult = (Int32)jobCommand.Parameters["@RETURN_VALUE"].Value;
  jobConnection.Close();

  switch (jobResult)
  {
    case 0:
      Console.WriteLine("SQL Server Agent job, RunSISSPackage, started successfully.");
      break;
    default:
      Console.WriteLine("SQL Server Agent job, RunSISSPackage, failed to start.");
      break;
  }
  Console.Read();
}

}

A:

You could try running sp_help_job afterwards
http://technet.microsoft.com/en-us/library/ms186722(SQL.90).aspx


Q:

Are there any orchestral pieces that render Ainulindalë?

Although I knew vaguely about the Ainur and the time before Earth, I only just recently read Ainulindalë in The Silmarillion. While reading I couldn't escape the thought of a piece of music that symbolizes or portrays the Great Song.

A:

No official version, and as far as I know Tolkien never felt compelled to attempt one. In honesty it doesn't make a lot of sense to take the Ainulindalë literally as a text; considering we're talking about the actions of non-embodied spirits palling around in the Netherspace, mentions of things like "voice" and "song" are more than likely just metaphors to describe events beyond our incarnate understanding.
Having said that, there are legion fan efforts on YouTube and elsewhere, including:

A museScore user by the name of Jodie Foster scored a version for strings and woodwinds; while it's not as impressive to listen to, it's one of the more book-accurate versions I've seen

Fan Stephan Krosecz made an audio-visual interpretation of the story

One I'm personally fond of, though it's not remotely close to what's in my head when I read the story, is another audio-visual interpretation by composer Diego Mitre:

There are many others, and they're all quite interesting and very non-canon.


Q:

Why do Kylo and Snoke follow the Rule of Two?

In The Last Jedi, Snoke says “Finish your training... and fulfil your destiny.”

 After this, Kylo kills his master and becomes a master himself.

If they are not Sith, why do they obey the Rule of Two?

A:

As the old Soviet joke goes, "Officer, I didn't steal those jeans. And they were dirty and all full of holes anyway!".
As such:

We don't know that they follow Rule of Two in the first place, in word or even deed:

Supplementary fact books show that Snoke had at least another apprentice besides Emo Ren.
We are given strong (but not yet canon confrimed) hints that Knights of Ren are Luke's former students that left with Ben Solo. If so, clearly Snoke was teaching them too
Finally, it can be argued that Kylo has no apprentices after killing Snoke.

Having said that, the rule of Two is not 1 to 1 associated with the Sith:

First, even the Sith didn't exactly obey it. For one thing, Sith before Darth Bane didn't. For another, we have tons of examples of Sidious/Vader violating it.
Second, Rule of Two isn't a "Sith only" thing. It's just a tactical/philosophical concept. As such, any Force user may act in the ways that follow such a rule, not because "they are following Sith ways" but because the rule makes a lot of sense (it did work out well for the Sith, after all).


Q:

Why is position broken after applying js

why does other images "jump" down after clicking on some image(applying js)?
http://almaweby.cz/reference.html
Try to click on first image.. text about it will slide down,that´s correct and then other images jump down..How can I rewrite the code to move down only next row and not the first?
And a bit offtopic. Why is second row moved differently than the first one?
Here is a sample of my problem
https://jsfiddle.net/ytLqgk0v

$('.hook').on('click', function( evt ) {
 $(evt.currentTarget).find('.popis').slideToggle();
});
.hook{
width: 30%;
margin-right: 10px;
display: inline-block;
}
.nahledy{
  width: 150px;
  height: 50px;
  background: yellow;
}

LOrem ipsum

Lorem ipsum again

Lorem ipsum for third time

`

A:

Try using flexbox for alignment instead of just having things float. To start, add display: flex; flex-wrap: wrap; to the parent container and then clean up the position from there.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/


Q:

Getting data from API service angular

I'm learning to create an API with nodejs (express) and angular for the front part.
What should i think and what should i want:
When a user is on www.url.com/ID display the data by him ID.
But actually i got problem..
Service file gonna get my data.
ServiceFile.ts
getAllPosts(): Observable<Project[]> {
        return this.http
            .get(this._postsURL)
            .map((response: Response) => {
                return <Project[]>response.json();
            })
            .catch(this.handleError);
    }
getPost(id: string): Observable<Project> {
        return this.getAllPosts()
            .map(projects => projects.find(project => project._id === id));
    }

My component file for get my data throught the ID url example "www.url.com/ID" call my service and send to my html file the data
my component.ts
_postssArray: any;

ngOnInit(): void {
        this.route.paramMap.subscribe(params => {
            const id = params.get('id');
            this._projectService.getPost(id)
                .subscribe(
                    data => {
                        this._postssArray = data;
                        console.log(this._postssArray);
                    }
            );
        });
    }

iterate to my data variable send by my component
View.html file

{{post.title}}

{{post.text_preview}}

console.log
Object

{   _id: "xxxxxxxxxxx",    title: "data",   text_preview: "data data
  data",   text: "data data" }

Error

ERROR Error: Cannot find a differ supporting object '[object Object]'
  of type 'object'. NgFor only supports binding to Iterables such as
  Arrays.

A:

You don't need an ngFor here as there is not array. The find function in getPost will always return one post

{{post.title}}

{{post.text_preview}}

_post: any;

ngOnInit(): void {
        this.route.paramMap.subscribe(params => {
            const id = params.get('id');
            this._projectService.getPost(id)
                .subscribe(
                    data => {
                        this._post = data;
                        console.log(this._post);
                    }
            );
        });
    }


Q:

repeating values in PHP drilldown

I am relatively new to PHP. I have drilled down a couple of levels through a DB, and i have hit a snag. i cant work out why i am only retrieving one repeated record when there should just be 5 different ones. my code is below...
<?php

    $sections = $_GET['rid'];
 // Connects to Database
 mysql_connect("localhost", "root") or die(mysql_error());
 mysql_select_db("test") or die(mysql_error());
 $data = mysql_query("SELECT question_keywords.rfp_id, question_keywords.section_id, section_name FROM rfp, question_keywords, section WHERE question_keywords.rfp_id = rfp.rfp_id AND section.section_id = question_keywords.section_id AND section.section_id = '$sections'")
 or die(mysql_error());
  echo "
";
echo "

Section ID	Section Name	" ;
 while($row = mysql_fetch_array($data)){
      $sid = $row['section_id'];  //if you have the column names, replace 0 with 'column_name'
      $sname = $row['section_name'];
     # $status = $row['status'];

# inserts value into table as a hyperlink

echo "
$sid	$sname	";
}

# displays table

print '
';

 ?>

Any help would be appreciated
Thanks

A:

I guess you simply forgot adding two
 s
If you have a look into the HTML-Output it should be there. Try :
echo "

Section ID	Section Name
" ;

and:
echo '

';

and as a comment already stated, try querying your command against the database in a sql command (or phpmyadmin).