text:
Q: Is there any good reason to catch exceptions in unittest transactions? The unittest module is extremely good to detect problems in code.
I understand the idea of isolating and testing parts of code with assertions:
self.assertEqual(web_page_view.func, web_page_url)
But besides these assertions you also might have some logic before it, in the same test method, that could have problems.
I am wondering if manual exception handling is something to take in account ever inside methods of a TestCase subclass.
Because if I wrap a block in a try-catch, if something fails, the test returns OK and does not fail:
    def test_simulate_requests(self):
        """
        Simulate requests to a url
        """
        try:
           response = self.client.get('/adress/of/page/')
           self.assertEqual(response.status_code, 200)
        except Exception as e:
            print("error: ", e)

Should exception handling be always avoided in such tests?

A: There are two "bad" states of a test: Failure (when one of the assertions fails) and Error (when the test itself fails - your case).
First of all, it goes without saying that it's better to build your test in such a way that it reaches its assertions.
If you need to assert some tested code raises an exception, you should use with self.assertRaises(ExpectedError)
If some code inside the test raises an exception - it's better to know it from 'Error' result than seeing 'OK all tests have passed'
If your test logic really assumes that something can fail in the test itself and it is normal behaviour - probably the test is wrong. May be you should use mocks (https://docs.python.org/3/library/unittest.mock.html) to imitate an api call or something else.
In your case, even if the test fails, you catch it with bare except and say "Ok, continue". Anyway the implementation is wrong.
Finally: no, there shouldn't be except in your test cases
P.S. it's better to call your test functions with test_what_you_want_to_test_name, in this case probably test_successful_request would be ok.

A: First part of answer:
As you correctly say, there needs to be some logic before the actual test.  The code belonging to a unit-test can be clustered into four parts (I use Meszaros' terminology in the following): setup, exercise, verify, teardown.  Often the code of a test case is structured such that the code for the four parts are cleanly separated and come in that precise order - this is called the four phase test pattern.
The exercise phase is the heart of the test, where the functionality is executed that shall be checked in the test.  The setup ensures that this happens in a well defined context.  So, what you have described is in this terminology the situation that during setup something fails.  Which means, that the preconditions are not met which are required for a meaningful execution of the functionality that is to be tested.
This is a common situation and it means that you in fact need to be able to distinguish three outcomes of a test: A test can pass successfully, it can fail, or it can just be meaningless.
Fortunately, there is an answer for this in python: You can skip tests, and if a test is skipped this is recorded, but neither as a failure nor as a success.  Skipping of tests would probably a better way to handle the situation that you have shown in your example.  Here is a small code piece that demonstrates one way of skipping tests:
import unittest
class TestException(unittest.TestCase):
   def test_skipTest_shallSkip(self):
      self.skipTest("Skipped because skipping shall be demonstrated.")

Second part of answer:
Your test seems to have some non-deterministic elements.  The self.client.get can throw exceptions (but only sometimes - sometimes it doesn't).  This means you do not have the context during the test execution under control.  In unit-testing this is a situation you should try to avoid.  Your tests should have a deterministic behavior.
One typical way to achieve this is to isolate your code from the components that are responsible for the nondeterminism and during testing replace these components by mocks.  The behaviour of the mocks is under full control of the test code.  Thus, if your code uses some component for network accesses, you would mock that component.  Then, in some test cases you can instruct the mock to simulate a successful network communication to see how your component handles this, and in other tests you instruct the mock to simulate a network failure to see how your component copes with this situation.


text:
Q: Make one http call based on previous' result I need to make two HTTP calls (first GET and second POST), the second based on result of the first.
Here's the response from the GET:
{
    "weekNbr": "34-2017",
    "startDate": "2017-09-16",
    "endDate": "2017-09-22"
}

This response will then be manipulated and sent as a POST request with the following JSON:
{
    "weekNbr": 34, (as received above)
    "year": 2017 (as received above)
}

One Solution:
http.get(url1).pipe(
    map(do your maipulation)
).subscribe(
    (newlyCreatedObject) => {
        return http.post(url2,newlyCreatedObject);
    }
);

But I don't think it's the correct way.
NOTE:
These calls are supposed to be made in a single service. If there are any rxjs operators to do the same, it'd be highly appreciated.

A: You can use the flatMap/mergeMap operator to make two HTTP requests, one depending on the other.
Like:
http.get(data).flatMap(res => {
    // res is response of Get
    // manipulate the data and passed in post call
    return http.post(data);
})
.map(res => {})
.catch(e => {});

A: i have prepare this dummy service :
import {of, Observable} from 'rxjs';
import {flatMap} from 'rxjs/operators';
/**
 * Dummy get observable.
 */
export class MyService {

  getInformation$(): Observable<{foo:string}> {
    return of({foo:'bar'});
  }

  postInformation$(params:{foo:string}): Observable<any> {
    return of({
      fooUpperCase: params.foo.toUpperCase() // Stupid transformation for demonstration only
    });
  }

  main() {
    this.getInformation$().pipe(
      flatMap(data => this.postInformation$(data)) // receive each next and return new observable.
    ).subscribe(console.log);
  }
}

new MyService().main();

For demonstration only, i have switch http observable to dummy of observable.
live sample

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set environment variables in Python and use them in a C extension I have created a Python wrapper for a C library. The library requires an environment variable (MY_DATA_FOLDER) to point to a folder with some data files. The data files are (in the current implementation of my wrapper) installed together with the Python wrapper when running setup.py, and are placed in a folder called coefficients together with the package installation. I set the environment variables in the package's __init__.py, which is excecuted whenever the package is imported:
# set environment variable
import os
from os.path import join, realpath, dirname
MY_DATA_FOLDER = join(realpath(dirname(__file__)), 'coefficients')
os.environ['MY_DATA_FOLDER'] = MY_DATA_FOLDER

# import the C extension (mymodule._mymodule) after setting the variable above
from mymodule import _mymodule

The wrapper functions are now available as mymodule._mymodule.myfunction(). I am testing the package with tox, and everything works well. In case it's useful, my testenv has the following commands:
commands =
    python setup.py clean --all build_ext --force --inplace
    {posargs:py.test -vv --ignore=src}

However, when I install the package using python setup.py install (or develop or pip install . with or without -e) and open a Python shell to run the wrapper, the C library gives an error indicating that the environment variable is not set. This happens whether I run some custom code or run py.test -vv --ignore=src just like tox does. Everything is importable, and the C extension does run (i.e. it's compiled correctly), but the environment variable is not passed along, hence the error.
I have banged my head against the wall for some time now and I have no idea what could be wrong, and apparently neither does Google. Why is the environment variable available to the C extension when running tox but not when installing normally?
I'm happy to provide more information if it's required. The entire source is here.

UPDATE
It works now. It seems to have been a classical case of "struggle for a few hours, give up and leave work, come back the next day, everything works." I have no idea why, but I must have done something wrong. Perhaps my environment wasn't as clean as I thought, or I forgot to activate it.


text:
Q: Why is $E(X_1^2)=1$? I need to show that $E(\chi_n^2)=n$. Since $E[\chi_n^2]=\sum_{i=1}^{n} E\left[X_{i}^{2}\right]=nE\left[X_{i}^{2}\right]$ where $X_i \sim \mathcal{N}(0,1)$ and thus all I need to know is $E\left[X_{i}^{2}\right]$. In the solution they casually plug in $E\left[X_{i}^{2}\right]=1$, how do we know that?

A: An alternative way to proceed is to realize that
$$X\sim\chi_{(n)}^2=\text{Gamma}\left(\frac{n}{2};\frac{1}{2}\right)$$
where $\frac{1}{2}$ is the rate parameter; thus using the known result of the Gamma distribution you have
$$\mathbb{E}[X]=\frac{\frac{n}{2}}{\frac{1}{2}}=n$$
...and similarly for the variance you have that
$$\mathbb{V}[X]=\frac{\frac{n}{2}}{\left(\frac{1}{2}\right)^2}=2n$$


text:
Q: Fast floating point model broken on next-generation intel compiler Description
I'm trying to switch over from using the classic intel compiler from the Intel OneAPI toolkit to the next-generation DPC/C++ compiler, but the default behaviour for handling floating point operations appears broken or different, in that comparison with infinity always evaluates to false in fast floating point modes. The above is both a compiler warning and the behaviour I now experience with ICX, but not a behaviour experienced with the classic compiler (for the same minimal set of compiler flags used).
Minimally reproducible example
#include <iostream>
#include <cmath>

int main()
{
    double a = 1.0/0.0;
    if (std::isinf(a))
        std::cout << "is infinite";
    else
        std::cout << "is not infinite;";
}

Compiler Flags:
-O3 -Wall -fp-model=fast
ICC 2021.5.0 Output:
is infinite
(also tested on several older versions)
ICX 2022.0.0 Output:
is not infinite
(also tested on 2022.0.1)
Live demo on compiler-explorer:
https://godbolt.org/z/vzeYj1Wa3
By default -fp-model=fast is enabled on both compilers. If I manually specify -fp-model=precise I can recover the behaviour but not the performance.
Does anyone know of a potential solution to both maintain the previous behaviour & performance of the fast floating point model using the next-gen compiler?

A: If you add -fp-speculation=safe to -fp-model=fast, you will still get the warning that you shouldn't use -fp-model=fast if you want to check for infinity, but the condition will evaluate correctly: godbolt.
In the Intel Porting Guide for ICC Users to DPCPP or ICX it is stated that:

FP Strictness: Nothing stricter than the default is supported.  There is no support for -fp-model strict, -fp-speculation=safe, #pragma fenv_access, etc. Implementing support for these is a work-in-progress in the open source community.

Even though it works for the current version of the tested compiler (icx 2022.0.0), there is a discrepancy: either the documentation is outdated (more probable), or this feature is working by accident (less probable).


text:
Q: Best practices for setting up Azure for a client and allow other devs access? Do I have the client setup an account using their payment, contact info etc? or do I use my own account then somehow transfer everything to the client? Also, How do I give access to devs?
Thanks.

A: There are different strategies you can employ to decide how you want to design and organize your Subscriptions. The Subscription decision guide within the Microsoft Cloud Adoption Framework for Azure can help you establish that structure.
As for granting access to others, Azure role-based access control (Azure RBAC) is a system that provides fine-grained access management of Azure resources. Using Azure RBAC, you can segregate duties within your team and grant only the amount of access to users that they need to perform their jobs. Instead of giving everybody unrestricted permissions in your Azure subscription or resources, you can allow only certain actions at a particular scope. You can further refer to the best practices for Azure RBAC doc to know more.


text:
Q: Elasticsearch Highlight the result of script fields In the last question that I asked I want to remove the HTML tags in my search results, After that I thought I could highlite the results with a common query, But in the highlighting field I got other html contents that you removed with script. Would you please help me to highlight the results without html tags that I saved in my db?
My mapping and settings:
{
  "settings": {
    "analysis": {
      "filter": {
        "my_pattern_replace_filter": {
          "type": "pattern_replace",
          "pattern": "\n",
          "replacement": ""
        }
      },
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "standard",
          "filter": [
            "lowercase"
          ],
          "char_filter": [
            "html_strip"
          ]
        },
        "parsed_analyzer": {
          "type": "custom",
          "tokenizer": "keyword",
          "char_filter": [
            "html_strip"
          ],
          "filter": [
            "my_pattern_replace_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "html": {
        "type": "text",
        "analyzer": "my_analyzer",
        "fields": {
          "raw": {
            "type": "text",
            "fielddata": true,
            "analyzer": "parsed_analyzer"
          }
        }
      }
    }
  }
}

Search Query:
POST idx_test/_search

{
  "script_fields": {
    "raw": {
      "script": "doc['html.raw']"
    }
  },
  "query": {
    "match": {
      "html": "more"
    }
  },"highlight": {
    "fields": {
      "*":{ "pre_tags" : [""], "post_tags" : [""] }
    }
  }
}

Result:
"hits": [
    {
        "_index": "idx_test2",
        "_type": "_doc",
        "_id": "GijDsYMBjgX3UBaguGxc",
        "_score": 0.2876821,
        "fields": {
            "raw": [
                "Test More test"
            ]
        },
        "highlight": {
            "html": [
                "
Test
 More test"
            ]
        }
    }
]

Result that I want to get:
"hits": [
    {
        "_index": "idx_test2",
        "_type": "_doc",
        "_id": "GijDsYMBjgX3UBaguGxc",
        "_score": 0.2876821,
        "fields": {
            "raw": [
                "Test More test"
            ]
        }
]

A: I thought of another solution. You could index two fields, the original html and the html_extract which has only the text.
You would have to use a processor to just index the text coming from the message and highligths would work.
Mapping
PUT idx_html_strip
{
  "mappings": {
    "properties": {
      "html": {
        "type": "text"
      },
      "html_extract": {
        "type": "text"
      }
    }
  }
}

Processor Pipeline
PUT /_ingest/pipeline/pipe_html_strip
{
  "description": "_description",
  "processors": [
    {
      "html_strip": {
        "field": "html",
        "target_field": "html_extract"
      }
    },
    {
      "script": {
        "lang": "painless",
        "source": "ctx['html_raw'] = ctx['html_raw'].replace('\n',' ').trim()"
      }
    }
  ]
}

Index Data
Note the use ?pipeline=pipe_html_strip
POST idx_html_strip/_doc?pipeline=pipe_html_strip
{
  "html": """
Test
 More test"""
}

Query
GET idx_html_strip/_search?filter_path=hits.hits._source,hits.hits.highlight
{
  "query": {
    "multi_match": {
      "query": "More",
      "fields": ["html", "html_extract"]
    }
  },"highlight": {
    "fields": {
      "*":{ "pre_tags" : [""], "post_tags" : [""] }
    }
  }
}

Results
{
  "hits": {
    "hits": [
      {
        "_source": {
          "html": """
Test
 More test""",
          "html_extract": "Test More test"
        },
        "highlight": {
          "html": [
            """
Test
 More test"""
          ],
          "html_extract": [
            "Test More test"
          ]
        }
      }
    ]
  }
}


text:
Q: How do I allow only internal network to access a particular UDP Port using iptables I want to allow Asterisk access (UDP Port 5060) to internal network only (192.168.3.0/24 and 192.168.4.0/24) and not allow external access.
Relevant part of my iptables was:
 iptables -F
 iptables -t nat -F
 iptables -A INPUT -p udp -j ACCEPT
 iptables -P INPUT DROP

 iptables -I INPUT -p udp ! -s 192.168.3.0/24 --dport 5060 -j REJECT
 iptables -I INPUT -p udp ! -s 192.168.4.0/24 --dport 5060 -j REJECT
 iptables -I INPUT -p udp  -s 192.168.3.0/24 --dport 5060 -j ACCEPT
 iptables -I INPUT -p udp  -s 192.168.4.0/24 --dport 5060 -j ACCEPT

This does not work.
I use NAT for a different purpose.

A: You're showing a sequence of inserts into iptables:
iptables -I INPUT -p udp ! -s 192.168.3.0/24 --dport 5060 -j REJECT
iptables -I INPUT -p udp ! -s 192.168.4.0/24 --dport 5060 -j REJECT
iptables -I INPUT -p udp  -s 192.168.5.0/24 --dport 5060 -j ACCEPT
iptables -I INPUT -p udp  -s 192.168.1.0/24 --dport 5060 -j ACCEPT

As these are each inserted as the first rule, the order is effectively reversed:
-A INPUT -p udp  -s 192.168.1.0/24 --dport 5060 -j ACCEPT
-A INPUT -p udp  -s 192.168.5.0/24 --dport 5060 -j ACCEPT
-A INPUT -p udp ! -s 192.168.4.0/24 --dport 5060 -j REJECT
-A INPUT -p udp ! -s 192.168.3.0/24 --dport 5060 -j REJECT

This means traffic from 192.168.3.0 will be rejected by the third rule and not reach the fourth rule.
Your question says internal networks are 192.168.3.0/24 and 192.168.4.0/24 so it is not clear why you are accepting 192.168.1.0/24 and 192.168.5.0/24.  Nonetheless, you should write the rule to accept the local subnets and reject everything else, e.g.
-A INPUT -p udp -s 192.168.3.0/24 --dport 5060 -j ACCEPT
-A INPUT -p udp -s 192.168.4.0/24 --dport 5060 -j ACCEPT
-A INPUT -p udp --dport 5060 -j DROP


text:
Q: Duplicate Filemaker Record and related Portal Records I'm a Filemaker noob, so I need to put that right out there.
I have a table (Gigs) and related portal table (Gigs_Join) where a list of songs is shown in the portal. These are connected via GigID in the main and portal tables.
I want to duplicate a Gig record and all related portal records. I know this has to be scripted, but for my life, I can't make it work.
Any suggestion is appreciated!

A: Try these steps,
1. Create two Table Occurrences GigsJoin1, GigsJoin2 based on Gigs_Join
2. Create two layouts (GigsJoin1, GigsJoin2) based on above TOs.

3. Write a script with following Steps.
    a. Go to Gigs layout.
    b. Save the Gig ID in a variable (OrigGigID).
    c. Duplicate the Gig record.
    d. Save the new Gig ID in a variable (NewGigID).
    e. Go to the layout GigsJoin1.
    f. Find the records using OrigGigID.
    g. Start Loop
        i. Go to first record
        ii. Copy all the field values in variables.
        iii. Go to layout GigsJoin2.
        iv. Create new record
        v. Set the values from variables.
        vi. Set the GigsID from variable NewGigID
        vii. Go to Layout GigsJoin1
        viii. Go to next record
    e. End Loop


text:
Q: Managing clicked item's props in a new route - React router v6 I have a map of an objects. Each object is an item in a list. When I click on a concrete item it moves me to a specific route with that item's id. How to properly manage that concrete item's props inside new route?
Is this the way to go or there is better way?
export const Router = (): ReactElement => {
  const [itemDetails, setItemDetails] = useState<Item>();
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Root />}>
          <Route
            index
            element={<ItemList setItemDetails={setItemDetails} />}
          />
          <Route
            path="/item/:itemId"
            element={<ItemDetails itemDetails={itemDetails} />}
          />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

So basically what I'm doing here is I'm passing state setter function to a list where my mapped items are stored so when I click on a concrete one I save its props to that function.
Then I just pass updated state to a new route where details of a concrete item should be displayed.

A: If you are asking if there's a better way than pushing some value from ItemList up to the parent state to be passed down to ItemDetails, then sure, a more React/react-router-dom way would be to hoist the items array from the ItemList component up to this parent component and pass the data down to children routes as props or via a context.
Example using props
export const Router = (): ReactElement => {
  const [items, setItems] = useState<Array<Item>>([]);

  ... logic to populate items state ...

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Root />}>
          <Route index element={<ItemList items={items} />} />
          <Route path="/item/:itemId" element={<ItemDetails items={items} />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

ItemDetails
const ItemDetails = ({ items }) => {
  const { itemId } = useParams();
  const item = items.find(item => String(item.id) === itemId);

  if (!item) {
    return
No matching item found.
;
  }
  return (
    ... render item out to JSX
  );
};

Example using Outlet context
export const Router = (): ReactElement => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Root />}>
          <Route index element={<ItemList />} />
          <Route path="/item/:itemId" element={<ItemDetails />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

Root
const Root = () => {
  const [items, setItems] = useState<Array<Item>>([]);

  ... logic to populate items state ...

  return (
    ...
    <Outlet context={{ items }} />
    ...
  );
};

ItemList
const ItemList = () => {
  const { items } = useOutletContext();

  return (
    ... map items to JSX
  );
};

ItemDetails
const ItemDetails = () => {
  const { items } = useOutletContext();
  const { itemId } = useParams();
  const item = items.find(item => String(item.id) === itemId);

  if (!item) {
    return
No matching item found.
;
  }
  return (
    ... render item out to JSX
  );
};


text:
Q: Directly call ASP.NET controller action from a different controller I have a situation where I need to redirect to an ASP.NET MVC action in a different controller.  I can't use RedirectToAction because I must POST the action's parameters to keep them out of the URL.
I attempted to instantiate and call the other controller's action directly like this:
OtherController myOtherController = new OtherController();
myOtherController.ControllerContext = new ControllerContext(this.ControllerContext.RequestContext, myOtherController);
return await myOtherController.Edit(myGuid);

When I do this, the other controller's code executes, but I end up with this error:

The model item passed into the dictionary is of type
  'System.Data.Entity.DynamicProxies.OtherModel_BBCEF7C9378F4C4F097CC08FA2E508B8BD8D865E33093E31959919087A31348E',
  but this dictionary requires a model item of type 'ThisModel'.

Does anyone know if I can get this working using the current approach?  Assuming I must use an HTTP POST action and cannot have parameters in the URL, is there a different approach that you would recommend to achieve this result (other than combining the controllers)?
Edit:
Note that I don't think I can post directly from the client because I would need to nest Html.BeginForm.

A: You should really just be using RedirectToAction to push the browser to the action you want instead of trying to do it like this. As you can see from @Andrei Olariu code a lot of things happen under the hood during the construction of your controller (DI then context and parameter mappings) that really shouldn't be done manually and can easily be screwed up leading to hours wasted wondering why certain things are not behaving as expected.

A: I hope I understood what you're trying to do. This is what I'm successfully using to execute an action on a different controller.
private void ExecuteErrorAction(string action, HttpContextWrapper httpContext, Exception exception)
{
    var routeData = new RouteData();
    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = action;
    routeData.Values["exception"] = exception;

    IController errorController = DependencyResolver.Current.GetService<ErrorController>();
    var context = new RequestContext(httpContext, routeData);
    errorController.Execute(context);
}

I think that in your case this could look like:
private void ExecuteOtherAction(string myGuid, HttpContextWrapper httpContext)
{
    var routeData = new RouteData();
    routeData.Values["controller"] = "OtherController";
    routeData.Values["action"] = "Edit";
    routeData.Values["myGuid"] = myGuid;

    IController otherCntroller = DependencyResolver.Current.GetService<OtherController>();
    var context = new RequestContext(httpContext, routeData);
    otherCntroller.Execute(context);
}

This is assuming that your Edit action on the OtherController takes a string called myGuid as a parameter.
Let me know if this helps.


text:
Q: Change position of legend in plot of pec object I am trying to plot the prediction error curve from pec package but I can't change the legend position and size. There's an example from pec package:
library(rms)
library(pec)
data(pbc)
pbc <- pbc[sample(1:NROW(pbc),size=100),]
f1 <- psm(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc)
f2 <- coxph(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc,x=TRUE,y=TRUE)
f3 <- cph(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc,surv=TRUE)
brier <- pec(list("Weibull"=f1,"CoxPH"=f2,"CPH"=f3),data=pbc,formula=Surv(time,status!=0)~1)
print(brier)
plot(brier)

But shows a big the legend in the middle of plot.

I also tried:
plot(brier, legend = "topright")
class(brier)

But don't show legend.

How can I change the position of legend? And also ¿is it posible to plot this graph using ggplot?

A: I think I got what you want using ggplot2. The idea is to pick elements from your brier object that contains data for the plot, make a dataframe with it and plot it.
library(ggplot2)
# packages for the pipe and pivot_wider, you can do it with base functions, I just prefer these
library(tidyr)
library(dplyr)

df <- do.call(cbind, brier[["AppErr"]]) # contains y values for each model
df <- cbind(brier[["time"]], df) # values of the x axis
colnames(df)[1] <- "time"
df <- as.data.frame(df) %>% pivot_longer(cols = 2:last_col(), names_to = "models", values_to = "values") # pivot table to long format makes it easier to use ggplot

ggplot(data = df, aes(x = time, y = values, color = models)) +
  geom_line() # I suppose you know how to custom axis names etc.

Output:


text:
Q: how to dismiss an alert in React Native? I am using an Alert , and  when i am navigating to previous screen on clicking of ok button this alert is not dismissing.
  its showing up again in that back screen.
How i can stop this alert showing up again.
I am trying this code.
  showErrorAlert = () => {
   Alert.alert(
      CONSTANTS.SOME_ERROR_OCCURED,
      '',
      [{ text: 'OK', onPress: () => this.loggingOut() },],)
   };

 loggingOut = () => {
  console.log("coming here");
 };

A: Can you please try the following code, you can try adding { cancelable: false }.
For more information go here
showErrorAlert = () => {
   Alert.alert(
      CONSTANTS.SOME_ERROR_OCCURED,
      '',
      [{ text: 'OK', onPress: () => this.loggingOut() },],
       { cancelable: false })
   };

 loggingOut = () => {
  console.log("coming here");
  };


text:
Q: xml indent and newline for new child I have a xml file that looks like a following.
<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
    </children>
</root>

I wish to add a new child with name foo to the  node using the functions xmlNewChild() followed by xmlNewProp(). I would like to generate something like the following.
<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
        <foo3 val="5"/>
    </children>
</root>

However, I always end up with the following.
<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
    <foo3 val="5"/></children>
</root>

I do understand that libxml2 does not favor white spaces by default. However, is there a way to achieve the result I want? I need to get those tabs in front and newlines in the end for the newly added child.
Any help would be appreciated. Thanks!

A: The issue is that the XML structure actually looks like this:
<root>
    [TEXT:"\n    "]
    <children>
        [TEXT:"\n        "]
        <foo1 val="23"/>
        [TEXT:"\n        "]
        <foo2 val="14"/>
        [TEXT:"\n    "]
    </children>
    [TEXT:"\n"]
</root>

If you just add an extra element node at the end of children, you can see that what you get is inevitable (as there is no text node to carry a newline and the desired indentation between foo3 and children).
You need to edit the final text node inside children (the one immediately after foo2) to give it an extra indent, then append your new node, then append a new text node to indent </children>. Alternately, you can insert a text node identical to previous text nodes inside children and then your new element node just before the final text node in children. Both should give you the same result, the one you need:
<root>
    [TEXT:"\n    "]
    <children>
        [TEXT:"\n        "]
        <foo1 val="23"/>
        [TEXT:"\n        "]
        <foo2 val="14"/>
        [TEXT:"\n        "]
        <foo3 val="5"/>
        [TEXT:"\n    "]
    </children>
    [TEXT:"\n"]
</root>

Another approach is to have libxml2 autoindent the output for you. This will destroy existing indentation and redo it from scratch. Here is a relevant answer.

A: Use xmlTextWriterSetIndent
Ref : http://xmlsoft.org/html/libxml-xmlwriter.html#xmlTextWriterSetIndent


text:
Q: How To create a shortcut for a command in python 3.3 I just started learning python and was wondering if their was a way to shortcut a line of code.
For example could I use something along the lines of.
command = input()
if command = "create turtle"
    t =turtle.Pen()

or
turtleCommand = input()
if turtleCommand = "circle"
    t.forward(100)
    t.left(91)

The turtle thing is just hypothetical maybe if a string "inputted" (if thats a word) activated a defineFunction

A: You can write a function:
def draw_circle(t):
    t.forward(100)
    t.left(91)

And then call it:
t = turtle.Pen()
command = input()

if command == "circle":
    draw_circle(t)
elif command = "stuff":
    ...

A more robust solution would be to use a dictionary that maps commands to functions:
commands = {
    "circle": draw_circle,
    "square": draw_square
}

And then get a function by name:
t = turtle.Pen()
turtle_command = input()
command = commands[turtle_command]

command(t)

A: def docircle(pen):
  pen.forward(100)
  pen.left(91)

commands = {
  'circle': docircle,
   ...
}

...

commands[turtleCommand](t)

A: You can set up a dictionary mapping a word to the function you want the word to activate:
commands = {'create turtle': create_turtle,
            'circle': circle, }

def create_turtle():
    t = turtle.Pen()

def draw_circle():
    ...

And then:
command = input()
commands[command]()


text:
Q: How to check if payment completed in MPL? Using PayPal MPL, how could the back-end server check whether the payment completed?
As I understand the MPL controls the entire flow, no need for back-end server calls - but what if the server needs to validate and register the purchase completion.
UPDATE First of all, thank you for the answers so far.
We have two requirements/preferences that can guide us to refine our process:

*

*The payment should be validated as soon as possible. Customer should access the paid services right after the purchase.

*For the validation process we should use minimum proof data from the app. Consider the following scenario: purchase completed, but the back-end server went offline - so the client app needs to store the proof data (transaction id, payment id) in order to validate later. But what if the client looses the proof data (app reinstall, etc.) in the meantime- how can then the client and the back-end server get back in sync?

Because of req #1, we don't prefer IPN. According to the IPN documentation:

Although PayPal usually processes IPN messages immediately, IPN is not synchronized with actions on your website. Internet connectivity is not always 100% reliable and IPN messages can be lost or delayed. The IPN service automatically resends messages until the listener acknowledges them. The service resents messages for up to 4 days.
    Because IPN is not a real-time service, your checkout flow should not wait for the IPN message before it is allowed to complete. If the checkout flow is dependent on receiving an IPN message, processing can be delayed by system load or other reasons. Configure your checkout flow to handle a possible delay.

The process described in the iOS SDK docs involves various API calls to verify the payment, but those calls need some proof data from the client app. But what if the client looses proof data? (req #2) Maybe the proof data could be sent to the back-end before the payment? In that case the back-end server could store the proof data until it can be validated. That process would go like this:

*

*Client app initiates a PayPal payment

*Client app sends proof data/payment info to the back-end server

*Back-end server stores payment info

*Client app follow through the payment process with PayPal

*Client app notifies back-end that the payment can be validated (no additional data needed)

*Back-end server validates payment using the data from step 2.

For this we need an API call with a parameter that is available in step 2, but most id-s are available only after payment completed. Any advices?

A: You should get a response back, indicating the payment was complete.  However if you are wanting to some validation and register the purchase complete outside of the respons, you got back from the MPL, you would either have to be using an API call or IPN.  You could use a API call to check the status of the transaction or using IPN and connecting to your database and verify that the order is complete.

A: See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/.
These docs are for the new iOS SDK being announced today, but the verification should be the same for the old MPL. (Though of course the hope is that you will like the new SDK better than the old MPL)


text:
Q: How to filter and sum the array of integers in PostgreSQL I have a task that requires to sum ALL topup_val performed by the id_user that had at least one topup_val ever by the amount of €15 exactly. This task needs to be solved in a single SELECT statement, without any window functions or subqueries (nested SELECT). I'm still a beginner in SQL so I found it struggle to finish this task.
I converted the topup_val rows for each id_user to array using array_agg(). However, I cannot filter the array using WHERE clause because WHERE clause is performed before the aggregate function.
Thank you so much!
Table topups
 id_user | topup_val
---------+-----------
    1    |    10
    1    |    15
    1    |    5
    2    |    10
    2    |    10
    3    |    15
    3    |    15
    3    |    10

Converted to array
 id_user | topup_array
---------+------------------
    1    |     {10, 15, 5}
    2    |        {10, 10}
    3    |    {15, 15, 10}

Expected result
 id_user | topup_sum
---------+------------
    1    |     30
    3    |     40

My PostgreSQL queries
SELECT id_user, array_agg(topup_val) AS array_topup
    FROM topups
    WHERE 15 = ANY(array_topup)
    GROUP BY id_user
    ORDER BY id_user;

A: Use HAVING rather than WHERE. I appears after the GROUP BY clause and is calculated after aggregation, so it can be used to filter rows after aggregation.

A: Between group by and order by you can further filter your result set with HAVING:
SELECT id_user,sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;

Demo: db<>fiddle
WITH topups (id_user,topup_val) AS ( VALUES
(1,10),(1,15),(1,5),(2,10),(2,10),(3,15),(3,15),(3,10))
SELECT id_user, sum(topup_val)
FROM topups
GROUP BY id_user
HAVING array_agg(topup_val) && array[15]
ORDER BY id_user;

 id_user | sum
---------+-----
       1 |  30
       3 |  40
(2 rows)


text:
Q: How to compute $\int x(2x-3)\,dx$ I've recently been doing calculus and I am quite confused on how to integrate.
I was wondering if someone could show me how to determine $\int x(2x-3)\,dx$.

A: $$\int x(2x-3) \, dx$$
$$=\int (2x^2 - 3x) \, dx$$
$$=\int 2x^2\, dx - \int 3x \, dx$$
$$=\frac23x^3 - \frac32x^2 + C$$

A: we have $x(2x-3)=2x^2-3x$ and $\int2x^2-3xdx=\int2x^2dx-\int3xdx=2x^3/3-3x^2/2+C$

A: There's no one-size-fits-all method to integration (unless you count something like the Risch algorithm); you just have to become familiar with the patterns and tricks to know when to use what technique. In this case, it's a matter of distributing and then remembering the fact that $\int x^n\ dx = \frac{x^{n+1}}{n+1}+C$. If you Google "integration techniques" you will find an abundance of resources.


text:
Q: Could someone explain this piece of code? import turtle
k = 4
turtle = turtle.Turtle()
turtle.speed(200)
turtle.pensize(1)
turtle.pencolor("blue")
x = 3
while True:
    for i in range(1, x):
        t.forward(n)
        t.left(360/x)
    x = x + 1

A friend posted this on Facebook and as a beginner i'm not exactly sure how it works. Please explain.

A: Your friends code contains a few errors. I modified the code to look like the example below:
import turtle
k = 4
t = turtle.Turtle()
t.speed(200)
t.pensize(1)
t.pencolor("blue")
x = 3
while True:
    for i in range(1, x):
        t.forward(i)
        t.left(360/x)
    x = x + 1

Nevertheless, Lets take it step by step:

*

*The first line, import turtle, imports all the code written in a python file called turtle, into the file your in now. The turtle module allows you to draw lines and shapes using a virtual pen to draw them.

*The next line, sets the variable k equal to the number 4.

*The third line is a bit hard to understand for a beginner, but basically what your doing is making a turtle object by using a class that was written in the turtle python file called turtle.Turtle. You should note that I'll cal our turtle object t not turtle as the module name your importing is named turtle already.

*After creating our turtle object using turtle, it now has all the attributes and methods of the turtle.Turtle class. One of the methods available is called speed(). This controls the speed of your turtle when drawing lines or shapes.

*The fourth line should be pretty self explanatory. On our turtle.Turtle object called t, we have another method called pen-size used to set the size of the pen used for drawing.

*The Fifth line just uses another method in the turtle.Turtle class to set the pen-color for drawing, blue.

*the sixth line sets the variable x equal to the number 3

*The next lines create a while-loop that will run forever. In that while-loop we tell python to:

*run a for-loop in the range 1 to 3 exclusive. In other word, run the for-loop 1 time.

*On each iteration of the for-loop, move our turtle pen forward 1 pixel.

*On each iteration of the for-loop, move our turtle pen left 180 degrees.

*The last and final line, increments the x variable by 1 number on each iteration of the while-loop, not the for-loop.

When the program is run, it will look something like the photo posted in Lyang's answer.

A: There are some errors in the code, such that k is not used, t does not exist (turtle = turtle.Turtle() should be t = turtle.Turtle() instead). I am assuming that n should be i instead.
Turtle is a package from python, but it is not a required package so your code might not run on online interpreters. When it runs, it generates an image like this (in an animation):


text:
Q: How to distinguish "RTP over TCP" from "RTP over HTTP"? dear all:
I wanna ask some questions about streaming protocol.
1.If I get video streaming use RTSP the video streaming will be sent add RTP header,but why some video streaming  also add RTP header via cgi command?
2.I could distinguish "RTP over TCP" from "RTP over UDP",but what differences between "RTP over TCP" and "RTP over HTTP"
I'm confuse ~

A: i think you're confusing RTP over HTTP with RTSP over HTTP ( and therefore RTP too ): see http://developer.apple.com/quicktime/icefloe/dispatch028.html for more info.


text:
Q: Search engine crawlers get redirected to English pages (and thus avoid other languages' pages) with a multilingual website I have the following multilingual URL structure:
example.com/article123            # english
example.com/fr/article123         # french
example.com/de/article123         # german

There is an automatic 302 redirection to the relevant language, according to the browser language ($_SERVER['HTTP_ACCEPT_LANGUAGE']). This is good for user experience, because most users haven't to manually click on a language switcher. According to my statistics, it works well.
Problem: when using Ahrefs Website Audit tool (it will be the same for search engine crawlers, GoogleBot, ...), I see that their crawlers get 302-redirected and therefore never visit the french website.
Indeed when the crawler (probably set to english) visits example.com/fr/article123 it will be redirected to example.com/article123. I imagine that these crawlers don't take cookies in consideration, so it will be the same for all pages.
What techical solution should I use to avoid a multilingual website to be crawled incorrectly by search engine bots?
TL;DR: How could I trigger a redirection according to the browser language for a normal user, and not redirect bots (such as GoogleBot, Facebook or Twitter Crawlers that are responsible for the "Share..." displayed cards)?
This is what I use:
function lang_redirect() {
    if (isset($_COOKIE['lang_redirect']))  // already redirected in the last 24 hours, don't do it again
        return;
    global $lang, $requesturi;
    $browserlang = getlang($_SERVER['HTTP_ACCEPT_LANGUAGE']);   // fr, de, en...
    $link = lang_translation_link($browserlang);
    if (($browserlang != $lang) && ($link != ''))
        header("Location: " . $link);      // redirect now!
    header("Set-Cookie: lang_redirect=1; Max-Age=86400; Path=/; HttpOnly; SameSite=Lax");
}

Note: The redirection happens only once (by setting cookies), because a visitor with a browser set to german could want to visit the english website and not be redirected every time to the german website. Example:
example.com/article123          # browser set to german
=> example.com/de/article123    # automatic redirection, setting a cookie to not redirect anymore
example.com/article123          # user returns on english website
=> no redirection here because there has already been a first redirection

A: You need to remove your system that automatically redirects based on $_SERVER['HTTP_ACCEPT_LANGUAGE'].  It makes your site uncrawlable by search engines and it it is bad for user experience.
Instead of automatically redirecting, you can put a prominent notice in the page that says:

Your browser says that you prefer English.  Would you like to visit the English version of the page now?
[Switch to English]

For more information see How should I structure my URLs for both SEO and localization? which has a whole section on why redirection with the accept-language-header kills SEO.


text:
Q: Why am I regularly getting +5 from upvotes when I am nowhere close to the rep cap?
Possible Duplicate:
Should the weight of question upvotes be reduced?

On Stack Overflow, I frequently get upvoted answers that only receive a +5 upvote, even if it is the first score I receive that day.
I thought +5 only came into effect upon hitting the 200 (or whatever) daily reputation limit.
Any ideas?

A: From looking at your profile, those are upvotes on QUESTIONS.
Question upvotes are worth 5 points, and answer upvotes are worth 10.


text:
Q: Trying to Add Field and Calculate Area of a selected shapefile I'm a Python beginner working with arcpy. I want to take a selected shapefile and add an area field to it, and then populate that field.
As of now, my code only works if I have the selected layer as a parameter input by the user. If I substitute that for the "selected layer" (which is commented out right now), the field is created, but it does not populate. I cannot figure out why.
What do I need to do in order to make this work?
import time, arcpy, sys, os, pythonaddins

## Set parameters

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
mxdName = os.path.basename(mxd.filePath)
directory = os.path.dirname(mxd.filePath)
layers = arcpy.mapping.ListLayers(mxd, "*", df)
arcpy.env.overwriteOutput = False
#####SelectedLayer = pythonaddins.GetSelectedTOCLayerOrDataFrame()
SelectedLayer = arcpy.GetParameterAsText(0)
f_name = "Area_ha"
f_type = "DOUBLE"
f_precision = 5
f_scale = ""
f_length = ""
f_alias = ""
f_null = "NULLABLE"
f_required = "NON_REQUIRED"
f_domain = ""

## Create Area field, calculate area in hectares

arcpy.AddField_management(SelectedLayer, f_name, f_type, f_precision,
f_scale, f_length, f_alias, f_null, f_required, f_domain)
areaexpression1 = "{0}".format("!SHAPE.area@HECTARES!")
arcpy.CalculateField_management(SelectedLayer, f_name, areaexpression1,
"PYTHON_9.3", "")

A: The pythonaddins module is intended only for use within a Python add-in and cannot be used in a script tool (see the note at the top of the linked page).
You will therefore have to make an add-in to use the GetSelectedTOCLayerOrDataFrame functionality or you can continue to use a script tool and get the input from the user with arcpy.GetParameterAsText(0)


text:
Q: Iterate over the same array from 2 different directions I have this problem from school:
You get a list of N students and a list of grades for each student. Every student gets coins. A student which has bigger grade than his neighbours from list earns more coins than them. Find the coins which every student must recieve.
Input:
6
Ionel
Mihai
Elena
Maria
George
Irina
9
10
8
6
9
10

Output:
Ionel 1
Mihai 3
Elena 2
Maria 1
George 2
Irina 3

Here is my code:

static void Main()
        {
            int number = Convert.ToInt32(Console.ReadLine());
            string[] studentsList = FillTheList(number);
            int[] studentsGrades = ConvertList(FillTheList(number));
            PrintResult(studentsList, CalculateCoins(studentsGrades, number));
        }

        static string[] FillTheList(int number)
        {
            string[] result = new string[number];
            for (int i = 0; i < number; i++)
            {
                result[i] = Console.ReadLine();
            }

            return result;
        }

        static int[] ConvertList(string[] array)
        {
            int[] result = new int[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                result[i] = Convert.ToInt32(array[i]);
            }

            return result;
        }

        static int[] GiveEachStudentCoins(int number)
        {
            int[] result = new int[number];
            result[0] = 1;

            return result;
        }

        static void CheckArray(int[] array, int[] theResult, int number, int counter)
        {
            int i = number;
            int count = counter;
            int[] result = theResult;
            for (int j = 0; j < array.Length; j++)
            {
                if (array[i] < array[j])
                {
                    result[j] += count;
                }
                else
                {
                    break;
                }
            }
        }

        static int[] CalculateCoins(int[] array, int number)
        {
            int[] result = GiveEachStudentCoins(number);
            const int count = 1;
            for (int i = 1; i < array.Length; i++)
                {
                if (array[i - 1] < array[i])
                {
                    result[i] += result[i - 1] + count;
                }
                else
                {
                    result[i] += count;
                    CheckArray(array, result, i, count);
                }
            }

            return result;
        }

        static void PrintResult(string[] array, int[] array2)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] += " " + array2[i];
            }

            foreach (string student in array)
            {
                Console.WriteLine(student);
            }
        }

It works for ascending and descending order of grades, and also for equal grades. But it doesn't work for mixed order. Here is the result I get:
Ionel 3
Mihai 4
Elena 2
Maria 1
George 2
Irina 3

My problem is on the CheckArray method I think, and I don't know how to change the logic for this thing to work.

A: We can access the neighboring elements while walking through the array in a for loop by subtracting or adding 1 to the index of the current item. Of course before we do this, we have to make sure that the neighbor we want to check actually exists (if i == 0 then we can't access index i - 1, and if i == array.Length - 1, then we can't access index i + 1).
Given this knowledge, we can follow a simple formula, just as if we were doing it "by hand" on a piece of paper:

*

*Start all values in the coins array with 1

*Loop through each item in the input array.

*If there's an item to the left and it's smaller than this item, then set the corresponding coins item to be one more than the coins item to it's left

*If there's an item to the right and it's smaller than this item, and if the corresponding coins item is equal to the coins item to its right, then increment this item by 1

*If we incremented this item after comparing to the right, then we need to re-check the item to the left and increment it if necessary (based on the corresponding values in the items array).

If that didn't make complete sense, try it on paper and it may be more obvious. Otherwise, hopefully this code sample will help:
public static int[] GetCoins(int[] input)
{
    int[] coins = new int[input.Length];

    // Initialize coins array with all '1's (similar to 'GiveEachStudentCoins')
    for (int i = 0; i < coins.Length; i++)
    {
        coins[i] = 1;
    }

    // Examine the neighbors of each item in the array
    for (int i = 0; i < input.Length; i++)
    {
        // Check left neighbor (if there is one)
        if (i > 0 && (input[i] > input[i - 1]))
        {
            if (coins[i] <= coins[i - 1])
            {
                coins[i] = coins[i - 1] + 1;
            }
        }

        // Check right neighbor (if there is one)
        if (i < input.Length - 1 && input[i] > input[i + 1])
        {
            if (coins[i] == coins[i + 1])
            {
                coins[i]++;

                // Recheck left since we incremented this one
                if (i > 0 && input[i - 1] > input[i])
                {
                    coins[i - 1]++;
                }
            }
        }
    }

    return coins;
}

Here's some sample code that can be used for testing, so you don't have to manually enter numbers into the console each time (this requires adding using System.Linq to the top of the file):
public static void Main(string[] args)
{
    // Populate the grades you want to test here
    int[] studentsGrades = {9, 10, 8, 6, 9, 10};

    // Student names are automatically generated
    string[] studentsList = Enumerable.Range(1, studentsGrades.Length)
            .Select(i => $"Student #{i} grade: {studentsGrades[i - 1]}\tcoins: ")
            .ToArray();

    // Call the new method to get the coins array
    int[] coins = GetCoins(studentsGrades);

    // Show the results
    PrintResult(studentsList, coins);

    Console.WriteLine("Done! Press any key to exit...");
    Console.ReadKey();
}


text:
Q: Get all components with a specific interface in Unity some GameObjects in my scene implement the interace ISaveable. In my script, I want to find all these interfaces and store them. Later on I can loop through them and call their implemented method SaveData().
My current workaround to find these interfaces:
    List<ISaveable> saveables = new List<ISaveable>();
    MonoBehaviour[] sceneObjects = FindObjectsOfType<MonoBehaviour>();

    for (int i = 0; i < sceneObjects.Length; i++)
    {
        MonoBehaviour currentObj = sceneObjects[i];
        ISaveable currentComponent = currentObj.GetComponent<ISaveable>();

        if (currentComponent != null)
        {
            saveables.Add(currentComponent);
        }
    }

The code works fine but is there a better way? I don't want to search for each Monobehaviour in the scene and then try to get its interface component.

A: Simplified filter using Linq
You can use Linq OfType
ISaveable[] saveables = FindObjectsOfType<MonoBehaviour>().OfType<ISaveable>().ToArray();

of course it still requires to find all objects first.
Note though that it underlies the general limitations of FindObjectsOfType regarding inactive GameObjects or disabled behaviors.

Iterate through the Hierachy
You could extend it to go through all root level objects of the scene. This works since afaik GetComponentsInChildren indeed does work also with interfaces!
var saveables = new List<ISaveable>();
var rootObjs = SceneManager.GetActiveScene().GetRootGameObjects();
foreach(var root in rootObjs)
{
    // Pass in "true" to include inactive and disabled children
    saveables.AddRange(root.GetComponentsInChildren<ISaveable>(true));
}

If it's more efficient - yes, no, maybe, I don't know - but it includes also inactive and disabled objects.
And yes one could extend that to iterate through multiple loaded scenes using
var saveables = new List<ISaveable>();
for(var i = 0; i < SceneManager.sceneCount; i++)
{
    var rootObjs = SceneManager.GetSceneAt(i).GetRootGameObjects();
    foreach(var root in rootObjs)
    {
        saveables.AddRange(root.GetComponentsInChildren<ISaveable>(true));
    }
}

Not use an interface in the first place
This alternative is a bit similar to this answer but it has a huge flaw: You would need a specific implementation for the interface in order to make it work which invalidates the whole idea of an interface.
So the big question also from the comments there is: Why have an interface at all?
If it is anyway only going to be used for MonoBehaviour you should rather have an abstract class like
public abstract class SaveableBehaviour : MonoBehaviour
{
    // Inheritors have to implement this (just like with an interface)
    public abstract void SaveData();
}

This already solves the entire issue with using FindObjectsOfType anyway since now you could simply use
SaveableBehaviour[] saveables = FindObjectsOfType<SaveableBehaviour>();

but you can still go further: For even easier and more efficient access you can make them register themselves completely without the need of a manager or Singleton pattern! Why should a the type not simply handle its instances itself?
public abstract class SaveableBehaviour : MonoBehaviour
{
    // Inheritors have to implement this (just like with an interface)
    public abstract void SaveData();

    private static readonly HashSet<SaveableBehaviour> instances = new HashSet<SaveableBehaviour>();

    // public read-only access to the instances by only providing a clone
    // of the HashSet so nobody can remove items from the outside
    public static HashSet<SaveableBehaviour> Instances => new HashSet<SaveableBehaviour>(instances);

    protected virtual void Awake()
    {
        // simply register yourself to the existing instances
        instances.Add(this);
    }

    protected virtual void OnDestroy()
    {
        // don't forget to also remove yourself at the end of your lifetime
        instances.Remove(this);
    }
}

so you can then simply inherit
public class Example : SaveableBehaviour
{
    public override void SaveData()
    {
       // ...
    }

    protected override void Awake()
    {
        base.Awake(); // Make sure to always keep that line

        // do additional stuff
    }
}

and you could access all instances of that type via
HashSet<SaveableBehaviour> saveables = SaveableBehaviour.Instances;
foreach(var saveable in saveables)
{
    saveable.SaveData();
}

A: You could have a manager class holding a collection/list of ISaveable.
You can then make that manager class a singleton by setting the Singleton value in its Awake method.
class SaveManager(){
public static SaveManager Instance;
Awake(){
if (Instance == null)
   {
    Instance = this;
   }
}

List<ISaveable> SaveAbles;
public void AddSaveAble(ISaveAble saveAble){
//add it to the list.
}
}

Then in the Start method of class implementing the ISaveable interface you can use the Singleton to add it to the total list.
class Example : MonoBehaviour, ISaveable
{
void Start(){
SaveManager.Instance.AddSaveAble(this);
}
}

That way, each SaveAble adds itself to the manager via the managers method when it is created.
Note that it is important that the Singleton is set in Awake so it can be used in Start, as Awake comes first in the lifecycle.

A: How about having global state, perhaps an list of ISaveable, and have each savable object add a reference to it during start()?  Then you can simply iterate through the array, invoking SaveData() on each ISaveable reference?

A: The typical real-world solution:
public interface Automateme
{
    public void Automate();
}

then ...
void _do()
{
    Automateme[] aa = GameObject
    .FindObjectsOfType<MonoBehaviour>()
    .OfType<Automateme>()
    .Where(a => ((MonoBehaviour)a).enabled)
    .ToArray<Automateme>();

    if (aa.Length == 0)
    {
        Debug.Log($"Automator .. none");
        return;
    }
    Debug.Log($"Automator .. " + aa.Length);

    foreach (Automateme a in aa)
    {
        Debug.Log($"Automator {a.GetType()} {((MonoBehaviour)a).gameObject.name}");
    }

    // do something to one of them randomly, for example! ->
    aa.AnyOne().Automate();
}

One point, it is all-but inevitable that you will need the object also as a MonoBehavior, ie you will be casting it to a MonoBehavior (as in the simple example of getting the name of the game object), so it's sensible (and no less/more inefficient) to use the FindObjectsOfType<MonoBehaviour>() idea first mentioned by @derHugo
Some points

*

*Of course, obviously, in some situations you wouldn't at all do what is asked in this question, you'd trivially "keep a list" of the items under consideration. (And that would vary greatly depending on the situation, do you only want active ones, do you want to include items on their first frame of bringup, etc etc etc). The entire point of the question is for the (many, typical) situations where you want to get them on the fly and caching is not relevant

*Unity development, confusingly, has a massive, just ridiculously big, domain range. Many types of projects have perhaps a dozen game objects in the whole scene; other types of projects can have vast numbers of game objects in the scene. Games with 2D physics are incredibly different from games with 3D physics, rendering approaches are incredibly different from shader approaches, and so on. Naturally with any "style" question like this if you are coming from a certain "domain" in your head, the answer can be quite different.

*Regarding FindObjectsOfType and similar calls, it's worth remembering that Unity efficiency has incredibly moved on from the early days. It used to be that the "first thing you'd tell new Unity programmers" was "Don't do something every frame that searches the scene!!! OMG! You'll slow down to 1fps!"  Of course that is still true in certain, perhaps many, domains.  BUT it is (for a decade now) often just completely wrong.  Unity's caching and handling of scene objects is now blisteringly fast (you can't write faster) and - as mentioned in the previous point - you're often just talking about a handful of items anyways. {A good example of the change in efficiency of the entire Unity paradigm is "pooling". (Any game programmers not as old as me can look up what that was :) )  In the early days of Unity you'd Pool! everything in a panic, My God, I may have three tanks at once, get a pooling library! Indeed I am so old I wrote one of the first popular Pooling articles that everyone used for awhile (long since deleted). Nowadays Unity's handling of instantiating prefabs or offscreen models is so fast and clever that you could more or less say they offer pooling built-in, and nowadays there's no need at all to pool things like everyday bullets from machine guns, etc. Anyway the point of this example is just that the (very old) "standard advice" about not searching the scene has to be understood more completely, these days.}
Swinging back to the original question:

I don't want to search for each Monobehaviour in the scene and then try to get its interface component.

The only way in a game engine to search each object in a scene, is to search each object in the scene. So there's no way around that.  Of course, one can "keep a list" BUT it rather misses the two points (A) in some/many situations that's just not viable/sensible in a game architecture and (B) Unity is already incredibly good at keeping a list of game objects / components, it's the whole raison d'etre of a frame engine.  (Note that if it's a physics game, the whole PhysX system for goodness sake is doing an astounding, cutting-edge job, of "finding things every frame", using mathematically freaky spatial hashing and more, dealing with orders of complexity that go with the square or worse of every physics poly in the scene! Compared to that it is misguided to worry about you pulling out 3 items from a list of 50 (which are flawlessly hashed and managed for efficiency by the frame engine anyway).)

A: Note that this solution is highly inefficient, but you could use LINQ to filter out the components that implement your interface. In this case MyInterface is the interface that we want to query for.
MyInterface[] myInterfaces = GameObject.FindObjectsOfType<MonoBehaviour>()
    .OfType<MyInterface>()
    .ToArray();

Small note to clarify "inefficient": With Unity optimizing their object querying methods the call is not even that bad. The issue is that LINQ allocates a lot of GC, which could introduce frame drops, which is why you should never run these "heavy" operations on a per-frame basis.
Running the query upon startup or when doing an obvious intensive operation (saving/loading) is totally fine.

A: In my case I was using this implementation:
    MonoBehaviour[] saveableScripts = (MonoBehaviour[])FindObjectsOfType(typeof(MonoBehaviour));
    foreach (var enemy in saveableScripts)
    {
        if (enemy is ISaveable == false)
            continue;

        // you code ...
        saveables.Add(currentComponent);
    }

A: Here is an improve of your method to get all the MonoBehavior wiht your interface actually in your scenes.
void Start()
{
    var myInterface = typeof(MyInterface);
    var monoBehavior = typeof(MonoBehaviour);
    var types = Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(p => myInterface.IsAssignableFrom(p) && monoBehavior.IsAssignableFrom(p));

    var myInstance = new List<MyInterface>();

    foreach (var type in types)
    {
        myInstance.AddRange(FindObjectsOfType(type).Select(x => x as MyInterface));
    }
}

Here you don't go through all the GameObject in the scenes, but you do more FindObjectsOfType call, + you have to cast. But no more GetComponent needed.
So depend on your case, but if you put the reflection part in cache (during a loading moment) it can avoid you to implement the Manager pattern and you can keep your interface architecture.
Otherwise you can take a look at the observer pattern, it is a different way to manage call over different class type. https://sourcemaking.com/design_patterns/observer

A: You can improve the code by replacing
ISaveable currentComponent = currentObj.GetComponent<ISaveable>();

with
ISaveable currentComponent = currentObj as ISaveable;

A: One way is to use unity container (though slightly older way). Register all the dependencies to container through configuration. All the instances of the ISaveable can be registered to unit container and then resolve them in the code
example:
unity container in web.config:
<container name="GameObjectContainer">
    <register type="ISaveable" mapTo="Example1" />
    <register type="ISaveable" mapTo="Example2" />
</container>

ISavable definition:
public interface ISavable
{
    void SaveData();
}

ISavable implementation:
public class Example1 : ISavable
{
    public void SaveData()
    {
    }
}

public class Example2 : ISavable
{
    public void SaveData()
    {
    }
}

A: I agree with the idea of using an ISaveable manager for this use case, as Doh09 and others suggest. But to answer your question as asked, you could traverse the entire scene hierarchy, or multiple scenes' hierarchies, as follows:
public class Foo : MonoBehaviour
{
    List<ISaveable> saveables;
    void RefreshSaveables()
    {
        saveables = new List<ISaveable>();
        for (var i = 0; i < SceneManager.sceneCount; ++i)
        {
            var roots = SceneManager.GetSceneAt(i).GetRootGameObjects();
            for (var j = 0; j < roots.Length; ++j)
            {
                saveables.AddRange(roots[j].GetComponentsInChildren<ISaveable>());
            }
        }
    }
}

The advantage of this over your original code is that you don't need to save every MonoBehaviour in the scene in order to later filter it - however I still think it is preferable for each ISaveable to register itself on Start and let the manager call their Save methods.


text:
Q: Incorrect derived query for byId in Spring Data Neo4j I have two entities: User and Connection, along with two appropriate repositories. Both entities has @GraphId id field. Connection entity has User user field.
In ConnectionRepository interface I added following method:
List<Connection> findByUserId(long userId)

But it doesn't work. It generates incorrect cypher query. I think it incorrect, because it contains clause like this:
WHERE user.id = 15

which is not working, because id is not a property. It must be:
WHERE id(user) = 15

Is this a bug? In any case, how can I get it to work?

A: The derived query translates to the property id of the user defined on the Connection. It is quite possible that node entities contain a user managed id property as well and it would be incorrect to assume that id is always the node id.
In this case, you might want to use a @Query instead.
@Query("MATCH (user:label) WHERE ID(user)={0} return user")
List<Connection> findByUserId(long userId)


text:
Q: Why does my submit button not work on first submit? I want to authenticate the user and redirect them to the home page after. When I submit this form redux state is being set, but the user is not redirected to the home page on first submit; I have to submit twice or sometimes three times for it to properly redirect me to the home page.
Any ideas as to what I may be doing wrong?
async function login(e) {
  e.preventDefault()
  const response = await axios.post("http://localhost:3001/login", {
    email,
    password
  }, {
    withCredentials: true
  })
  if (response.data.auth) {
    history.push("/")
    store.dispatch({
      type: "setUser",
      payload: response.data
    })
  }
}

Here is my code for the login form.
<form className="login_form" onSubmit={(e)=> login(e)}>
  Email
  <input type="text" onChange={e=> setEmail(e.target.value)} required placeholder="enter your email"/>
  Password
  <input type="password" onChange={e=> setPassword(e.target.value)} required placeholder="enter your password"/>

    <button className="route_to_register_btn" onClick={()=> history.push("/register")} type="button">Create account</button>
    <button className="login_submit_btn" type="submit">Sign in</button>

</form>

Here I initialize history in its own file and pass it to the root component as a prop.
const createHistory = require("history").createBrowserHistory
export default createHistory();


text:
Q: Can MS Exchange Autodiscover service share same domain as website? I have a client that wants (or needs, not sure) to use the MS Exchange Autodiscover service on their naked domain https://example.com.
Their IT person has asked me to place (move) their new in-development WordPress marketing website on the www subdomain, thinking that these two cannot both share the naked domain.
If this is truly necessary (is it?) then I would be ok with that (not hard to point it to wherever)
HOWEVER they have also told me that we won't be able to redirect requests for the pages/URLs on naked domain to the new www subdomain. I told the client that not redirecting would be committing Google suicide, not to mention a bad user experience for people using links on other websites, bookmarks, links in old email signatures, etc.
Here is their (redacted) message:

Beginning with Outlook 2007, through to Outlook 365, it goes through a
specific search order to connect to a Microsoft Exchange Server.

*

*SCP (Service Connection Point) in Active Directory. (This is for users connecting to Exchange Server from inside the office.)

*Root Domain check. (If the above fails, it will then check for example, https://redacted.com/autodiscover/autodiscover.xml, which
will be for people using Outlook outside the office.)
a. As you can see, if the website is on the root domain, the
website will get a request from Outlook.

*Autodiscover DNS check.

*…
By using www.redacted.com, you can avoid the website being
contacting by an Outlook client and potentially causing issues.
It also means that we cannot use redirects for the website to redirect
it from for example, redacted.com to www.redacted.com, as
this will still confuse autodiscover in Outlook.
If having the website on the root domain is needed, then there is some
work you can do on the website to specifically redirect autodiscover
queries in point 2 above.
Specifically, an SSL certificate is needed, which is now standard on
websites. And a redirect is needed to redirect all requests from for
example, redacted.com/Autodiscover to
autodiscover.redacted.com.
https://practical365.com/exchange-server/fixing-autodiscover-root-domain-lookup-issues-mobile-devices/
Which option you use is up to you.

I feel like I'm being janked around a bit on this so I'm trying to find out the truth. Also this is totally outside of the scope of the marketing website proposal I am building for the client, so I don't appreciate him putting this back on me to "decide" on.
Basically these are two different projects here (the MS Exchange service and the marketing website), that aren't really related at all. I was just providing some free advice saying that they really should employ redirects (ie, if the website needs to be "moved" to another (sub)domain... which I'm not convinced it does).
I am skeptical that this "can't be done", as I'm sure a lot of people are using this technology alongside their marketing websites.
So to boil it down:

*

*Can they both share the same root domain?

*And if not, can we somehow employ 301 page-to-page redirects from the old website to the new www subdomain?

PS - Anecdotally, the website is small in terms of number of pages (say 10 pages).


text:
Q: Login with FB button Framework7 im having a problem on implementing the login FB on my framework7 code. It just doesnt display the button, as follows:

Left panel content goes here

        <fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
        </fb:login-button>
        <button class="btn-default" scope="public_profile,email" onlogin="checkLoginState();">Login fb</button>

Any sugestion on how to tackle this problem?

A: Does your project is in cordova environment ? , I would suggest You using cordova fb plugin
https://github.com/Wizcorp/phonegap-facebook-plugin
Mine work like a charm

*

*Login page

                        Sign In

                        Register

                        Login With Facebook

                        Login With Google

*init function
$('#facebookLogin').on('click', function () {
            facebookLogin();
        })

*facebookLogin function
function facebookLogin() {
   facebookConnectPlugin.login(["public_profile", "user_birthday", "user_hometown", "email"],
    fbLoginSuccess,
    function (error) { app.app.alert(JSON.stringify(error)) }
);

 var fbLoginSuccess = function (userData) {
   // use token from userData to your existing login system
   //userData.authResponse.accessToken
  };

}


text:
Q: Create session in openerp gtk-client 6.0 Hi currently i'm using Openerp 6.0 (GTK-Client)
Do you guys have any idea about how to create a session for GTK-Client in openerp 6.0?
The reason of why i want to create is because of i want to ask system rollback the whole process while the connection from client to server was lost.
i already tried some of error handling, such:

*

*IOError for broken pipe and connection reset

*socket.error

*rpcsession

*etc

but all of them was not working. that's why i was thinking of create a session for GTK-Client.
Do you guys think it is possible to create a session for GTK-Client in openerp 6.0? If not, do you guys have any idea for handled connection lost?

A: I am also working on this same problem as well, I am working on OpenERP 5.0.10. I have done it on the client side. It worked correctly. The link Below contains the file where I made my modifications.
https://dl.dropboxusercontent.com/u/37021432/rpc.py
Just replace it with your own in clients code. I hope there wont be many differences in 5 and 6's clients versions. I am currently trying it on Server as well. I will post the answer as soon as I am done with it


text:
Q: Library not loaded: '@rpath/OneSignalCore.framework/OneSignalCore' - Thread 1: signal SIGABRT Xcode Version: 14.2
Device: Iphone 6S
React Native Version: 0.69.6
When I try to upload my react native project to my ios device, I get this error

A: First I added "OneSignalCore.xcframework" to the library, then I pressed the run button. It gave an error again and said that it could not find "OneSignalOutcomes.xcframework". So I added it to the library and it worked as a result.

A: The solution I got is really very weird and it just came out while trying and was able to resolve this issue for me. So if anyone here is getting the same error can try this.
Steps
Open Xcode -> Select your app in the Targets -> Go to General Tab -> Frameworks, Libraries and Embedded Content.
Click on + . Search for OneSignal in it and add OneSignal.xcframework.
Here comes the weird part.
After OneSignal.xcframework is added. Just remove this OneSignal.xcframework by selecting and clicking -.
Now just build your app again. Your app should run now.
!!! IMPORTANT !!!
If doesn't work try with OneSignalCode


text:
Q: Mysql - joins - too many rows are being returned - one for each of the joined table but dont want that I have this kind of mysql db (table name/fields)

tbl_users: id, title, approved
tbl_photos: id, user_id, title, filename

I have one row in users, and three photos (all with user_id = the id of the user)
doing this:
select
tbl_users.*,
tbl_photos.filename

from tbl_users

left join tbl_photos on tbl_photos.user_id = tbl_users.id

where tbl_users = '1' order by rand()

(table query simplified a little bit)
doing that sql query returns three rows . I only want one row (ie i want the user row, plus any random photo that has the user_id of that user id)
i've tried all joins - left right inner but they always return 3 rows

A: Your code should be like the following
select
tbl_users.*,
tbl_photos.filename

from tbl_users

left join tbl_photos on tbl_photos.user_id = tbl_users.id

where tbl_users = approved order by rand() LIMIT 1

The LIMIT keyword will restrict the query for returning only 1 row.
A simple list of my-sql command examples can be found here
http://itswadesh.wordpress.com/2011/04/12/mysql-commands/

A: you also add DISTINCT:
select  DISTINCT tbl_users.id,
        tbl_users.title,
        tbl_users.approved,
        tbl_photos.filename
from tbl_users left join tbl_photos
       on tbl_photos.user_id = tbl_users.id
where tbl_users = 'approved' order by rand()

A: It is very simple if you want to get only one row for each do it like this
select
tbl_users.*,
GROUP_CONCAT(tbl_photos.filename) as Photos

from tbl_users

left join tbl_photos on tbl_photos.user_id = tbl_users.id

where tbl_users = '1' order by rand()

It will give you comma seperated values in a single field

A: If filename is the only field you will retrieve from tbl_photos, this could deliver what you need:
select
    tbl_users.*,

    (select filename
     from tbl_photos where user_id = tbl_users.id
     order by rand()
     limit 1) as filename

from tbl_users

If you want other information from photos, this is the query:
select tbl_users.*, 'x' as separator, tbl_photos.*
from tbl_users
left join tbl_photos on tbl_photos.user_id = tbl_users.id
where (tbl_users.id, tbl_photos.id) in

    (
    -- you can run this query independently
        select

            id,

            (select id
             from tbl_photos
             where user_id = tbl_users.id
             order by rand()
             limit 1)

        from tbl_users
    )


text:
Q: Dynamic sort options for SilverShop Module I have been breaking my head on how to do a dynamic sort option, which will show/hide the sort option, depending on whether the category has the "Manufacturer" that the sorter is looking for...
private static $sort_options = array(
    'Alphabetical' => 'URLSegment',
    'Lowest Price' => 'BasePrice'
);

Normally the sorter gets its options like this, but this will not seem to cut it for the task at hand.
If anyone can give some tips or ideas of what I can try, that would be really helpful. What am I missing?

A: Your best bet is to override the getSorter method in ProductCategory_Controller and add any additional logic there:
https://github.com/silvershop/silvershop-core/blob/master/code/product/ProductCategory.php#L202


text:
Q: Send File to my website I am trying to send a file through FTP in VB.NET.
I have 3 labels with the server password and user information and a textbox with the file location called txtFile and my Textbox 1 has the new file name.
I click send and it doesn't come up in my website?
My.Computer.Network.UploadFile(txtFile.Text,
                               ServLabel.Text & TextBox1.Text,
                               PassLabel.Text,
                               UserLabel.Text)

A: According to; http://msdn.microsoft.com/en-us/library/dfkdh7eb(v=vs.90).aspx
You have your Username and Password swapped;
Public Sub UploadFile( _
   ByVal sourceFileName As String, _
   ByVal address As String, _
   ByVal userName As String, _
   ByVal password As String _
)

and should be doing;
My.Computer.Network.UploadFile(txtFile.Text,
                               ServLabel.Text & TextBox1.Text,
                               UserLabel.Text,
                               PassLabel.Text)

Also, make sure you have the necessary Path Separators between your Server Address, and the file name.

A: You could use the FtpWebRequest class. Here is an example: http://msdn.microsoft.com/en-us/library/ms229715.aspx

A: using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static async Task Main()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");

            // Copy the contents of the file to the request stream.
            using (FileStream fileStream = File.Open("testfile.txt", FileMode.Open, FileAccess.Read))
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    await fileStream.CopyToAsync(requestStream);
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    {
                        Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
                    }
                }
           }
        }
    }
}


text:
Q: Is there a way to see the automator script in text? If i create some type of workflow on Automator, can I see the script in plain text?
For example, maybe get the script and push it out through Apple Remote Desktop to a remote computer?

A: While you could look at, copy and transfer, the contents of the document.wflow file found inside the filename.workflow bundle or Automator filename.app bundle, it's just XML, I'm not sure how much good it will do you as it will not open in the Automator.app.  It will open  with the Automator Runner however it may not run as intended, depends on what's in there.


text:
Q: Multiplying each value with every other value in a vector I have a vector like:
ar=[0,1,2,3]

I want to multiply every value with eachother. And my output could be like:
ar2=[[0,0,0],
     [0,2,3],
     [0,2,6],
     [0,3,6]]

Could you help me for creating a "for loop"?

A: You can do this using list concatenation
res = [[i*j for j in a if i!=j] for i in a]

[[0, 0, 0],
[0, 2, 3],
[0, 2, 6],
[0, 3, 6]]

Edit:
Explanation: This runs two loops and multiplies i and j if the values are not equal.
As @abarnert pointed out, this will not work if the values are repeated, something like [1, 0, 2, 2]
In that case, we can use the index to identify the element instead of values.
Edit2: As pointed out by @coldspeed, using enumerate is a cleaner and better way to do this, e.g.:
res =[[x * y for i, y in enumerate(a) if i != j] for j, x in enumerate(a)]

Using range, we can do this way:
res = [[a[i]*a[j] for j in range(0,len(a)) if i!=j] for i in range(0,len(a))]

Running this for a = [0 ,1 ,2 ,2] we get
[[0, 0, 0],
 [0, 2, 2],
 [0, 2, 4],
 [0, 2, 4]]

A:
Could you help me for creating a "for loop"?

The for loop is the easy part. Although it's actually two for loops, nested, because you need "every" value with "each" other. So:
for every_value in ar:
    for each_other in ar:

The tricky part is that you want to multiply by each other value—that is, every value except itself.
It's not entirely clear whether you mean you want each value to skip multiplying by equal values, or you only want to skip multiplying by itself. Of course there is no difference with [0,1,2,3] because there are no equal values, but if you try it with, say, [0,1,2,0], do you want to get 3 values in every row, or 3 values in some rows and 2 in others?
I'll assume you want to just skip the value itself. While there are cleverer ways to do this, let's pick the simpler one: use the index.
for i, x in enumerate(ar):
    for j, y in enumerate(ar):
        if i == j:
            continue # don't multiply a value by itself

So now, it's just a matter of multiplying and storing the values:
ar2 = []
for i, x in enumerate(ar):
    row = []
    for j, y in enumerate(ar):
        if i == j:
            continue
        row.append(x * y)
    ar2.append(row)

If you want to make this more compact, you can turn the inner loop into a comprehension:
ar2 = []
for i, x in enumerate(ar):
    row = [x * y for j, y in enumerate(ar) if i != j]
    ar2.append(row)

Or even the whole thing:
ar2 = [[x * y for j, y in enumerate(ar) if i != j]
       for i, x in enumerate(ar)]

A: You can try this:
ar=[0,1,2,3]
expected_list=[]

for i in range(len(ar)):
    temp_list = []
    for j in range(len(ar)):
        if i!=j:
            temp_list.append(ar[i]*ar[j])
    expected_list.append(temp_list)
print(expected_list)

Output:
[[0, 0, 0], [0, 2, 3], [0, 2, 6], [0, 3, 6]]


text:
Q: A question about calculating conditional probability $P(B)=2/3, P(C)=3/4, P(A|C)=1/6, P(A|B \cap C)=1/12$, finds:
(a)$ P(C|B)$?
(b)$ P(A \cap C|B)$
(c) $P(\overline{B}|A \cap C)$
I only know that $P(A|C)=1/6 = P(A\cap C)/P(C)$ so $P(A\cap C) = 1/8$.
$P(A|B \cap C)=1/12 = P(A \cap B \cap C)/P(B \cap C) = 1/12,$ but we do not know $P(A \cap B \cap C)$ and we don't know $P(B \cap C).$
I got stuck here. How to approach this question?
Thank you very much!

A: You've not given enough information to calculate any of the three quantities in (a), (b) or (c).  Let $\ \alpha,\beta,\gamma\ $ be any real numbers satisfying
\begin{align}
\frac{5}{144}&<\alpha<\frac{5}{88}\\
0&<\beta<\frac{2}{3}-12\alpha\\
0&<\gamma<12\alpha-\frac{5}{12}
\end{align}
and
\begin{align}
p_{000}&=\alpha\\
p_{001}&=\beta\\
p_{010}&=\frac{1}{8}-\alpha\\
p_{011}&=\gamma\\
p_{100}&=11\alpha\\
p_{101}&=\frac{2}{3}-12\alpha-\beta\\
p_{110}&=\frac{5}{8}-11\alpha\\
p_{111}&=12\alpha-\gamma-\frac{5}{12}\ .
\end{align}
Then $\ p_\omega\ $ is a probability mass function on the set
$$
\Omega=\{000,001,010,011,100,101,110,111\}\ .
$$
Now let
\begin{align}
A&=\{000,001,010,011\}\\
B&=\{000,001,100,101\}\ \ \text{and}\\
C&=\{000,010,100,110\}\ .
\end{align}
Then
\begin{align}
P(B)&=p_{000}+p_{001}+p_{100}+p_{101}\\
&=\frac{2}{3}\\
P(C)&=P_{000}+p_{010}+p_{100}+p_{110}\\
&=\frac{3}{4}\\
P(A\cap C)&=p_{000}+p_{010}\\
&=\frac{1}{8}\\
P(A\cap B\cap C)&=p_{000}\\
&=\alpha\\
P(B\cap C)&=p_{000}+p_{100}\\
          &=12\alpha\\
P(A\,|\,B\cap C)&=\frac{P(A\cap B\cap C)}{P(B\cap C)}\\
&=\frac{1}{12}\ .
\end{align}
Thus, these events in this probability space satisfy all the identities given, but
\begin{align}
P(B\,|\,C)&=\frac{P(B\cap C)}{P(C)}\\
&=16\alpha\\
P(A\cap B\,|\,C)&=\frac{P(A\cap B\cap C)}{P(C)}\\
&=\frac{4\alpha}{3}\\
P(\overline{B}\cap A\cap C)&=p_{010}\\
&=\frac{1}{8}-\alpha\\
P(\overline{B}\,|
 A\cap C)&=\frac{P(\overline{B}\cap A\cap C)}{P(A\cap C)}\\
&=1-8\alpha\ .
\end{align}
Since $\ \alpha\ $ can assume any value in the interval $\ \left(\frac{5}{144},\frac{5}{88}\right)\ $, these quantities are clearly not determined by those you've been given.


text:
Q: Setting where die() should be printed out Is it possible to place die(); on a specific place on the page?

A: die immediately ends procesing of the script. Any output from it will always be the last content the script outputs.

A: Yea, you can place die anywhere on a page since it will always be the last content the script outputs before it ends processing of the script.

A: You can put it anywhere in your code that you want.


text:
Q: JavaScript - неправильный вывод месяца Бодрого всем кодинга
Вопрос:
Почему time.getMonth() выдаёт цифру от предыдущего месяца?
И как это исправить?
time.getMonth()+1 делает конкатенацию, но не сложение.
A: простите за глупое предположение, но не пытаетесь ли вы месяцы считать с единицы? getMonth считает с нуля: январь это нулевой месяц, июнь — пятый, ноябрь десятый.


text:
Q: ExtJS 4, Issue in grid with selType: checkboxmodel, after first click scroll to top I have a grid with selType: 'checkboxmodel' but in IE there is an issue: after clicking on grid row (selecting it) page scroll to position that first row is on top.
Please, help.

A: Found a proper anwser
        Ext.override(Ext.selection.CheckboxModel, {
            onRowMouseDown: function (view, record, item, index, e) {
                //view.el.focus(); - commented focus()
                var me = this,
                    checker = e.getTarget('.' + Ext.baseCSSPrefix + 'grid-row-checker'),
                    mode;
                if (!me.allowRightMouseSelection(e)) {
                    return;
                }
                if (me.checkOnly && !checker) {
                    return;
                }
                if (checker) {
                    mode = me.getSelectionMode();
                    if (mode !== 'SINGLE') {
                        me.setSelectionMode('SIMPLE');
                    }
                    me.selectWithEvent(record, e);
                    me.setSelectionMode(mode);
                } else {
                    me.selectWithEvent(record, e);
                }
            }
        });

worked for me

A: Another solution which solves root cause of the problem for all scenarious and selection models:
Ext.override(Ext.dom.Element, {
    focus: function (defer, dom) {
        var me = this,
            scrollTop,
            body;

        dom = dom || me.dom;
        body = (dom.ownerDocument || DOC).body || DOC.body;
        try {
            if (Number(defer)) {
                Ext.defer(me.focus, defer, me, [null, dom]);
            } else {
                if (dom.tagName != 'DIV') {
                    if (dom.offsetHeight > Ext.dom.Element.getViewHeight()) {
                        scrollTop = body.scrollTop;
                    }
                    dom.focus();
                    if (scrollTop !== undefined) {
                        body.scrollTop = scrollTop;
                    }
                }
            }
        } catch (e) {
        }
        return me;
    }
});


text:
Q: How can I make Firefox annotate links which point to files such as PDFs, which won't be opened in Firefox? I want Firefox to scan every page, and for every Text element, I want Text to be replaced with Text [PDF] if URI point to a PDF file (similar to Google Scholar results).
This is because I have Firefox configured to open PDFs externally, and I am annoyed by the extra blank tab from attempting to open them in a new tab, and the popup dialogs are an unwelcome surprise.
If possible, I would like it to automatically do this for every file that is configured to be opened with an external application under Options -> Applications.
I don't need any advanced logic - just a simple regex match for \.(pdf|PDF)$ would suffice, but a smarter method would of course be even better. It would also be nice if it didn't append the [PDF] when it's already appended, such as on the Google Scholar page, to avoid redundancy.
Ideally I'm looking for a Firefox  extension.

A: You could use Greasemonkey and a user script. User scripts are scripts that you install in Firefox and that can run on any webpages to do things.
You could install for example:
http://userscripts.org/scripts/show/8615 - automatically adds icons to non html files (pdf and other):

You will need to install the Greasemonkey extension before installing a user script. (on the userscript site, go to "How do I use this?" under the "Install" link.)
There may be other scripts that only do pdf links.

A: Another option would be to edit your user agent style (.css), and add a rule that matches <a href="*.pdf" elements, and style them with a background of a pdf icon, or highlight them...


text:
Q: Magento - How to put Mageworx downloads block outside of magento? How to put Mageworx downloads block outside of magento?
For Example:
{{block type="downloads/link" id="5,6,7" title="Files"}}

A: Almost any Magento blocks can be programmed this way:
   <?php
    require_once('app/Mage.php'); // don't forget to replace app/Mage.php with the actual path to your Magento
    $mage = Mage::app();
    // create the block
    $block = $mage->getLayout()->createBlock('downloads/link', '', array('id' => '1,5,6,7', 'title' => 'Files'));
    // output the block
    echo $block->toHtml();

Please note that most likely you will face typical issues of such an  "ouside of Magento" output, such as absence of scripts, styles, images.
In this case, everything is connected in a similar way. All dependencies can be found in the corresponding layout.


text:
Q: MaxLength DataAnnontation not found I am trying to create a new Orchard CMS Module to mimic another MVC  project I built. I am using VS 2013 Express for both with the most recent Orchard v1.72.  I have a class that includes the using statement
using System.ComponentModel.DataAnnotations;
I have the following properties
    [MaxLength(16)]
    public virtual string Symbol { get; set; }

    [StringLength(16)]
    public virtual string SymbolSequence { get; set; }

    [StringLength(512)]
    public virtual string Notes { get; set; }

    public virtual double Begin { get; set; }

    public virtual double End { get; set; }

    [Range(0.01, int.MaxValue, ErrorMessage = "Please enter a value 0.01 or larger.")]
    public virtual double Increment { get; set; }

Is there any reason that the MaxLength annotation cannot be found while the StringLength and Range annotations are?
They all reside in the same System.ComponentModel.DataAnnotations namespace and there is no problem in the other project.
How can I fix it?
Edit  Retargeting for .NET 4.5 seems to have solved the problem

A: The MaxLength DataAnnotation was introduced in .NET Framework 4.5.
StringLength and Range were introduced in 3.5 SP1.


text:
Q: React Native - How to use excludedActivityTypes property in ActionSheetIOS options parameter? I am new to react native and i don't have any background in Objective-C or Swift. The documentation does not provide enough content to understand the use of excludedActivityTypes property. Documentation says:

excludedActivityTypes (array) - the activities to exclude from the
  ActionSheet

It takes array but i don't know what to mention in the array and what is the purpose of using this property. Can anyone tell its purpose and how to use it? A little example will be more appreciated. Thanks !!!

A: It's purpose is to remove some options from the list of available actions (like sharing to facebook/twitter or saving to camera roll)
So, in most of the cases you can simply skip it.
excludedActivityTypes: [
'com.apple.UIKit.activity.PostToFacebook',
'com.apple.UIKit.activity.PostToTwitter']

The list of possible exclusions you can find at Apple's developer documentation:
https://developer.apple.com/documentation/uikit/uiactivitytype
Find more info on this react-native component use here:
https://github.com/react-native-community/react-native-share/issues/153


text:
Q: I am trying to install a site that a larger organization sent me, where do I start? I have the zip file with everything in it, but there's just not a simple way to "run"? What all do I need? Do I need my own server or should they have their own?

A: No, there is no 'run'. Assuming your zip file includes a WordPress install and a database, then you'll need access to a web server and a MySQL installation. If you just want to run it on your own machine, you could install WAMP (if on Windows) or MAMP (for Macs) - these would give you all you need to get going. If you want to make this website live, however, you need a hosting company.
http://codex.wordpress.org/Installing_WordPress


text:
Q: Compile C++ code for AIX on Ubuntu? Question in one sentence: How can I compile code for AIX using G++ on Ubuntu? (Assuming it is possible)
I hope that it is as simple as adding an option to the make file to specify target processor.  I am a novice when it comes to most things compiler related.
Thank you in advance.

A: What you are looking for is a cross-compiling toolchain.
A toolchain includes a cross-compiler (a compiler that runs on the current platform but builds the binary code to run on another, on your case, AIX), the C or C++ library, and some other interesting tools.
I have successfully used buildroot in the past, which is a tool that automates the process of creating a cross-compiling toolchain. I know they support several target platforms, maybe AIX is among them.
If you want to compile your toolchain by hand, take a look at the Roll-your-own section on this page.
Another approach, probably easier on your case, would be to install a AIX system inside a virtual machine on Ubuntu. This way you would have access to a complete AIX system running inside your machine, giving the opportunity to develop and test your application under real conditions (or whatever reasons you may find interesting for doing such a thing).

A: You'll want to download the right version of g++ (i.e., one that generates code for POWER, or whatever you're running AIX on), and compile that to run under Ubuntu.

A: Try to compile with -maix32 or -maux64 (like g++ -m32 file.cxx), it it doesn't work it means that it's not supported by your compiller.


text:
Q: Java NullPointerException in ArrayList This simple piece of code removes any Statistic in an arrayList if its properties are null.  Unfortunately, I'm getting a java.lang.NullPointerException on the first line of the if Statement (if tempStat.serialName==null...).  Thoughts?
public static ArrayList<Statistic> removeEmptyStats(ArrayList<Statistic> al) {
    Statistic tempStat=new Statistic();
    for (int i=0; i<al.size(); i++) {
        tempStat=al.get(i);
        if (tempStat.serialName==null || tempStat.serialPublisher==null || tempStat.serialISSN==null || tempStat.serialOnlineISSN==null) {
            al.remove(i);
        }
    }
    return al;
}

A: You should not remove entries of a list on which you are doing a loop.
tempstat is null, because when doing for (int i=0; i<al.size(); i++), it stores the initial value of al.size().
Then when you are doing al.get(i) after having removed some values, you can have a i which is higher than the size of the list. (BTW, once you remove a value, it also mean that you will skip one in your list).
You'd to have to use an iterator and iterator.remove().
Iterator<Statistic> iterator = al.iterator();
while(iterator.hasNext()) {
    Statistic tempStat = iterator.next();
    if (tempStat.serialName==null || tempStat.serialPublisher==null || tempStat.serialISSN==null || tempStat.serialOnlineISSN==null) {
        iterator.remove();
    }
}

A: It must be because tempStat itself is null. However you need to be very careful with this.
Say you have 5 elements in your list element 2 is invalid so you remove it, element 3 has now dropped back to element 2, but you're going to move on to check element 3 next, however this is now the old element 4 (if that makes any sense!)

A: The variable tempStat is null! check the values contained in passed array al