text:
Q: Firebase limited service account I have a java client (Standalone app) that is using the Firebase Admin SDK, because I need to read values from the Realtime database whenever a value is changed. (A ValueChange listener is being used).
Currently I'm including the service-account.json in the app. Even if I set the roles to Viewer, using this service-account.json, I can create accounts usingFirebaseAuth.createCustomTokenAsync, which is something I dont want.
Is there a way to make a service-account with Realtime-database read only?
I know I can use setDatabaseAuthVariableOverride to "limit", but if someone extracts my service-account.json from the app/jar, they have the power to do everything..
I'm not using node.js, just Java with spring. And js firebase is a no, because I need to receive updates even without a web page.

A: Never distribute service accounts to end users.  They should only go to trusted parties.
There is currently no fine-grained way to control access to Realtime Database via service accounts.  Access control is performed via Firebase Authentication client libraries, which are not available for non-Android Java clients.


text:
Q: Is there any way to post on users behalf, and make it look like an actual post? We need to post a message from the user that looks like an actual status update, without anything giving away that is was made trough an app, no extra images or hyperlinks. We also want to "tag" a page in the post.
Is there any way this is possible without having the user to make the post themselves?

A: Publishing something via an App and making it look like the user posted it is not possible, users should always be able to block the app (and with that, the postings of the app). Also keep in mind that the "message" field always has to be user generated, so you are not allowed to use auto-generated content for publishing. After all, posting via an app only leaves a very small footprint, it just writes "via xxxxx" (App Name). The only serious way to post something is via the JavaScript SDK feed dialog anyway:

https://developers.facebook.com/docs/reference/dialogs/feed/

About tagging a page in a post, i am not sure. some months ago it was not possible.

https://developers.facebook.com/docs/reference/api/user/

Search for "Comma-separated list of Facebook IDs of people tagged in this Post" - i guess you can still only tag Users, but you can just try with a Page ID.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is struts 2 interceptor different from hibernate interceptor? I am having an application where struts2 and hibernate is used. For restricting users from accessing unauthorized pages. I tried implementing struts interceptor. But after mentioning interceptor tag in struts.xml file, httpsession object in my java pages started throwing java.lang.NullPointerException. I was wondering if I cannot use struts interceptor when hibernate is used? Or are there any thing called hibernate interceptor to achieve my objective.
Stacktrace
java.lang.NullPointerException
    at com.uac.dao.RoleDaoImpl.listRoles(RoleDaoImpl.java:308)
    at com.uac.biz.RoleAction.viewRoles(RoleAction.java:193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

Struts.xml
<interceptors>
     <interceptor name="authentication" class="com.uac.biz.AuthenticationInterceptor">  </interceptor>
    <interceptor-stack name="uac_auth">
        <interceptor-ref name="authentication" ></interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>
     </interceptor-stack>
</interceptors>......
......................
<action name="addUserRedirect" class="com.uac.biz.RoleAction" method="viewRoles">
    <interceptor-ref name="uac_auth" />
    <result name="success">/addUser.jsp</result>
</action>

piece of code using session object
roleList=new ArrayList();
System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXX-----enterd into listRoleeees");
//Criteria roles=session.createCriteria(RolePojo.class);
**Query query= session.createQuery(" from RolePojo");**
result=roles.list();
System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXX-----after seesion");
for(Iterator it=result.iterator();it.hasNext();){
RolePojo rolepojo=(RolePojo) it.next();
roleList.add(new Pojo(rolepojo.getRoleId(),rolepojo.getRoleName()));

A: You can certainly use Struts2 and Hibernate together. A Struts2 interceptor is a great way to handle the access security that you are looking for.
In the question linked below, I provided an answer that should give you a starting point for how to use an interceptor to provide this functionality.
Sessions in struts2 application
As for the NullPointerException you are encountering, you would need to provide the stack trace and code examples of your struts.xml the Java code where the NPE is occurring.

A: Finally we could resolve this. We found the solution from
http://www.mkyong.com/hibernate/hibernate-error-an-annotationconfiguration-instance-is-required-to-use/
Instead of @session, we created sessionfactory objects manually.
SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
Thanks to all.

A: You can try Servlet Filter to filter request URL


text:
Q: Avoid UITableViewCell updating content when scrolled I've found some similar questions already on SO, but nothing that seems to address this specific problem.
I'm using a UITableView with around 25 dynamic cells. Each cells contains a hidden UIProgressView. When the user taps on the download button within the cell to download that item, the UIProgressView is displayed and it indicates the progress of the download.
I've achieved this by assigning a tag to each cell which is equivalent to its corresponding downloadItemID. Each instance of MyCell has its own progressBar property.
This works fine as long as the table view is not scrolled during the download. It works also when the user is downloading multiple items at the same time. The code looks like this:
UIProgressView *theProgressBar;
for (MyCell *cell in self.tableView.visibleCells)
{
    if (cell.tag == downloadItemID) theProgressBar = cell.progressBar;
}

float progressPercentage = (float)completedResources / expectedResources;
[theProgressBar setProgress:progressPercentage animated:YES];

The problem is that when the user scrolls the table view, the cell and progress view are transferred to another cell. It's simple enough to reset and hide the progress view for the new cell, but when the original/downloading cell is scrolled back into view, no progress is visible.
I've tried caching active progress bars into a dictionary and reallocating them back to the original cell in cellForRowAtIndexPath, but this is giving me the same result: no visible progress after scrolling the cell off and on the screen. Even if I can get them to show up, I'm doubtful I can get this to work seamlessly by rolling my own caching method.
What I need is to keep cells in memory. But can I work around dequeueReusableCellWithIdentifier? This whole problem has arisen because I had to switch to a dynamic system of allocating the cells, but it is too dynamic. Can I create the cells dynamically, but keep them in memory all the time once created, or at least keep the ones that are currently downloading?
(I understand the reasons why cell reuse is the preferred way to go with table views.)

A: You are working against the framework. As vadian says in the comment, you need to separate the logic and state information from the cells and put them elsewhere.
Here is one way of doing it.

*

*Create a class to hold each download state, like a download ongoing flag, download progress, title, URL, etc.

*In your view controller, create and add all your download objects to an array when the view controller is created. The first object corresponds to the first row in the table.

*Whenever you dequeue a cell, populate it with data from the array. The NSIndexPath row property serves as the index into the array.

*All your updates (download progress) updates the download objects in the array, then update the cell content using the updated object. You can use UITableView cellForRowAtIndexPath to get the cell for a specific array index, if you get nil there is no need to update it.


text:
Q: Error loading native librarie libarrow_dataset_jni.dylib in Apache Arrow 7.0.0 Java Dataset API I got this error when I tried to run a simple Java program that uses the Dataset API available in version 7.0.0.
The error occurred when trying to get a NativeMemoryPool using the getDefault() method.
. . .
NativeMemoryPool nativeMemoryPool = NativeMemoryPool.getDefault();
FileSystemDatasetFactory factory = new FileSystemDatasetFactory(
        new RootAllocator(Long.MAX_VALUE), nativeMemoryPool, FileFormat.PARQUET, uri);
. . .

By the way, I installed all the binary libraries for my platform using the instructions available at https://arrow.apache.org/install/ and correctly assigned the property java.library.path in my Java Program. The fact is that the library libarrow_dataset_jni.dylib was not actually installed even though libarrow_dataset.700.dylib and several others were installed with the respective symlinks.


text:
Q: How do we know the Gamma function Γ(n) is ((n-1)!)? We know that
$$\Gamma(n) \equiv \int_0^{\infty}t^{n-1}e^{-t} \textrm{d}t = (n-1)!$$
But this just looks like another formula and I can't see why this would be equal to $(n-1)!$.
Is there a proof that
$$\Gamma(n)  = (n-1)!$$ ?
I'm not too familiar with the Gamma function. Any help is appreciated.

A: Let $\epsilon>0$ then integrating by parts for all $n \in \mathbb{N}^{*}$
$$
\int_{0}^{\epsilon}t^{n}e^{-t}\text{d}t=\left[-e^{-t}t^{n}\right]^{\epsilon}_{0}+\int_{0}^{\epsilon}nt^{n-1}e^{-t}\text{d}t
$$
And $\displaystyle -e^{-\epsilon}\epsilon^{n} \underset{\epsilon \rightarrow +\infty}{\rightarrow}0$ so when $\epsilon \rightarrow +\infty$ it becomes
$$
\Gamma\left(n+1\right)=n\Gamma\left(n\right)
$$
And
$$
\Gamma\left(1\right)=\int_{0}^{+\infty}e^{-t}\text{d}t=1
$$
With  $0!=1$ and $n!=n\left(n-1\right)!$ both expressions satisfies exactly the same induction relations. What is more interesting is that $\Gamma$ satisfies it for all $x \in \mathbb{R}^{*+}$.

A: Just to give another (non-rigorous) approach, if $|x|\lt1$, then, slipping an infinite sum inside the integral, we have
$$\sum_{n=0}^\infty{\Gamma(n+1)\over n!}x^n=\int_0^\infty\left(\sum_0^\infty{(tx)^n\over n!}\right)e^{-t}dt=\int_0^\infty e^{-t(1-x)}dt={1\over1-x}=\sum_{n=0}^\infty x^n$$
and so $\Gamma(n+1)/n!=1$ for all $n$.
To make this rigorous would require justifying two key steps: the interchange $\sum\int=\int\sum$, and the conclusion that $\sum a_nx^n=\sum b_nx^n$ for all $|x|\lt1$ implies $a_n=b_n$ for all $n$.

A: derivation from taken from flammable maths


text:
Q: Unable to render the JSON Object on browser in React.js I am trying to display a JSON object which is an array in React. I am able to write the React code for doing that. However, I am not able to see the output in my browser.
Here is my code:
import React, {Component} from 'react';
import data from '../articles';
export default class fetchData extends Component {
  showData = (inputValue) => {
    inputValue.forEach((temp) => {
      return (

 temp.article_id

      );
    });
  }
  render () {
    return (

 {this.showData(data)}

    );
  }
}

JSON object: (located in ../articles)
[
  {
    "article_id": "101",
    "org_id": "10001",
    "reported_by": "Srilakshmi",
    "reported_on": "11-16-2016",
    "author": "Sree",
    "language": "English",
    "src_url": "",
    "key_words": "CS, Programming",
    "status": "Draft",
    "channel_ids": "IOE1",
    "title": "CS 101 Lession",
    "description": "CS 101 First Lession",
    "file_on_disk": "",
    "publish_on": "",
    "Published_on": "",
    "contentArray": ""
  },
  {
    "article_id": "102",
    "org_id": "10001",
    "reported_by": "Srini",
    "reported_on": "11-16-2016",
    "author": "Srini",
    "language": "English",
    "src_url": "",
    "key_words": "CS, DB",
    "status": "Draft",
    "channel_ids": "IOE2",
    "title": "CS DB 101 Lession",
    "description": "CS DB 101 First Lession",
    "file_on_disk": "",
    "publish_on": "",
    "Published_on": "",
    "contentArray": ""
  }
]

Any help with getting the data to display would be highly appreciated.

A: 3 mistakes here...
First:

 temp.article_id
 won't print article ID. Use curly braces to print actual value

{ temp.article_id }

Second:
forEach array method just loops array, it does not create new one from values returned in callback. Use map method instead.
inputValue.map((temp) => {
    return (

 temp.article_id

    );
});

Third:
you are not returning from showData method at all.
Edit your code to return newly created array of components (that array created using map method)
showData = (inputValue) => {
    return inputValue.map((temp) => {
        return (

{ temp.article_id }

        );
    });
}

Bonus:
make it short using arrow functions
showData = (inputValue) =>
    inputValue.map(temp =>
{ temp.article_id }
)


text:
Q: Update in action create I have three models,auto, perfil, and user. Each user has their own profile. I need that when you publish a new Auto you can update your profile user if the data are different or change in time. But not as used to update the action in the action create. I use nested attributes.
 def create
         current_user.perfil||= current_user.build_perfil
         @perfil = current_user.perfil
         @perfil.update_attributes(auto_params)

         @auto = @current_user.autos.new(auto_params)
          respond_to do |format|
       if @auto.save
        format.html { redirect_to @auto, notice: 'Auto was successfully created.' }
        format.json { render :show, status: :created, location: @auto }
       else
         format.html { render :new }
         format.json { render json: @auto.errors, status: :unprocessable_entity }
      end
     end

A: I think what you ask is that whenever an "Auto" object is created, "User" profile should be updated if there is some change in the data and you don't want to update in the "Create" method of "AutoController"
What you can do is, in your "Auto" model
include ActiveModel::Dirty

and define a
after_commit :update_user_profile, on: :create

in your "Auto" model and in the callback function
def update_user_profile

prev_changes = self.previous_changes

end

Now using "prev_changes" you can check for appropriate changes and update "User" model accordingly.


text:
Q: Mount/Render a React component manually using JS I am trying to use the react-rails with the kaminari gem.
below piece of code is responsible for creating the Admins page with pagination, paginate being a kaminari method:
#app/views/dashboard/admins/_admins.html.erb

  <%= react_component 'Admins', {data: admins} %>

<%= paginate admins, :remote => true %>

on firing request with remote=true, this whole stuff is repainted, the response being generate through the following code:
#app/views/dashboard/admins/index.js.erb
<% if @admins.present? %>
$("#admin_wrapper").html("<%= escape_javascript(render partial: 'admins', locals: { admins: @admins } ) %>");
React.render("Admins", "#admins_component"); //How to make this work???
<% end %>

After the ajax request, the response is correctly generated and the ReactComponent is also being created in the HTML of the page as follows:

But the problem is that the component is not rendered/mounted. I tried mounting the component manually through console, but I am not sure if I was doing it correctly or not.
Moreover, the react extension in chrome displays the previous state of the Admin component, after the request for next page is fired:

Aim is to replace the html of the red-box below, on clicking the pagination link:
When I run Admin.prototype in console before/after clicking on the pagination link, I get the following output:

A: react-rails includes some helpers for mounting components based on data-react-class and data-react-props attributes. The gem uses these helpers for mounting components and you can call them yourself, too.
You should remove this line:
React.render("Admins", "#admins_component"); //How to make this work???

And replace it with:
// Find any divs with `data-react-class` and mount them
ReactRailsUJS.mountComponents()

It's ok to call that function anytime. Even if a component is already mounted, it will re-render it but not mess anything up!
You can see all of react-rails's helpers in the react_ujs* files here:
https://github.com/reactjs/react-rails/tree/master/lib/assets/javascripts


text:
Q: Is it correct to say "the said meeting"? Is it correct to use "the said meeting" as a way of referring to what people were told at the meaning?

A:
The word said can also be used as an adjective to refer to
  something that has been previously introduced. (vocabulary.com)

*

*Its use as an adjective comes mainly in legal and business writing.

In that vein, the word offers a reference to something that was mentioned earlier.

*

*The judge may tell you that if you can't provide said evidence,
your case will be dismissed. (That evidence was mentioned before).

It's essentially a briefer replacement of words like aforementioned
  and aforesaid. (grammarist.com)

In these examples, said serves no purpose and could be removed:

*

*The said location is set up on 2123 Rhode Island, a vacant lot.    [Property Magazine]

*Verizon will accept pre-orders for the iPhone 4 starting this    Thursday and will begin selling the said smart phone on February 10.
  [Top Tech Reviews]

In other cases, said could be replaced with the:

*

*For months we've heard rumour of a 'PlayStation Phone' being    released, and speculated with regards to what the specs and capabilities of said phone would be. [Kotaku]

*Celebrity bloggers … love to post the latest scandalous photos of    stars then ridicule said celebrities for being fame whores. [Creative
  Loafing Tampa]

A: The word "said" in "the said X" is a noun-modifier that specifies what kind of "X" it is referring to, namely "the X that has been mentioned". So in official documents "said" is often used to avoid having to repeat the specification. It usually can be omitted without any ambiguity.
It is unlikely that an official document would use the phrase "the said meeting" incorrectly, so it is likely that you misunderstood.

A: You might come across something like:
"The third annual meeting of The Exalted Poobahs of the Order of the Sighing Buffalo took place last Thursday. Said meeting was held in the Grand Ballroom of the Podunk Marriott."
In this case, "said" is used to avoid having to say, "The third annual meeting of The Exalted Poobahs of the Order of the Sighing Buffalo," again.
The definite article (the) is not required, as said is taking it's place.


text:
Q: Is there an algorithm to calculate a numerical rating of the degree of abstractness of a word in NLP? Is there an algorithm that can automatically calculate a numerical rating of the degree of abstractness of a word. For example, the algorithm rates purvey as 1, donut as 0, and immodestly as 0.5 ..(these are example values)
Abstract words in the sense words that refer to ideas and concepts that are distant from immediate perception, such as economics, calculating, and disputable. Other side Concrete words refer to things, events, and properties that we can perceive directly with our senses, such as trees, walking, and red.

A: There's no definition of abstractness that I know of, neither any algorithm to calculate it.
However, there are several directions I would use as proxies

*

*Frequency - Abstract concepts are likely to be pretty rare in a common speech, so a simple idf should help identify rare words.

*Etymology - Common words in English, are usually decedent from Germanic origin, while more technical words are usually borrowed from French / Latin.

*Supervised learning - If you have Wikipedia articles you find abstract, then the common phrases or word would probably also describe similar abstract concepts. Training a classifier can be a way to score.
There's no ground truth as to what is abstract, and what is concrete, especially if you try to quantify it.
I suggest aggregating these proxies to a metric you find useful for your needs.


text:
Q: Handling Display URLs and actual URLs with Linkify I am trying to find the best way to implement the following:

*

*A normal URL would look like
https://www.google.com/something/somethingmore/a_lot_more_stuff.html

*I'd like to display this as google.com/... in my TextView (for better readability)

*When user clicks on google.com/... in the TextView, the actual long
URL should be used automatically for further action
Assuming that I have both the display URL as well as the actual URL with me, how can I use Linkify (or any other technique) to ensure that a very long URL can be displayed in a short fashion, yet when the user clicks on the Linkified URL, the actual long URL is used?


text:
Q: Maximum length of string preg_match_all can match and acquire? I'm trying to parse some web pages with preg_match_all() and some of them are quite large as several MBs in size. And one of the regular expressions matches some text strings that are so large that they don't seem to be able to match and acquire them. It simply returns an empty string.
One of the strings is 1.32MB or 1,393,557 bytes when I manually selected it and saved it as a .txt file.
When the string is much shorter as just tens of thousands of bytes, that regular expression successfully matches and acquires it.
So my question is, as it occurs to me there's a limit / maximum length of string preg_match_all() can match, what is it and how can I set it larger?

A: Set the ini_set('pcre.backtrack_limit', '1048576'); to whatever you want in your script or on your php.ini file for global use. (example is 1mb)
Credit to: http://www.karlrixon.co.uk/writing/php-regular-expression-fails-silently-on-long-strings/

A: I tried increasing 'pcre.backtrack_limit' and 'pcre.recursion_limit' but neither of these solved my problem. In my case, the solution was to avoid backtracking altogether by using the possessive quantifier +.
The section on Quantifiers in The Stack Overflow Regular Expressions FAQ may be helpful if anybody else stumbles onto this.


text:
Q: In AutoMapper how does one project from an abstract base class to an interface I am trying to map a number of entities that come from EF Core backed by CosmosDB to an equivalent set of concrete types that implement an interface. For simplicity, In the example below I have just stripped it down to a List<T>.
When I run my code I get an exception about IAccount not having a default constructor.

`IAccount' does not have a default constructor (Parameter 'type')'

The error happens at var query = mapper.ProjectTo<IAccount>(repo);.  I have tried every combination of configuration that I can think of but I am stuck.
My current version is as follows, which is stripped down from my original classes.  This is why AccountBase exists, which isn't obvious from the example.
Source Types
public abstract class AccountEntity
{
    public Guid Id { get; set; }
    public abstract string Name { get; set; }
}

public class UserEntity : AccountEntity
{
    public string Username { get; set; } = null!;
    public string Email { get; set; } = null!;
    public string FirstName { get; set; } = null!;
    public string LastName { get; set; } = null!;
    public override string Name { get; set; } = null!;
}

public class OrganizationEntity : AccountEntity
{
    public override string Name { get; set; } = null!;
    public IEnumerable<string> Industries { get; set; } = null!;
    public string? Website { get; set; }
}

Destination Types
public interface IAccount
{
    Guid Id { get; }
    string Name { get; }
}

public abstract class AccountBase : IAccount
{
    public Guid Id { get; set; }
    public string Name { get; set; } = null!;
}

public class User : AccountBase
{
    public string Username { get; set; } = null!;
    public string Email { get; set; } = null!;
    public string FirstName { get; set; } = null!;
    public string LastName { get; set; } = null!;
}

public class Organization : AccountBase
{
    public IEnumerable<string> Industries { get; } = null!;
    public string? Website { get; set; }
}

Test
var config = new MapperConfiguration(c =>
{
    c.CreateMap<AccountEntity, IAccount>()
        .IncludeAllDerived();

    c.CreateMap<UserEntity, IAccount>()
        .As<User>();

    c.CreateMap<UserEntity, User>();

    c.CreateMap<OrganizationEntity, IAccount>()
        .As<Organization>();

    c.CreateMap<OrganizationEntity, Organization>();
});

config.AssertConfigurationIsValid();

var mapper = config.CreateMapper();

var repo = new List<AccountEntity>()
{
    new UserEntity()
    {
        Id = Guid.NewGuid(),
        FirstName = "First",
        LastName = "User"
    },
    new OrganizationEntity()
    {
        Id = Guid.NewGuid(),
        Industries = new [] { "SPACETRAVEL" },
        Name = "Org 1"
    }
}.AsQueryable();

var queryProjection = mapper.ProjectTo<IAccount>(repo);
var results = queryProjection.ToList();

My goal is to get an Organization when OrganizationEntity is encountered and likewise an User for an UserEntity.
I have tried .DisableCtorValidation() and .ConvertUsing() but those don't help in my testing.

A: Based on the response from github issue 3293, it appears not to be possible.  Though it feels like it should be because the underlying provider, at least in my case the CosmosDB provider, does support inheritance via a Discriminator.
Maybe AutoMapper will improve to support this but for now I need to figure out a workaround...
I'll gladly still take suggestions :)


text:
Q: Regex - lookahead assertion I have problem with lookahead assertion (?=). For example, I have expression:
/Win(?=2000)/

It match Win, if expression is like Win2000, Win2000fgF. I have next expression:
^(?=.*\d)(?=.*[a-z]).*$

It match for digit and lower case letter, for example: 45dF, 4Dd. But I don't know, why it works and match all characters :) I haven't characters, which are before (?=.*\d). I think, only this expression should work:
^.\*(?=.*\d)(?=.*[a-z]).*$

(with \* before expression).
Could you explain it?

A: lookaheads don't match, they assert.
this means that if you use a lookahead, you need something that will match what you want if you want to go any further.

A: Let's say we are the regex engine and apply the regex ^(?=.*\d)(?=.*[a-z]).*$ to the string 2a.
Starting at position 0 (before the first character):

*

*^: Make sure we're at the start of the string: OK

*(?=: Let's check if the following regex could match...

*.*: match any number of characters -> 2a. OK.

*\d: Nope, we're already at the end. Let's go back one character: a --> No, doesn't match. Go back another one: 2 --> MATCH!

*): End of lookahead, match successful. We're still at position 0!

*(?=: Let's check if the following regex could match...

*.*: match any number of characters -> 2a. OK.

*[a-z]: Nope, we're already at the end. Let's go back one character: a --> MATCH!

*):  End of lookahead, match successful. We're still at position 0!

*.*: match any number of characters -> 2a --> MATCH!

*$: Let's see - are we at the end of the string? Yes, we are! --> MATCH!

*Hey, we've reached the end of the regex. Great. Match completed!


text:
Q: I want to read a string with multiple names and match them with names in a list Python In Python I receive a string of surnames and last names so for instance "Jmes Mai, Richard Hammond  Jrmy Clarkson". These are user input so I cannot verify if they will be separated with a comma or spelled correctly. Users can also fill in as many names as they want. Furthermore I have a list with +- 200 names in it of people the user can pick.
What I want to do now is make a list of these names from the large list that are the best match with the user picked names. So in the above example, I want the output to be [James May, Richard Hammond, Jeremy Clarkson] (Given that these exist in the large list of names.)
So far I have tried cutting the string in all possible substrings. and using the process.extract from the fuzzywuzzy package to brute force this problem in a way where all the substrings are matched and put in a list. After this duplicates are removed. The problem with this is it gives a lot of false positives and takes a really long time so I was wondering if there was a better way to do it.
Thank you in advance!
def match_names(s):
    lst = []
    for name in names:
        for tup in process.extract(name.lower(), options(s)):
            if tup[1] > 95:
                if name not in lst:
                    lst.append(name)
    return lst

A: Try using difflib library and import get_close_matches as followed :
from difflib import get_close_matches
for i, j in zip(len(name), len(lst)):
    if len(get_close_matches(name,lst[i])>0):
        'Do what ever you wish here'


text:
Q: uiwebview open tag img Tell me please, I have an article that is introduced into the UIWebView. It has pictures, they are small and hard to see, I want to open by clicking the image at full size, so you can scale it and consider the details. At first I thought there need a JS module, but I was told that there are delegates from UIWebView. I can not find anything like it. Tell me what they are called, and please give an example.
Here's an example, when you click on the picture, it opens in full, and we can share the it.


text:
Q: two edit text with independent text I have a custom keyboard, and two EditTexts. I input number in the first edit text and then send focus to second edit text and get it back to the first edit text. My problem is that I can not write in the second edit text independently from the first edit text. Here is my code:
private class BtnListener implements OnClickListener {

    public void onClick(View view) {

        switch (view.getId()) {

        case R.id.btnNum0Id:
        case R.id.btnNum1Id:
        case R.id.btnNum2Id:
        case R.id.btnNum3Id:
        case R.id.btnNum4Id:
        case R.id.btnNum5Id:
        case R.id.btnNum6Id:
        case R.id.btnNum7Id:
        case R.id.btnNum8Id:
        case R.id.btnNum9Id:

            String inDigit = ((Button) view).getText().toString();

            if (inStr.equals("0")) {

                inStr = inDigit;

              } else {
                inStr += inDigit;
              }

            editX.setText(inStr);

            editX.addTextChangedListener(new TextWatcher() {

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Para Numero
                    if(editY.requestFocus() == true && editY.length() == 0 )
                    {
                        btnCalcula.setOnClickListener( new OnClickListener(){
                            public void onClick(View arg0){

                                int inNum = Integer.parseInt(inStr);

                                inStr = "0";

                                if (lastOperator == ' ') {
                                  result = inNum;//Asignacion de suma
                                  } else if (lastOperator == '+') {
                                      result += inNum; //Suma
                                      }

                                editZ.setText(String.valueOf(result).substring
                                        (0,editX.getText().length()-2));
                                mData.add(new Data(result));
                                mAdapter.notifyDataSetChanged();
                                lastOperator = '+';

                                    }
                                });
                    }

                }

                public void afterTextChanged(Editable s) {
                    //Para Pale
                    if(s.length() == 4 && editY.requestFocus() == true ){
                        btnCalcula.setOnClickListener( new OnClickListener() {
                            public void onClick(View v){
                                        if(editY.requestFocus() == true)
                                        {
                                            int inNum = Integer.parseInt(inStr);

                                            inStr = "0";

                                            if (lastOperator == ' ') {
                                              result = inNum;//Asignacion de suma
                                              } else if (lastOperator == '+') {
                                                  result += inNum; //Suma
                                                  }

                                            editZ.setText(String.valueOf(result).substring
                                                    (0,editY.getText().length()));
                                            mData.add(new Data(result));
                                            mAdapter.notifyDataSetChanged();
                                            lastOperator = '+';
                                            editY.clearFocus();
                                        }
                                    }
                            });
                        //para Tripleta
                    }else if (s.length() == 6){
                        btnCalcula.setOnClickListener( new OnClickListener() {
                            public void onClick(View v){
                                //editY.requestFocus();
                                        if(editY.requestFocus() == true)
                                        {
                                            int inNum = Integer.parseInt(inStr);

                                            inStr = "0";

                                            if (lastOperator == ' ') {
                                              result = inNum;//Asignacion de suma
                                              } else if (lastOperator == '+') {
                                                  result += inNum; //Suma
                                                  }

                                            editZ.setText(String.valueOf(result).substring
                                                    (0,editY.getText().length()));
                                            mData.add(new Data(result));
                                            mAdapter.notifyDataSetChanged();
                                            lastOperator = '+';
                                            editY.clearFocus();
                                        }
                                    }
                            });
                    }

                }

            });

                if (lastOperator == '=') {
                   result = 0;
                   lastOperator = ' ';
                }

              break;

           case R.id.btnClearId:
             result = 0;
             inStr = "0";
             lastOperator = ' ';
             editZ.setText("");
             editX.setText("");
             editY.setText("");
             mData.clear();
             mAdapter.notifyDataSetChanged();

              break;
           case R.id.btnAnula:
               editX.setText("");
               editY.setText("");
               editY.clearFocus();
               break;
           case R.id.btnImprim:
               //Buscar Api
               break;
           case R.id.btnReimp:
               //Reimplementar api
               break;
           }
        }

}


text:
Q: How to define "minimum" distance Constraint in IOS for multiple UIVIews Well i have 3 views like these:

I need to define a Constraint so on either Blue or Mustard vertical resizing, the Red view will remain at minimum distance of either upper view, like

Or

So how can i achieve that result???

A: Establish inequality vertical space constraints from both upper views to the red view:

*

*The vertical space from the mustard view to the red view is >= 8 points (or some other arbitrary space)

*The vertical space from the blue view to the red view is likewise >= 8 points

In addition, you may need a low-priority constraint that tries to keep the red view at the top of the superview, so that it doesn't pick some arbitrary point well below both views to occupy.


text:
Q: Converting Java code to Objective-C with J2Objc I'm trying to convert the Compression Scheme for Unicode implementation in Java to Objective-C using J2Objc. I have successfully downloaded and compiled J2Objc and run the command ./j2objec /SCSU/*.java after making sure that the Java code compiles. Nevertheless, I'm getting a huge block of error mostly saying that some classes, variables and functions are undefined:
error: SCSU/Compress.java:41: SCSU cannot be resolved to a type
error: SCSU/Compress.java:63: The method getCurrentWindow() is undefined for the type Compress
error: SCSU/Compress.java:77: The method selectWindow(int) is undefined for the type Compress
error: SCSU/Compress.java:105: EndOfOutputException cannot be resolved to a type
error: SCSU/Compress.java:105: EndOfInputException cannot be resolved to a type
error: SCSU/Compress.java:105: IllegalInputException cannot be resolved to a type
error: SCSU/Compress.java:107: The method getCurrentWindow() is undefined for the type Compress
error: SCSU/Compress.java:126: IllegalInputException cannot be resolved to a type
error: SCSU/Compress.java:134: EndOfInputException cannot be resolved to a type
error: SCSU/Compress.java:143: IllegalInputException cannot be resolved to a type
error: SCSU/Compress.java:165: SQ0 cannot be resolved to a variable
error: SCSU/Compress.java:171: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:171: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:173: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:181: EndOfOutputException cannot be resolved to a type
error: SCSU/Compress.java:216: EndOfOutputException cannot be resolved to a type
error: SCSU/Compress.java:218: Debug cannot be resolved
error: SCSU/Compress.java:219: The method getCurrentWindow() is undefined for the type Compress
error: SCSU/Compress.java:224: EndOfOutputException cannot be resolved to a type
error: SCSU/Compress.java:228: SQ0 cannot be resolved to a variable
error: SCSU/Compress.java:231: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:231: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:233: dynamicOffset cannot be resolved to a variable
error: SCSU/Compress.java:238: staticOffset cannot be resolved to a variable
error: SCSU/Compress.java:238: staticOffset cannot be resolved to a variable
error: SCSU/Compress.java:240: staticOffset cannot be resolved to a variable
error: SCSU/Compress.java:245: Assert cannot be resolved to a type
error: SCSU/Compress.java:249: Debug cannot be resolved
error: SCSU/Compress.java:266: EndOfOutputException cannot be resolved to a type
error: SCSU/Compress.java:279: The method isCompressible(char) is undefined for the type Compress

And the log goes on... Why am I getting such errors and what should I do to resolve them?

A: You need to specify the directory where the sources are in the -sourcepath (j2objc uses the Eclipse compiler as its front-end, which is where this requirement comes from). I copied those source files to ~/Downloads/unicode, and used this command:
$ j2objc -d build -sourcepath ~/Downloads/unicode ~/Downloads/unicode/*.java
translating /Users/tball/Downloads/unicode/Assert.java
translating /Users/tball/Downloads/unicode/Compress.java
translating /Users/tball/Downloads/unicode/CompressMain.java
translating /Users/tball/Downloads/unicode/Debug.java
translating /Users/tball/Downloads/unicode/Display.java
translating /Users/tball/Downloads/unicode/EndOfInputException.java
translating /Users/tball/Downloads/unicode/EndOfOutputException.java
translating /Users/tball/Downloads/unicode/Expand.java
translating /Users/tball/Downloads/unicode/IllegalInputException.java
error: /Users/tball/Downloads/unicode/SCSU.java:241: The method reset in type SCSU can only set one of public / protected / private

That's a weird error at the end, but looking at the source found it's indeed illegal Java:
SCSU.java:241:
protected public void reset()
    {
...

Fix that (remove either modifier), and you should be good to go.


text: Q: Diagonalizing operator over $L^2(\mathbb{T})$ I've been asked to diagonalise an operator on $L^2(\mathbb{T})$, given by $Tf(z) = f(z^{-1}$). I know that I'm expected to find a $U$ such that $TU = UM_f$, where $M_f$ is the multiplication operator, however I can't seem to construct the $U$ that does this. Could anyone provide any hints?


text:
Q: How to get Auth Token of Azure to create azure resources programmatically I want to create azure resources but I am having an issue while generating the token credential for creating such resources.
The following is the way to create azure postgres SQL but I need to Pass the credentials
But I don't know how to generate that token programitaillcay.
I need help for this.
const msRestAzure = require('ms-rest-azure');
const PostgreSQLManagementClient = require('azure-arm-postgresql');

const subscriptionID = '<subscription id>';
const resourceGroup = '<resource group name>';
const serverName = '<server name>'; // must be globally unique

msRestAzure.interactiveLogin().then((credentials) => {
  let client = new PostgreSQLManagementClient(credentials, subscriptionID);
  return client.servers.createOrUpdate(resourceGroup, serverName, {
    location: 'eastus',
    properties: {
      createMode: 'Default',
      administratorLogin: 'postgres',
      administratorLoginPassword: 'F00Bar!!'
    }
  });
}).then((server) => {
  console.log('Server:');
  console.dir(server, {depth: null, colors: true});
}).catch((err) => {
  console.log('An error ocurred');
  console.dir(err, {depth: null, colors: true});
});

Does anyone know how to generate it? and using what?  It's a signed token I guess using Client Id and tenant ID But how to generate it.
There's no documentation provided to generate it programitially. Is there any way?

A: interactiveLogin() will provide a link and a code that will allow the user to authenticate from a browser.
When using the Node.js SDK programmatically, there are 2 methods.
1)You could use your username and password to authenticate with the API using your Azure account. It's not recommended because it requires a very high degree of trust in the application, and carries risks which are not present in other flows.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');

MsRest.loginWithUsernamePassword(process.env.AZURE_USERNAME, process.env.AZURE_PASSWORD, (err, credentials) => {
  if (err) throw err;

  let client = new PostgreSQLManagementClient(credentials, subscriptionID);

  // ...
});

2)You may want to use service principal authentication rather than providing your account credentials. It is based on service principal without user account. First, create service principal in Azure portal.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');

MsRest.loginWithServicePrincipalSecret(
  'clientId/appId',
  'client-secret',
  'tenantId',
  (err, credentials) => {
    if (err) throw err

    let client = new PostgreSQLManagementClient(credentials, subscriptionID);

    // ...
  }
);

For more detail about JavaScript authentication samples using ms-rest-azure library, see here.

Update:
If using service principal, try to add Azure OSSRDBMS Database application permission. Navigate to Azure AD > your app > API permission. And remember to grant admin consent for your tenant.


text:
Q: WCF Service passing a filepath In my WCF I accept a parameter Filepath
I.e.
F:\BatchFiles\InputFile\SampeFile_Tabbed_WithNull.txt (This file 100% exists)
And I have this check then
public BatchSplitterResponse SplitFile(BatchSplitterRequest request)
        {
            //Retrieve File
            var response = new BatchSplitterResponse();
            if (request != null)
            {
                var filePath = request.FilePath;
                var numberOfRecordsPerFile = request.NumberOfRecordsPerFile;

                if (File.Exists(filePath))
                {..
}

When I add my WCF as a service reference to my console application and call my WCF service I keep getting an error that the file does not exist..
var linkService = new BatchSplitterClient("BasicHttpBinding_IBatchSplitter");
var response = linkService.SplitFile(new BatchSplitterRequest(){FilePath = @"F:\BatchFiles\InputFile\SampeFile_Tabbed_WithNull.txt",NumberOfRecordsPerFile = 1000});

Am I missing something ?

A: The user that is running your WCF service probably doesn't have access to the the "F:\" drive. This could be because it is a mounted drive or some missing/incorrect permission.

A: Your problem my be in the applicationpool identity.
You need to set up your applicationpool to "ApplicationPoolIdentity"
Here is a link that explains a bit more about the subject.
http://www.iis.net/learn/manage/configuring-security/application-pool-identities


text:
Q: Angular 2 Ngrx Store: Updating Array I currently have an angular2 CRM app based on ngrx/store architecture.  I have the CRUD functions for updating, listing and adding customers working fine and all tied up to Firebase Database using ngrx/effects.
To keep the smart component in sync with the store i have the following code.  Again all working fine, however i am unsure about how to update an array in the form - see code below: -
This is where i update the form with the data from the store
if (this.customer) {

          this.customerForm.get('name').setValue(this.customer.name);
          this.customerForm.get('overview').setValue(this.customer.overview);
          this.customerForm.get('imagePath').setValue(this.customer.imagePath);

          console.log("ngOnChanges", this.customer);

        }

I want to do a similar thing with address form but unsure how to do the above to populate the array object in the form.  Any ideas / suggestions welcome
When i log the console below i actually have the address details just need to know how to get them into the form object.
Object
addresses: Array(2)
0:Object
1:Object
length:2
imagePath:"http://www.bytes.co.uk/application/themes/bytes/img/bytes-technology-group.svg"
name:"Bytes Technology Group Emirates LLC"
overview:"Kronos Re-Seller for the Middle East and GCC Countries and Egypt"
parentId:"-KcRRsAGRYASXNU3gO_F"

Full Customer Detail Smart Component
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, OnChanges } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from "@angular/forms";

// Mojito Models
import { CustomerModel } from '../../models/customer-model';
import { AddressType } from '../../../shared/models/address.model';

@Component({
  selector: 'mj-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomerDetailComponent implements OnInit, OnChanges {

  @Input() customer: CustomerModel;
  @Output() updatedCustomer: EventEmitter<CustomerModel> = new EventEmitter<CustomerModel>();
  @Output() showView: EventEmitter<string> = new EventEmitter<string>();
  @Output() customerId: EventEmitter<string> = new EventEmitter<string>();

  customerForm: FormGroup;
  addressForm: FormGroup;

  addressTypes: AddressType[] = [
    { "id": 1, "name": "Work" },
    { "id": 2, "name": "Home" },
  ]

  private newAddressGroup() {
    return new FormGroup({
      type: new FormControl,
      street: new FormControl,
      city: new FormControl,
      country: new FormControl,
      postalCode: new FormControl
    })
  }

  get addresses() {
    return (this.addressForm.get('addressGroups') as FormArray).controls;
  }

  constructor(private fb: FormBuilder) {

    this.customerForm = this.fb.group({
      name: [null, Validators.required],
      overview: [null, Validators.required],
      imagePath: [null, Validators.required],
    });

    this.addressForm = this.fb.group({
      addressGroups: this.fb.array([])
    });
  }

  ngOnChanges() {

    if (this.customer) {

      this.customerForm.get('name').setValue(this.customer.name);
      this.customerForm.get('overview').setValue(this.customer.overview);
      this.customerForm.get('imagePath').setValue(this.customer.imagePath);

      console.log("ngOnChanges", this.customer);

    }

  }

  ngOnInit() {

  }

  onAddAddressGroup() {
    const fa = this.addressForm.controls["addressGroups"] as FormArray;

    fa.push(this.newAddressGroup());

  }

  onSaveAddress() {
    const addresses = this.addressForm.controls["addressGroups"].value;
    this.customer.addresses = addresses;
    this.onSaveCustomer();
  }

  onSaveCustomer() {

    this.customer = Object.assign(this.customer, this.customerForm.value);
    this.updatedCustomer.emit(this.customer);
    this.showView.emit('list');

  }

  onDeleteCustomer() {

    this.customerId.emit(this.customer.$key);
    this.showView.emit('list');

  }

  goBack() {

    this.showView.emit('list');

  }

}

A: You can set the values by iterating the data you have in customer.addresses and by the way, you can shorten the setting of values, instead of setting each value separate, you can make it shorter like:
ngOnChanges() {
  if (this.customer) {
    // set values in customerForm
    this.customerForm.setValue({
      name: this.customer.name,
      overview: this.customer.overview;
      imagePath: this.customer.imagePath
    })
    // set controls to addressForm, formArray
    let control = <FormArray>this.addressForm.get('addressGroups');
    this.customer.addresses.forEach(x => {
       control.push(this.fb.group({...}))
    })
  }
}

Notice the this.fb.group({...}) I'm not sure what form controls you have there, so you need to append them... Something like:
this.fb.group({myFormControlName1: x.myProperty1, myFormControlName2: x.myProperty2....})


text:
Q: Golang - How to display modules version from inside of code I'm writing two binaries, and both of them use two libraries (we can call them libA and libB).
Each lib is in a dedicated git repo, with git-tags to declare versions.
For example, libA is at v1.0.9 and libB is v0.0.12.
Both binaries have CLI flags, and I would like to add a debug flag to display lib versions like that:
> ./prog -d
Used libraries:
- libA, v1.0.9
- libB, v0.0.12

I don't know how to do that.
The only way I see to set variable from "outside" is to use ldflags (go build -ldflags="-X 'main.Version=v1.0.0'" for example). But this way don't seems scalable, how to add a libC? It also imply to manage tags two times, one time for git, and one time in goreleaser.yml or makefile.
Can you help me to find a solution?

A: The Go tool includes module and dependency information in the executable binary. You may use runtime/debug.ReadBuildInfo() to acquire it. It returns you a list of dependencies, including module path and version. Each module / dependency is described by a value of type debug.Module which contains these info:
type Module struct {
    Path    string  // module path
    Version string  // module version
    Sum     string  // checksum
    Replace *Module // replaced by this module
}

For example:
package main

import (
    "fmt"
    "log"
    "runtime/debug"

    "github.com/icza/bitio"
)

func main() {
    _ = bitio.NewReader
    bi, ok := debug.ReadBuildInfo()
    if !ok {
        log.Printf("Failed to read build info")
        return
    }

    for _, dep := range bi.Deps {
        fmt.Printf("Dep: %+v\n", dep)
    }
}

This outputs (try it on the Go Playground):
Dep: &{Path:github.com/icza/bitio Version:v1.0.0 Sum:h1:squ/m1SHyFeCA6+6Gyol1AxV9nmPPlJFT8c2vKdj3U8= Replace:<nil>}

Also see related question: How to get Go detailed build logs, with all used packages in GOPATH and "go module" mode?


text:
Q: Value from database is not being read Using EntityFramework 6.2.0
My model looks like:
<Table("Invoice_Totals")>
Public Class Invoice

    <Key>
    <Column("Invoice_Number")>
    Public Property IntegrationKey As Int64

    <Column("CustNum")>
    Public Property CustomerKey As String = String.Empty

    <Column("DateTime")>
    Public ReadOnly Property CreatedTime As DateTime

    <Column("Grand_Total")>
    Public Property Price As Decimal = Decimal.MaxValue

    <Column("Amt_Tendered")>
    Public Property Payment As Decimal = 0

    <Column("Amt_Change")>
    Public Property PaymentChange As Decimal = 0

End Class

This query:
Using database As PosModels.PosDatabase = PosModels.PosDatabase.CreateWithNoProxies
    Dim q As IQueryable(Of PosModels.Invoice) = database.Invoices
    posInvoices = q.ToList
End Using

produces this SQL:
SELECT
    [Extent1].[Invoice_Number] AS [Invoice_Number],
    [Extent1].[CustNum] AS [CustNum],
    [Extent1].[Grand_Total] AS [Grand_Total],
    [Extent1].[Amt_Tendered] AS [Amt_Tendered],
    [Extent1].[Amt_Change] AS [Amt_Change]
    FROM [dbo].[Invoice_Totals] AS [Extent1]

As you can see, the column [DateTime] is not included in the query.  I assume because "DateTime" is a SQL keyword/data type.  Is there any way to get EF to perform this query correctly?
Even when performing the query "manually" the object mapper does not appear to kick in:
posInvoices = database.Database.SqlQuery(Of PosModels.Invoice)($"
                SELECT
                    [Extent1].[Invoice_Number] AS [IntegrationKey],
                    [Extent1].[CustNum] AS [CustomerKey],
                    [Extent1].[DateTime] AS [CreatedTime],
                    [Extent1].[Grand_Total] AS [Price],
                    [Extent1].[Amt_Tendered] AS [Payment],
                    [Extent1].[Amt_Change] AS [PaymentChange]
                    FROM [dbo].[Invoice_Totals] AS [Extent1]
            ").ToList

This still does not fill in any values for the CreatedTime property.  As in the previous query, all values in the model remain at DateTime.MinValue.  The oldest data in the database is from 2011.

A: You've declared that as a ReadOnly property
 Public ReadOnly Property CreatedTime As DateTime

Which means that only a constructor can set it.  EF Core supports Backing Fields, which can be used to implement Read Only properties.  But in EF6 all Properties mapping to database columns must be read/write.


text:
Q: In emacs's perspective mode is there a way to preserve multiple locations in a single buffer when switching perspectives? I have been using perspective mode for some time, and on the whole it is excellent. However if you have a single buffer open in multiple windows and switch perspectives, when you change back each window shows the same location in the buffer. Is it possible to preserve the different locations when switching perspectives?
Thanks in advance.

A: If anyone else is curious, using clone-indirect-buffer rather than simply splitting the frame seems to do exactly what I want.


text:
Q: File move to another folder laravel I need the last 7 days' storage logs to move a new folder. But, I can't move them and got this error.

rename(/var/www/html/eMarketing/storage/logs/old-log-2020-02-27,/var/www/html/eMarketing/storage/logs/laravel-2020-02-27.log): Not a directory

My Code is here
public function logs()
{
  $today = \Carbon\Carbon::today()->format('Y-m-d');
  $days  = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');

  $newDirectoryPath = storage_path('logs/old-log-'.$days);
  if (!\File::isDirectory($newDirectoryPath)) {
      \File::makeDirectory($newDirectoryPath);
  }

  $path = storage_path('logs/');
  $allFiles = \File::allFiles($path);

  foreach($allFiles as $files) {
      $file = pathinfo($files);
      $logDay = str_replace('laravel-','', $file['filename']);

      if ($logDay >= $days && $logDay < $today) {
          \File::move($newDirectoryPath, $path.$file['basename']);
      }

   }
}

A: Problem
The problem is, you don't have files to move.
$newDirectoryPath = storage_path('logs/old-log-' . $days);

if (!\File::isDirectory($newDirectoryPath)) {
    \File::makeDirectory($newDirectoryPath);
}

The move() method may be used to rename or move an existing file to a new location. But
$newDirectoryPath is a folder not a file.

Solution
You need to change :
\File::move(
    $path . $file['basename'],                  // old file
    $newDirectoryPath . '/' . $file['basename'] // new file
);

public function logs()
{
    $today = \Carbon\Carbon::today()->format('Y-m-d');
    $days  = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');

    $newDirectoryPath = storage_path('logs/old-log-' . $days);
    if (!\File::isDirectory($newDirectoryPath)) {
        \File::makeDirectory($newDirectoryPath);
    }

    $path     = storage_path('logs/');
    $allFiles = \File::allFiles($path);

    foreach ($allFiles as $files) {
        $file   = pathinfo($files);
        $logDay = str_replace('laravel-', '', $file['filename']);

        if ($logDay >= $days && $logDay < $today) {
            \File::move($path . $file['basename'], $newDirectoryPath . '/' . $file['basename']);
        }

    }
}


text:
Q: Azure Mobile Apps, Authorization works, but token expiration doesn't work I am using custom authentication and generating a JWT token.
When I post to any service, any authorization attribute say [Authorize(Roles = "Admin")] is respected and users who don't have this role are getting an authorisation error (good!). This highlights to me that the token generation and posting back works!
However, when a token expires, nothing happens. And it is treated as a valid token while I should be getting some sort of exception, my code is this:
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
{
    SigningKey = ConfigurationManager.AppSettings["authSigningKey"],
    ValidAudiences = new[] { ConfigurationManager.AppSettings["authAudience"] },
    ValidIssuers = new[] { ConfigurationManager.AppSettings["authIssuer"] },
    TokenHandler = config.GetAppServiceTokenHandler()
});

And:
JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
new Claim[] { new
Claim(JwtRegisteredClaimNames.Sub, assertion["username"]) },
                mySigningKey,
                myAppURL,
                myAppURL,
                // Setting very short time to test expiration
                TimeSpan.FromSeconds(10));

I am testing locally and I am expecting an error being sent to the client stating an expired token. What am I doing wrong?

A: There is a 5-minute expiration grace period to account for clock-skew. I'm guessing that you're sending this token sometime after the 10 seconds but before the 5 minute grace period expires. Try waiting for longer than 5 minutes to confirm whether the token has expired.

A: When a token expires, nothing happens directly.  When you first try to use that token, you should get a 401 Unauthorized error for any endpoint using the [Authorize] attribute.  That's because the token you are submitting is no longer valid.


text:
Q: Is there a "local-to-global" proof of the Mordell–Weil theorem? I am wondering if there is, or is any hope for, a local-to-global proof of the Mordell–Weil theorem.
Below I'll specialize to elliptic curves over $\mathbb Q$ for simplicity, but I'm interested in the general case too.
Also, to be more precise I am wondering about the proof of the full Mordell–Weil theorem assuming the weak version, but any ideas about variations would welcome too.
It seems that the obstruction in proving the full M.–W. theorem from the weak version is the possibility of divisible elements in $E(\mathbb Q)$.
To get some control on this, I want to use the embeddings $E(\mathbb Q)\hookrightarrow E(\mathbb Q_p)$ and the nice "virtual" description of the latter group, namely that it has a subgroup of finite index isomorphic to $(\mathbb Z_p,+)$ (VII.6.3 in Silverman's AEC).
The group $(\mathbb Z_p,+)$ has very little divisibility by $p$ in the sense that one has $\bigcap_{n\geq0} p^n\mathbb Z_p=0$, hence the same holds for $E(\mathbb Q)$ (edit: this is not true—see below).
This leads to the following:
Question.
Suppose $A$ is an Abelian group satisfying the following properties:

*

*For all primes $p$, one has $\bigcap_{n\geq0}p^nA=0$.

*For all $m\geq1$, the quotient $A/mA$ is finite.

Does it follow that $A$ is finitely generated?
If not, can one deduce a stronger algebraic property of $E(\mathbb Q)$ using the embeddings above that would lead to finite generation?
Edit: We cannot guarantee that $E(\mathbb Q)$ satisfies condition (1) above, since it may have nontrivial torsion.
But we can freely pass to the quotient by the torsion, since by VII.3.1 of AEC (injectivity of torsion under reduction) the torsion of $E(\mathbb Q)$ is already known to be finite (or use the Nagell–Lutz theorem?).
But it is still not clear to me that we can guarantee $\bigcap_{n\geq0}p^nA=0$ for all primes $p$, only that for each fixed prime there is a finite-index subgroup of $A$ for which this holds.
Maybe there is an easier counterexample to this weaker version of the question above.
Also, The resemblance between Mordell's theorem and Dirichlet's unit theorem makes me realize that a proof of the M.–W. theorem along these lines should also prove Dirichlet's unit theorem.
This makes me more skeptical that such a proof exists.


text:
Q: Asymptotics of packing Define $m(n,k,l)$ as the maximal size of a family $k$-element subsets of $[n]$ having the property that the intersection of every two sets is less than $l$.
As stated on wikipedia, in 1985 Rödl proved Erdős's conjecture that for fixed $k$ and $l$
$$ \lim_{n \to \infty} m(n,k,l) = \binom{n}{l}/\binom{k}{l}.$$
(The book "the probabilistic method" contains a proof of this fact.)
Does anybody know what happens when $k = k(n), l = l(n)$? I am especially interested in the case when $l = O(\log n)$ and $k = n^{\epsilon}$ (which is one of the settings that has applications in theoretical computer science for Nisan-Wigderson pseudorandom generators).


text:
Q: How to create dictionary key-values in django I am developing server web with Django, and my model ST_Folio contains idST and idFolio, I need to create a dictionary {idST: [idFolio1, idFolio2, ...]}
But my problem is that I can create similar dictionary but no like I want.
I am using this method for this..
st_database = St_folio.objects.exclude(idST__isnull=True)
dictionary = {k: list(g) for k, g in groupby(st_database, key=lambda q: q.idST)}

and obtains this
First print (st_database):
<QuerySet [<St_folio: 1st_folio>, <St_folio: 2st_folio>, <St_folio: 3st_folio>]>

Second print (dictionary):
{<ST: st1>: [<St_folio: 1st_folio>, <St_folio: 2st_folio>], <ST: st2>: [<St_folio: 3st_folio>]}

I need thing like this:
{<ST: st1>: [<idFolio: folio1>, <idFolio: folio20>], <ST: st2>: [<idFolio: folio1>]}

My model ST_Folio
class St_folio(models.Model):
    idST = models.ForeignKey('ST', blank=True, null=True)
    idFolio = models.ForeignKey('Folio', blank=True, null=True)
    class Meta:
        unique_together = (('idST', 'idFolio'),)
    idPro = models.ForeignKey('Pro', blank=True, null=True)
    path_img = models.TextField(blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    lng = models.FloatField(blank=True, null=True)
    lat = models.FloatField(blank=True, null=True)
    date = models.DateTimeField(blank=True, null=True)
    def __str__(self):
        return str(self.id) + "st_folio"

Thanks!!

A: You could access the related objects and build a list from those:
dct = {k: [x.idFolio for x in g] for k, g in groupby(st_database, key=lambda q: q.idST)}

Also, note that groupby requires that the iterable be presorted, therefore, you may want to order your QuerySet befoere applying groupby:
st_database = St_folio.objects.exclude(idST__isnull=True).order_by('idST')

Or:
st_database = St_folio.objects.exclude(idST__isnull=True).order_by('idST_id')

in case you have a different field specified for Meta.ordering.
You can also add select_related to fetch the related object and optimize access to the related objects.


text:
Q: Overloaded final function in derived class How can I use final overloaded function from derived class?
Compiler says 'no matching function for call to 'B::foo()''.
class A
{
public:
    virtual void foo() final
    {
        std::cout << "foo";
    }
    virtual void foo(int b) = 0;
};

class B : public A
{
public:
    void foo(int b) override
    {
        std::cout << b;
    }
};

//Somewhere
B* b = new B;
b->foo(); //Error

But it works without overloading.
class A
{
public:
    virtual void foo() final
    {
        std::cout << "foo";
    }
};

class B : public A
{
};

//Somewhere
B* b = new B;
b->foo(); //Works!

A: This declaration in class B
void foo(int b) override
{
    std::cout << b;
}

hides all other  functions with the same name declared in class A (excluding of course the overriden function).
You can either call the function explicitly like this
b->A::foo();

Or include using declaration
using A::foo;

in the definition of class B.
Or you can cast the pointer to the base class pointer
static_cast<A *>( b )->foo();


text:
Q: Is explorer.exe connecting to a Singapore Microsoft server common behaviour? Netstas results
explorer.exe TCP 192.168.x.x: 491x 111.221.124.116: 443 ESTABLISHED
Is this part of error reporting?

A: Port 443 is the https-protocol. Depending on your Windows-version and settings it could be part of SmartScreen.
Why would you think it was part of the "error reporting"?
Error reporting would only occur when you encounter an error. And even then Microsoft asks permission to send data to its servers.
So i think SmartScreen is a more likely candidate for this open connection.
SmartScreen is used to scans all the files before opening them. This protects you from malware.

You can read a discussion here. It's a different IP but i imagine Microsoft uses many different IPs for this.
If you want to disable SmartScreen (to see if it is indeed the connection you're referring to)
you can follow this guide (if you use Windows 8).


text:
Q: Javascript onload event to resize image help This might be a simple one for you guys, im learning Javascript and have hit a problem. I am trying to have the script resize a particular image on the page when onload is called like so:

...

...

apologies, forgot to mention that is doesn't work! after loading the page in multiple browsers the image stays it native size and the error consoles say they fail to parsing value for height. Declaration dropped.
I have tried lots of different ways but cannot seem to get it to work.

A: (document.body.clientWidth) * 0.2 will give you an integer. The CSS height property accepts a length.
Add some units.

A: There is a live example at http://jsbin.com/uyihe4
You can see the zoom effect when loading. I have only changed the
document.getElementById("sampleImage").style.height

to
document.getElementById("sampleImage").height

A: Well, your problem is that the images may not be ready when you apply the styles to them.
Use this function instead (note it takes a DOM object):
var imgLoader = function(domImg) {
  var imgObj = new Image();
  imgObj.onload = function()
  {
    // apply styles
    domImg.style.height = "100px";
  }
  imgObj.src = domImg.src;
}

A: Though I haven't figure out the problem. But the following code snippet works for me (Tested in Chrome 8.0 and IE9.0Beta).

        <title>test</title>


text:
Q: What is the difference between gksudo and gksu? Is there any difference between the behavior of gksu foo and gksudo foo?
Can they be used interchangeably?

A: Both files point to the same place:
$ ls -l /usr/bin/gksudo
lrwxrwxrwx 1 root root 4 2010-09-27 18:23 /usr/bin/gksudo -> gksu

... gksudo is symlinked to gksu. But this doesn't mean they do the same things, far from it.
Applications can detect the command used to run it. This is typically argv[0] in C-style languages or $0 in Bourne-style shell scripts. The application can look at that and in this case, actually it changes how it works. The first indication of this is in the man gksu page:
gksu  is  a  frontend  to  su  and gksudo is a frontend to sudo.

If you look in the source (apt-get source gksu) for run_mode, you'll see how it detects this:
  { /* support gksu_sudo_run */
    gchar *myname = g_path_get_basename (argv[0]);
    if (!strcmp(myname, "gksudo"))
      run_mode = SUDO_MODE;
    g_free (myname);
  }

You can override this with the --su-mode/-w and --sudo-mode/-S arguments (so you can run equivalent commands without needing the gksudo symlink... But that's up to you.
If you want to know how these "modes" really differ, there's only a bit of escaping in gksu. You need to follow it into libgksu. This is the library that actually checks permissions before handing off to the system.
If no mode is specified (eg you call gksu without arguments) by the time it reaches  libgksu, it will check Gconf (as Stefano points out) and if it still can't decide, it'll default to the su mode.

A: In Ubuntu (!), there is no difference.

*

*gksu would normally log in the root user and run an app on this session. However, on Ubuntu, it defaults to using the "sudo mode", which is equivalent of running gksudo. This is because on ubuntu, you can't log in as root by default.

*gksudo is the graphical equivalent of sudo (and as Oli points out, just a symbolic link to gksu)
From the gconf entry of gksu:

Furthermore, on the difference between sudo and gksudo:

You should never use normal sudo to start graphical applications as root. You should use gksudo (kdesudo on Kubuntu) to run such programs. gksudo sets HOME=~root, and copies .Xauthority to a tmp directory. This prevents files in your home directory becoming owned by root. (AFAICT, this is all that's special about the environment of the started process with gksudo vs. sudo). — (from the community documentation via Chris Wilson)

A: I know that this is an old thread, but I've been asked to tell you about a subtle but essential difference between gksu and gksudo.
Although I have looked long and hard, I cannot find a documented difference anywhere, and yet it does exist. I have also not found out why there is a difference. I found this the hard way when I accidentally deleted some system files precisely because of this difference (discussed in a thread in Ubuntu Forums) — I had been using gksu, but since then I have made sure always to use gksudo.
To summarise, try this.

*

*Create three files in some folder:
touch abc
touch abc.tmp
touch abctmp

*Run the following six commands. The first five give the same (expected) result (i.e. just abc.tmp) whereas the sixth includes an extra file (abctmp) that it shouldn't.
find . -regextype posix-egrep -regex '.*\.tmp' -print
sudo find . -regextype posix-egrep -regex '.*\.tmp' -print
gksudo -- find . -regextype posix-egrep -regex '.*\.tmp' -print
gksudo --su-mode -- find . -regextype posix-egrep -regex '.*\.tmp' -print
gksu --sudo-mode -- find . -regextype posix-egrep -regex '.*\.tmp' -print
gksu -- find . -regextype posix-egrep -regex '.*\.tmp' -print

Imagine the problems when you replace -print with -delete in the find command (which is exactly what happened to me, causing some system files to be deleted).
So, please use gksudo instead of gksu.


text:
Q: value of output layer of feed-forward MLP is too large to softmax properly I have a simple classification problem.
Input feature's range: 0 ~ 65535
Target output: 2 labels, [1, 0] or [0, 1]
Here is what my MLP looks like.
def multilayer_perceptron(x):
    mu = 0
    sigma = 1

    dim = 23
    left = 30
    right = 10

    # Network Parameters
    n_hidden_1 = 128 # 1st layer number of features
    n_hidden_2 = 128 # 2nd layer number of features
    n_hidden_3 = 128 # 2nd layer number of features

    n_input = dim*(left+1+right)
    n_classes = 2

    layer_1_w = tf.Variable(tf.truncated_normal([n_input, n_hidden_1], mean = mu, stddev = sigma), name='layer_1_w')
    layer_1_b = tf.Variable(tf.truncated_normal([n_hidden_1]), name='layer_1_b')
    layer_1 = tf.add(tf.matmul(x, layer_1_w), layer_1_b)
    layer_1 = tf.nn.relu(layer_1)

    layer_2_w = tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2], mean = mu, stddev = sigma), name='layer_2_w')
    layer_2_b = tf.Variable(tf.truncated_normal([n_hidden_2]), name='layer_2_b')
    layer_2 = tf.add(tf.matmul(layer_1, layer_2_w), layer_2_b)
    layer_2 = tf.nn.relu(layer_2)

    layer_3_w = tf.Variable(tf.truncated_normal([n_hidden_2, n_hidden_3], mean = mu, stddev = sigma), name='layer_3_w')
    layer_3_b = tf.Variable(tf.truncated_normal([n_hidden_3]), name='layer_3_b')
    layer_3 = tf.add(tf.matmul(layer_2, layer_3_w), layer_3_b)
    layer_3 = tf.nn.relu(layer_3)

    out_layer_w = tf.Variable(tf.truncated_normal([n_hidden_3, n_classes], mean = mu, stddev = sigma), name='out_layer_w')
    out_layer_b = tf.Variable(tf.truncated_normal([n_classes]), name='out_layer_b')
    out_layer = tf.matmul(layer_3, out_layer_w) + out_layer_b
    return out_layer

After training process, I use training data(value range from 0~65535) to test my network. But the value of output layer is too large(more than 1000) or too small(less than -1000). Basically, I can have the correct answer by picking the larger value from two of them of output layer. But at the same time, I also want to put the output layter to softmax().
Here are my questions:

*

*If I feed softmax() with the very large or very small value, I got [1, 0] or [0, 1] which is not intuitive. I want the output of softmax be something like [0.333, 0.667]. How can I achieve this by controlling the value of the output layer to be very close.

*I've tried to normalize input feature to 0 ~ 1. It helps but the value of output layer is still range from -100 to 100 which still is too large to softmax().

*I believe the cause of this phenomenon is deu to ReLU activation function and adding effect of many neurons. Therefore, I change the ReLU to Sigmoid. The result is what I expected, the value of output layer is closer. But I don't think it's the right way to solve this problem since changing activation funciton alter my network architecture and affect the training process.
Any opinion and experience is welcome. Thanks in advance.


text:
Q: facebook php sdk - ask for additional permissions later I am using the following code to check if the user has given permission to publish on user's wall. I don't want to get this permission initially at login because according to facebook that is a bad practice since user isn't aware what this permission might be used for. So at the time when user clicks on publish to facebook wall, I want to check if user has already given the permission to publish and if not ask for the permission. My code checks which permissions I have and stores in an array list of permissions which I don't have and require from the user.
Problem: But when I get the url and I click on it, it simply redirects me to the redirect url instead of asking permissions.
My code is as follows:
<?php
$permsNeeded = array();
$permsNeeded[] = "email";
$permsNeeded[] = "publish_stream";

require_once( 'includes/Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'includes/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'includes/Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'includes/Facebook/Entities/AccessToken.php' );
require_once( 'includes/Facebook/Entities/SignedRequest.php' );

require_once( 'includes/Facebook/FacebookSession.php' );
require_once( 'includes/Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'includes/Facebook/FacebookRequest.php' );
require_once( 'includes/Facebook/FacebookResponse.php' );
require_once( 'includes/Facebook/FacebookSDKException.php' );
require_once( 'includes/Facebook/FacebookRequestException.php' );
require_once( 'includes/Facebook/FacebookOtherException.php' );
require_once( 'includes/Facebook/FacebookAuthorizationException.php' );
require_once( 'includes/Facebook/GraphObject.php' );
require_once( 'includes/Facebook/GraphSessionInfo.php' );

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;

use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

FacebookSession::setDefaultApplication("$appid","$appsecret");
$facebook = new FacebookRedirectLoginHelper("$redirectto");

if(isset($_SESSION['token'])){
    $fbsession = new FacebookSession($_SESSION['token']);
    try{
        $fbsession->Validate($id, $secret);
    }catch(FacebookAuthorizationException $e){
        $fbsession = '';
    }
}

if ( isset( $fbsession ) ) {
    $_SESSION['token'] = $fbsession->getToken();
    $request = new FacebookRequest( $fbsession, 'GET', '/me/permissions' );
    $response = $request->execute();
    $graphObject = $response->getGraphObject();
    $totalproperties = count($graphObject->getPropertyNames());
    $permsArray = array();
    for ($i = 0; $i < $totalproperties; $i++) {
        $permsArray[] = $graphObject->getProperty($i)->GetProperty('permission');
    }
    $permsToPrompt = array();
    for ($i = 0; $i < count($permsNeeded); $i++) {
        if (!in_array($permsNeeded[$i],$permsArray)) {
            $permsToPrompt[] = $permsNeeded[$i];
        }
    }
    if (count($permsToPrompt) > 0) {
        $scopeparams = implode(",",$permsToPrompt);
        $params = array(
            'scope' => $scopeparams
        );
        $helper = new FacebookRedirectLoginHelper($weburl);
        $loginUrl = $helper->getLoginUrl($params);
        echo $loginUrl;
        echo "test";
        //header("Refresh:0;URL=$reloadurl");
    }
    else {
        //Post
    }
}

?>
On echo this returns the following url
https://www.facebook.com/v2.2/dialog/oauth?client_id={app_id_here}&redirect_uri={redirect_url_is_written_here}&state={some_value_here}&sdk=php-sdk-4.0.12&scope=publish_stream

A: The way you're asking for permissions is incorrect. You should change your code to this instead:
$params = array( 'email', 'publish_actions' );
$helper = new FacebookRedirectLoginHelper( $weburl );
$loginUrl = $helper->getLoginUrl( $params );

The parameter $params passed to getLoginUrl is an array of permissions. You don't need to add scope like the old PHP SDK.


text:
Q: Promise in the if statement (Javascript) I want to use promise results in the if statements, however when I try to, I get something like this:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
  resolve(5 * 2)
}, 1000)
})

console.log(promise.then(i => i) === 10) //false

Is it possible to somehow wait for the extraction of the promise result in this case?

A: You can use Async/Await to use it in a more synchronous fashion.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(5 * 2)
  }, 1000)
});

(async () => {
  console.log(await promise === 10);
})();

A: You need to process the result of the Promise within then.
console.log(promise.then(i => i === 10))

This will log the promise object anyway. If you want to log the result:
promise.then(i => console.log(i === 10))

To make it clearer, see the lambda written with more syntax hints:
promise.then(    (i) => { console.log(i === 10); }    );

Or even as an anonymous function:
promise.then(   function(i){ console.log(i === 10); }  );

Here you prepare the behavior beforehand and then pass it:
var myTimeoutHandler = function(i){
    console.log(i === 10);
};
promise.then(myTimeoutHandler);

The i => ... syntax is a shorthand for this.
In general, with Promise (and ReactiveX's Observable alike), you are reacting to something, so you are providing the behavior by passing a callback (here in a form of a lambda). So every action that needs to work with whatever comes processed needs to be within the callback.
Read more about Promise and then.

A: You can only work with the value of a Promise inside of a function passed to then –

const delay = x =>
  new Promise (r => setTimeout (r, 1000, x))

delay (5*2) .then (console.log)
// 10

delay (5*2) .then (x => x === 10) .then (console.log)
// true

Or inside of an async function using the await keyword –

const delay = x =>
  new Promise (r => setTimeout (r, 1000, x))

const main = async () =>
{ const x = await delay (5*2)
  console.log (x)
  console.log (x === 10)
  return 'done'
}

main () .then (console.log)
// 10
// true
// done


text:
Q: BackOffPolicy and SimpleRetryPolicy not in effect when injected into RetryTemplate I am using Spring AMQP to send messages and be able to perform retries on a "custom" Exception. Lets say I have a Receiver which throws a custom exception "EventException" and for that, I want there to be a n number of retries (in our example 5). Between the retries I also want there to be a 5 seconds delay as well. Here is my source code:
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    final static String queueName = "testing-queue";

    @Autowired
    AnnotationConfigApplicationContext context;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    Queue queue() {
        Map<String, Object> arguments = new HashMap<String, Object>();
        arguments.put("x-dead-letter-exchange", "dead-letter-exchange");
        Queue queue = new Queue(queueName, true, false, false, arguments);
        return queue;
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange("testing-exchange");
    }

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    Queue deadLetterQueue() {
        return new Queue("dead-letter-queue", true);
    }

    @Bean
    FanoutExchange deadLetterExchange() {
        return new FanoutExchange("dead-letter-exchange");
    }

    @Bean
    Binding deadLetterBinding(Queue deadLetterQueue, FanoutExchange deadLetterExchange) {
        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange);
    }

    @Bean
    ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory =
                new CachingConnectionFactory("localhost");

        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        return connectionFactory;
    }

    @Bean
    SimpleMessageListenerContainer container(
            ConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter,
            RetryOperationsInterceptor interceptor) {

        Advice[] adviceChain = { interceptor };

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setAdviceChain(adviceChain);
        container.setMessageListener(listenerAdapter);

        return container;
    }

    @Bean
    Receiver receiver() {
        return new Receiver();
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        MessageListenerAdapter adapter =
                new MessageListenerAdapter(receiver, "receiveMessage");

        return adapter;
    }

    @Bean
    RetryOperations retryTemplate() {
         Map<Class<? extends Throwable>, Boolean> retryableExceptions =
                 new HashMap<Class<? extends Throwable>, Boolean>();
        retryableExceptions.put(EventException.class, false);

        FixedBackOffPolicy backoffPolicy = new FixedBackOffPolicy();
        backoffPolicy.setBackOffPeriod(5000);

        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setBackOffPolicy(backoffPolicy);
        retryTemplate.setRetryPolicy(new SimpleRetryPolicy(5, retryableExceptions));

        return retryTemplate;
    }

    @Bean
    RetryOperationsInterceptor interceptor(RetryOperations retryTemplate) {
        RetryOperationsInterceptor interceptor = new RetryOperationsInterceptor();
        interceptor.setRecoverer(new CustomMessageRecover());
        interceptor.setRetryOperations(retryTemplate);

        return interceptor;
//      return RetryInterceptorBuilder
//              .stateless()
//              //.retryOperations(retryTemplate)
//              .maxAttempts(5)
//              .recoverer(new CustomMessageRecover()).build();
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Sending message...");
        rabbitTemplate.convertAndSend(queueName, "Hello from RabbitMQ!");
        context.close();
    }

    public class Receiver {

        public void receiveMessage(String message) throws Exception {
            System.out.println("!!!!!!!!Message has been recieved!!!!!!");
            throw new EventException("TESTING");
        }
    }

    public class CustomMessageRecover implements MethodInvocationRecoverer<Void> {

        @Override
        public Void recover(Object[] args, Throwable cause) {
            System.out.println("IN THE RECOVER ZONE!!!");
            throw new AmqpRejectAndDontRequeueException(cause);
        }
    }

    class EventException extends Exception {
        private static final long serialVersionUID = 1L;

        public EventException() {}

        public EventException(String message) {
            super(message);
        }
    }
}

Now in the code, as you can see I am using RetryOperationsInterceptor in order to intercept and check to see what type of exception it is being thrown and base on that, make the decision to either do the retry or not, along with the delay between the retries.
For this I am setting the backoffPolicy and retryPolicy of the RetryTemplate Bean and having that injected into the RetryOperationsInterceptor.
I would appreciate if anyone can help me out and tell me why the retry and the delay between the retries are not working. My messages are going directly to the dead letter exchange without the retries and the delays happening.
THANK YOU!

A: Your issue is here:
retryableExceptions.put(EventException.class, false);

Please, find the SimpleRetryPolicy code:
public boolean canRetry(RetryContext context) {
    Throwable t = context.getLastThrowable();
    return (t == null || retryForException(t)) && context.getRetryCount() < maxAttempts;
}

and further:
private boolean retryForException(Throwable ex) {
    return retryableClassifier.classify(ex);
}

Since you specify a false for your EventException, it won't be retryable. Hence any retries and backoffs.


text:
Q: Hadoop is complaining for nonexistent anonymous class (NoClassDefFoundError) Consider a simple Java file which creates a BufferedInputStream to copy a local file 1400-8.txt to Hadoop HDFS and print some dots as a progress status. The example is Example 3-3 from the Hadoop book here.
// cc FileCopyWithProgress Copies a local file to a Hadoop filesystem, and shows progress
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;

// vv FileCopyWithProgress
public class FileCopyWithProgress {
  public static void main(String[] args) throws Exception {
    String localSrc = args[0];
    String dst = args[1];

    InputStream in = new BufferedInputStream(new FileInputStream(localSrc));

    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(URI.create(dst), conf);
    OutputStream out = fs.create(new Path(dst), new Progressable() {
      public void progress() {
        System.out.print(".");
      }
    });

    IOUtils.copyBytes(in, out, 4096, true);
  }
}
// ^^ FileCopyWithProgress

I compile the code and create the JAR file with
hadoop com.sun.tools.javac.Main FileCopyWithProgress.java
jar cf FileCopyWithProgress.jar FileCopyWithProgress.class

The above commands generate the files FileCopyWithProgress.class, FileCopyWithProgress$1.class and FileCopyWithProgress.jar. Then, I try to run it
hadoop jar FileCopyWithProgress.jar FileCopyWithProgress 1400-8.txt hdfs://localhost:9000/user/kostas/1400-8.txt

But, I receive the error

Exception in thread "main" java.lang.NoClassDefFoundError:
FileCopyWithProgress$1

To my understanding, the FileCopyWithProgress$1.class is due to the anonymous callback function the program declares. But since the file exists what is the issue here? Am I running the correct sequence of commands?

A: I found the issue so I am just posting in case it helps someone. I had to include the class FileCopyWithProgress$1.class in the JAR. The correct one should be
jar cf FileCopyWithProgress.jar FileCopyWithProgress*.class