text:
Q: Issue with the blank non mandatory date field in JAXB in SOAP UI I am working on financial sector project in jaxb technology. Have developed a web service consumption part and got stuck into a issue BEEN REPORTED FROM CLIENT END. I have two fields in my bean class of date type as follows
 @XmlElement(name = "abc")
    @XmlSchemaType(name = "date")
    private Date abc;

    @XmlElement(name = "qwe")
    @XmlSchemaType(name = "date")
    private Date qwe;

Now when these fields does not have data then it gives exception
Also these fields are not mandatory, takes date in yyyy-mm-dd as per the gregorian calender as per the annotation tags.
The reqest when done testing at local end using SOAP UI
            </data>
               <!--Optional:-->
               <abc></qwe>
               <!--Optional:-->
               <qwe></qwe>
            </data>

Exception Description: The object [], of class [class java.lang.String], from mapping [org.eclipse.persistence.oxm.mappings.XMLDirectMapping[abc-->abc/text()]] with descriptor [XMLDescriptor(fully qualified package name --> [])], could not be converted to [class java.util.Calendar].

Same is the case for both of these fields and works well when the date is filled only in the expected format.
I donot know how to handle this issue properly either through tags or any other means as it gives exception at the bean class itself does not even reaches the service layer.
Any suggestion to solve the problem is appreciable.
Thanks.

A: Base Problem
Empty String is not a valid value for the xsd:date type.  To be valid with the XML schema an optional element should be represented as an absent node.,

Why the Base Problem is Impacting You
All JAXB implementations will recognize that empty String is not a valid value for xsd:date.  They do this by reporting it to an instance of ValidationEventHandler.  You can see this yourself by doing the following:
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            System.out.println(event);
            return true;
        }
    });

The implementation of JAX-WS you are using, leverages EclipseLink MOXy as the JAXB provider.  And in the version you are using MOXy will by default throw an exception when a ValidationEvent of severity ERROR is encountered instead of FATAL_ERROR like the reference implementation.  This has since been fixed in the following bug:

*

*http://bugs.eclipse.org/369994

Work Around
If you are using the JAXB APIs directly you could simply override the default ValidationEventHandler.  In a JAX-WS environment a XmlAdapter can be used to provide custom conversion logic.  We will leverage an XmlAdapter to override how the conversion to/from Date is handled.
XmlAdapter (DateAdapter)
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, Date>{

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date unmarshal(String v) throws Exception {
        if(v.length() == 0) {
            return null;
        }
        return dateFormat.parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        if(null == v) {
            return null;
        }
        return dateFormat.format(v);
    }

}

Java Model (Root)
The XmlAdapter is referenced using the @XmlJavaTypeAdapter annotation.  If you wish this XmlAdapter to apply to all instances of Date you can register it at the package level (see:  http://blog.bdoughan.com/2012/02/jaxb-and-package-level-xmladapters.html).
import java.util.Date;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlSchemaType(name = "date")
    @XmlJavaTypeAdapter(value=DateAdapter.class, type=Date.class)
    private Date abc;

    @XmlSchemaType(name="date")
    @XmlJavaTypeAdapter(value=DateAdapter.class, type=Date.class)
    private Date qwe;

}

Demo Code
Below is a standalone example you can run to see that everything works.
jaxb.properties
In a standalone example to use MOXy as your JAXB provider you need to include a file called jaxb.propeties in the same package as your domain model with the following entry (see:  http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

input.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <abc></abc>
    <qwe>2013-09-05</qwe>
</root>

Demo
import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum18617998/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Output
Note that in the marshalled XML the Date field that was null was marshalled as an absent element (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <qwe>2013-09-05</qwe>
</root>


text:
Q: Http protocol, Content-Length, get page content Python I'm trying to code my own Python 3 http library to learn more about sockets and the Http protocol. My question is, if a do a recv(bytesToRead) using my socket, how can I get only the header and then with the Content-Length information, continue recieving the page content? Isn't that the purpose of the Content-Length header?
Thanks in advance

A: In the past to accomplish this, I will read a portion of the socket data into memory, and then read from that buffer until a "\r\n\r\n" sequence is encountered (you could use a state machine to do this or simply use the string.find() function.  Once you reach that sequence you know all of the headers have been read and you can do some parsing of the headers and then read the entire content length.  You may need to be prepared to read a response that does not include a content-length header since not all responses contain it.
If you run out of buffer before seeing that sequence, simply read more data from the socket into your buffer and continue processing.
I can post a C# example if you would like to look at it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paypal Express checkout only works for base site/currency in multi-site setup I have a site with multiple store fronts where every front has its own top level domain, language and currency. I have activated the built-in paypal express in my Magento 1.7.0.2.
Paypal now works fine as an option for my swedish front. Note that my store's base currency is in swedish currency (SEK). Paypal does not work in any other front such as the UK front which uses british pounds.
For the non-swedish fronts the checkout sends the user to a completely blank page on that front's domain such as https://ourdomain.co.uk/paypal/express/start/
Anybody with clues on what the issue could be? Is PayPal express at all meant to work on a multi-site environment? Could the problem be the currency, the different domains or something else? All ideas welcome.

A: Solved it!
Uncommented "ini_set('display_errors', 1);" from my index.php page which enabled me to see an error message instead of the blank page. Turns out the problem was a conflict with our unirgy gift certificate module. After disabling that module everything works.


text:
Q: More: Generalised: Accessing the logic values of a TikZ coordinate This is a follow-up question to:  Generalised: Accessing the logic values of a TikZ coordinate.
In that question a PGFplot answer was suggested by jake.
I took that answer and modified it to the following MWE:
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{intersections}

 \newcommand\xcoord[2][center]{{%
   \pgfpointanchor{#2}{#1}%
   \pgfgetlastxy{\ix}{\iy}%
   \pgfplotspointaxisorigin%
   \pgfgetlastxy{\ox}{\oy}
   \pgfmathparse{(\ix-\ox)/\pgfplotsunitxlength/1000}
   \pgfmathprintnumber{\pgfmathresult}}
}

\begin{document}

\vspace{1cm}
\begin{tikzpicture}
\begin{axis}[
  domain=1:8.2,
  samples=150,
  no markers,
  axis lines=middle,
  enlarge x limits=upper,
  enlarge y limits=true,
  x axis line style={{name path global=xaxis}}
  ]
\addplot +[name path global=plot] {(x-2.07)*(x-4.09)*(x-5.72)*(x-8.04)};
\pgfplotsextra{
\fill [name intersections={of=xaxis and plot, name=i, total=\t}]
  [red, every node/.style={black}]
  (i-1) circle (2pt) node [pin={\xcoord{i-1}}] {}
  (i-2) circle (2pt) node [pin={\xcoord{i-2}}] {};
}
\end{axis}
\end{tikzpicture}
\end{document}

This produces the following:

So the coordinates is off by a factor 10.
How would one correct that and I was wondering how one would access them through a foreach loop in stead of specifically making a node for each of them.

A: Hm, something's not quite right with the \pgfplotsunitxlength macro. I've written a new macro \xcoord macro that works by extracting the values for the plot points (0,0) and (1,1) and using that for the unit vector. Note also that \pgfplotspointorigin points to the point where the two axes meet, not to the point (0,0), so the value was not only off by a factor of 10, but also by a shift of 1. I used the point (0,0) in the code below to correct for this.
You can just loop through the intersections by using \foreach \n in {1,...,\t}, where \t is the macro that holds the total number of intersections specified in total=\t.
There are sometimes issues with intersections being found twice if they lie exactly on one of the support points of the plot. In that case, you should adjust the domain slightly.
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{intersections}

 \newcommand\xcoord[2][center]{{%
   % The actual point of interest
   \pgfpointanchor{#2}{#1}%
   \pgfgetlastxy{\ix}{\iy}%
   % (0,0)
   \pgfplotspointaxisxy{0}{0}%
   \pgfgetlastxy{\ox}{\oy}
   % (1,1)
   \pgfplotspointaxisxy{1}{1}%
   \pgfgetlastxy{\ux}{\uy}
   \pgfmathparse{(\ix-\ox)/(\ux-\ox)}
   \pgfmathprintnumber{\pgfmathresult}}
}

\begin{document}

\vspace{1cm}
\begin{tikzpicture}
\begin{axis}[
  xmin=0,
  domain=0:8.4,
  restrict y to domain=-100:50,
  samples=149,
  no markers,
  axis lines=middle,
  enlarge x limits=upper,
  enlarge y limits=true,
  x axis line style={{name path global=xaxis}}
  ]
\addplot +[name path global=plot] {(x-2.07)*(x-4.09)*(x-5.72)*(x-8.04)};
\pgfplotsextra{
\fill [name intersections={of=xaxis and plot, name=i, total=\t},
    red,
    every node/.style={black}]
    \foreach \n in {1,...,\t} {
  (i-\n) circle (2pt) node [pin={\xcoord{i-\n}}] {}
  };
}
\end{axis}
\end{tikzpicture}
\end{document}


text: Q: SharePoint 2007 - Calendar time column freeze pane I built a basic schedule for my team on our team site SharePoint 2007 and I am noticing a formatting issue. When we scroll the schedule to the right, you can no longer see the time column to the left. I was hoping there might be a simple way to resolve this issue and "freeze pane" the time column. I do not have access to add a content editor web part, but I do have access to SharePoint designer. So please keep that restriction in mind.


text:
Q: How to verify TPS is achieved from Aggregate Summary report in JMeter I need to verify one of API TPS.
6TPS is Requirement.
I have given 6 user load , 1s pacing and runned for 1hr.
Output snap attached.
From the Output how do i verify that API is achieved 6TPS.
Thanks in advance enter image description here

A: In your case the number of TPS for Get_id transaction is 1.9 per second so my expectation is that you either need to remove pacing or increase the number of users or both.
You can reach 6 TPS with 6 users only if response time is 1 second (or less), looking at your results it can be as high as 5.6 seconds so either your server cannot server 6 transactions per second of you just need to add more users.
If you want to check the throughput automatically and fail the test if the expected number of transactions per second is not met you can consider running your JMeter test using Taurus tool as a wrapper, Taurus provides flexible and powerful Pass/Fail criteria subsystem which can check multiple metrics and return non-zero exit status code in case if throughput will be lower than your expectations.
More information: Failure Criteria


text:
Q: Filtering OrganizationUser's by Organization in Django-Organizations There is a relatively similar thread on this topic, but I can't seem to figure out how to translate it to my situation. I have a roster that I need to only display the organizationusers within the same organization of the viewer. I have a webapp that I am developing that is used to manage volunteers in an organization. I'm still new to backend development so I'm having trouble problem solving.
This is the code for the table view using Django_Tables2 package:
#tables.py
class VolunteerTable(tables.Table):
    class Meta:
        model = OrganizationUser

# views.py
def VolunteerRoster(request):
    table = tables.VolunteerTable(OrganizationUser.objects.all())
    return render(request, 'staff/roster.html', {'table': table})
I'm trying to figure out how to either convert the view to a class-based view so I can use the OrganizationMixin and the SingleTableView in Django_Tables2's documentation.

I was thinking about something like this based on the other threads explanation
class VolunteerRoster(SingleTableView, OrganizationMixin):
    table_class = VolunteerTable
    queryset = OrganizationUser.objects.all()
    template_name = "staff_roster.html"

    def get_queryset(self):
        return self.queryset.filter(organization=self.get_organization())

When I try this I get: "TypeError: init() takes 1 positional argument but 2 were given"
As I said, I'm still new to django so I'm not really sure what to fix in this instance.

A: Try:
def get_queryset(self):
    return OrganizationUser.objects.filter(organization=self.request.user.organization)


text:
Q: Is there any way to send a 3-plug RCA audio/video signal to an ipad screen? I have a "Phantom DJI" quadcopter with a lot of upgrades, including a "Fatshark predator" "FPV" system which basically allows me to view VGA quality video, live, from a gopro mounted on the quadcopter. The fatshark comes with a so-so video quality "virtual boy" looking pair of goggles that doubles as the receiver itself.
This headset/receiver has a 1/16th inch 3 ring RCA A/V output jack that can go to a video monitor. The kit includes a cable which can be plugged into a traditional RCA jack setup.
So my question is, is there any way to transmit rca video signal to an ipad? For example, one or more "proxies" as a solution could be reasonable. Transmitting the last leg to the ipad via some internet protocol may work for example.
The appeal of using the ipad is that it is a high resolution battery powered monitor which I already own. I'll be in the field with this thing and the portability is of particular interest.
I consider solutions requiring jailbreaking reasonable answers though this is not preferred for obvious reasons. Also, low cost android tablet solutions are equally reasonable. I've already ordered an RCA-to-hdmi converter which should arrive shortly.


text:
Q: Explain Kerr-Newmann Black Hole Spins in SI Units I'm trying to run some calculations on Kerr-Newman black holes, but I'm having two major difficulties.  First, most equations I've been able to find are only for Kerr black holes.  Second, essentially all equations are in one of several incompatible varieties of "natural units" (this is a big problem for me, since my background is not in Physics, and so I don't magically know when to multiply things by $c$, $G$, $k_B$, $\hslash$, $M$, etc.).
In approximately increasing order of my confusion:

*

*"$J$": I assume this is angular momentum, with the usual $\text{kg}\cdot\text{m}^2\cdot\text{s}^{-1}$ units?

*"$J_{max}(M)$": Presumably the maximum allowable value of $J$ for a given mass $M$ (in $\text{kg}$).  I found an SI formula for a Kerr black hole.  Would it be different for a Kerr-Newman black hole?

*"$\Omega$": Angular velocity (from an observer at infinity, with units $\text{rad}\cdot\text{s}^{-1}$, I assume).  I found this formula for Kerr, not Kerr-Newman, and I couldn't get the units to make sense.

*"$M$": I assume this is mass in $\text{kg}$.  But, I've also seen it rescaled to $\text{m}$, somehow.

*"$a$": Some kind of spin parameter?  Unclear how exactly this relates to $J$.  AFAICT, there are multiple definitions, with dimensionless units, meters (e.g. as $J/(M c)$ from Abramowicz and Fragile 2013 $\S 3$), and possibly other units.  Is the dimensionless version supposed to be $a/M$, with $M$ rescaled to length (by $GM/c^2$) or something?  I also found a dimensionless version here as a ratio of $J$ to $J_{max}(M)$.  How does that tie in?

*"$a/M$": Specific angular momentum?  Seen in e.g. Bardeen et al. 1972 (fig 1.).  Also seems to be called $\chi$, "dimensionless spin".  Does this have anything to do with spin?
For each of these quantities (and anything else relevant), I'm looking for (1) their scientific names (so I can research them), (2) their SI definitions (so I can do dimensional analysis on them), and (3) their SI equations for Kerr-Newman black holes (so I can calculate them).  At least a self-consistent explanation of $a$, $a/M$ and how they relate to $J$, as treated in the literature, so that I'm not completely lost when reading it anymore.

A: On the wikipedia page https://en.wikipedia.org/wiki/Kerr%E2%80%93Newman_metric the Kerr-Newman (KN) metric is given in SI units and all metric parameters are defined. $J$ is the black holes (BH) angular momentum, $Q$ its charge and $M$ its mass.
$a=J/(M c)$ is called "Kerr parameter" or angular momentum per unit mass it has the dimension of length. One can get this dimensionless by e.g.
$\chi=a/(M G)c^2$. I am not aware of an interpretation of $\chi$ as a quantum mechanical spin but I know that the a KN BHhas a Dirac gyromagnetic ratio of $\gamma_{KN}=Q a c$. For more information on that topic I would recommend the references in section "Interpretive issues" of http://www.scholarpedia.org/article/Kerr-Newman_metric .
The a KN BH has two horizons $r_\pm$:
$$r_\pm=\frac{M G}{c^2}\pm\sqrt{\left(\frac{M G}{c^2}\right)^2-a^2-r_Q^2},\tag{1}$$
with $r_Q\equiv \frac{Q^2 G}{4\pi\epsilon_0 c^4}$ as the length scale corresponding to the black holes charge Q. A Kerr-Newman black hole is extremal for $r_+=r_-$ which means for $a_{ext}$
$$a_{ext}=\pm\sqrt{\left(\frac{M G}{c^2}\right)^2-r_Q^2}.$$
The angular velocities on the horizons of the Kerr metric are given by
$$\Omega_\pm=\frac{a}{a^2+r_\pm}c,\tag{2}$$
so using eq. (1) would lead to a charge contribution. Which makes sense, since the KN metric has electromagnetically induced frame-dragging but I am not certain if (2) is correct for a KN BH.
Maybe after that one short note on geometrical units in General relativity $GR$: they usually use only $G=c=1$ and use that to convert all dimensions to powers of length: a second can be converted to a meter by multiplying with $c$ and a kilogram  can be converted to meter by multiplying it with $G/c^2$. For currents or charges there are a few conventions out there. One example would be $\mu_0/(4\pi)=c=G=1$ which makes currents dimension less. One Ampere can be converted multiplying it with $\sqrt{G \mu_0/(4\pi)}/c^2$.  If temperatures are involved $k_B=1$ can be used to convert temperatures into energies. Energies can be converted to length by multiplying with $G/c^4$. $\hbar$ is not common in GR since $c=G=\hbar=k_B=\mu_0=1$ would result in completely dimensionless Planck units. But in principle $\hbar$ can be used instead of $G$ to convert masses or with $c=G=k_B=\mu_0=1$ to eliminate the last dimension.
Geometrized units are not hard to understand and extremely useful in theoretical physics, since they make equations less cluttered and numerical computations easier.

A: To get the dimensionless spin parameter use
$$\rm \bar a=\frac{J c}{G M^2}$$
where J is the angular momentum of the black hole (the angular momentum J can be expressed in terms of GM²/c, so divide by that to get rid of the dimensions). This always gives a number between 0 and 1 for black holes (regular objects also can have spin parameters larger than 1, but those have to eject some of their angular momentum before collapsing to a black hole). If for some reasons you want to keep the M in the equations instead of setting G=M=c=K=1, just divide by M instead of M².


text:
Q: Avery labels printing PDF 2 columns across then down I have followed this documentation http://www.bscichicago.com/documents/CreatingAvery5160MailingLabelsSSRS.pdf
to print my labels but I did not see where they Spreading Data across 2 columns. PDF rendering is just printing in first column and at the end of the page it will now begin the second column. I wish to print in one column then next column before going to the second row in PDF rendering. Thanks

A: Create two identical tables side by side that both point to your data set. On the Detail row of the first table, for the Visibility-Hidden property use the following formula:
=iif((RowNumber(Nothing) Mod 2) = 0, True, False)

On the Detail row of the second table, for the Visibility-Hidden property use the formula:
=iif((RowNumber(Nothing) Mod 2) = 1, True, False)

This means the first table will print every odd row and the second table will print every even row, effectively giving you multiple column output but left-to-right first, then down the page, rather than down the page first before moving to the next column like SSRS multi-column reports do.


text:
Q: How to Install Pillow on Openshift I'm trying to deploy my django web application on OpenShift. When I try to deploy it I get this error:

I have no idea how I can access the terminal in the openshift to install pip.

A: Add pillow==6.2.1 on your requirements.txt and deploy again, OpenShift will read thi's file and install all requirements.


text:
Q: Redirect doesn't work in Application_BeginRequest Everything in the code below works great.  The log logs. But the redirect never happens....
        if (HttpContext.Current.Request.Url.Host.ToLower().Trim() == "mydomain.com")
        {
            if (!HttpContext.Current.Request.IsSecureConnection)
            {
                LogThis.WriteLog("redirecting");
                HttpContext.Current.Response.Redirect(
                    string.Concat("https://mydomain.com", Request.RawUrl));
                HttpContext.Current.Response.End();
            }
        }

Any ideas?  This is all happening in the Application_BeginRequest, in the global.asax.  It's inline code, inside a  tag.  There is no codebehind at all.


text:
Q: Matching ViewModel and View in MVVMCross I have an MVVM Cross application, and I'm trying to figure out why the initial screen isn't showing (this is on WinRT).
The following code looks like it loads the ViewModel MainViewModel:
var setup = new Setup(rootFrame);
setup.Initialize();

var start = Cirrious.CrossCore.Mvx.Resolve<Cirrious.MvvmCross.ViewModels.IMvxAppStart>();
start.Start();

However, the Start method of MainViewModel never gets called.  The reason appears to be this error in the output:
Error seen during navigation request to MainViewModel - error KeyNotFoundException: Could not find view for MyApp.PCL.ViewModels.MainViewModel

So, here's my guess as to the problem: it's looking for MyApp.PCL.ViewModels.MainView, Obviously, this doesn't exist.  The view is in: MyApp.Views.MainView.  Is my assumption correct and, if so, how can I persuade MVVMCross to look in the correct place?
EDIT:
The Setup method is called from the MyApp.Windows WinRT app.
protected override IMvxApplication CreateApp()
{
    return new MyApp.PCL.App();
}

MyApp.PCL is a portable class library that is referenced from MyApp.Windows.
MyApp.PCL contains the ViewModels, and MyApp.Windows contains the views.
I have tried to override Start():
public class MainViewModel
    : MvxViewModel
{

    public override void Start()
    {
        System.Diagnostics.Debugger.Break();
        base.Start();
    }

but this never gets hit.

A: Massive Doh! here, but I'll post the solution; my view was not using the MvxStoreView, but the standard StoreView.
The solution was to change the view as follows:
 ...
 xmlns:views="using:Cirrious.MvvmCross.WindowsStore.Views"
 ...
<views:MvxStorePage


text:
Q: Having error when pushing global linked list *sometimes(randomly)* I created a global linked list. It doesnt work sometimes. First push is always succesfully done but second push makes error sometimes. I tried on another computer but its same.
typedef struct person{
    char name[20];
    char surname[20];
    char musical_Work[20];
    int age;
    struct person *next;
}*top;

top head=NULL;  /* GLOBAL */

void addNode(   /* datas */    ){
    top new_node=(top)malloc(sizeof(top));

    /* copying datas */

    new_node->next=head;
    head=new_node;
}

A: The code top new_node=(top)malloc(sizeof(top)); allocates enough space for a top, which is a pointer to struct person. However, the space is going to be used to hold struct person, and therefore it must allocate enough space for struct person. Therefore, correct code for this is:
 top new_node=(top)malloc(sizeof(struct person));

Additionally:

*

*Using sizeof *new_node automatically allocates enough space for whatever new_node points to, even if the type of new_node is changed as the code is edited.

*In C, there is no need to cast the type of malloc. This code can be top new_node = malloc(sizeof *new_node);.

*Consider using a different name for a pointer to struct person, instead of top. It is not always the top of the stack.


text:
Q: Try to update sessions value using forEach loop In an admin profile, I have a list where I display the session history. I created a button to delete all sessions where isActive = false. To see the result I have to refresh my page. I want the data updated dynamically.
I'm trying to use a forEach loop to check if session isActive = false, delete the session and update sessions.
Here it's what I have done but it only removes 2-3 raw of sessions. It should remove ALL inactive sessions.

import { defineStore } from "pinia";

import axios from "axios";

export const useAuthenticationStore = defineStore({
  id: "authenticationStore",
  state: () => ({
    session: null,
    sessions: [],

    loaders: {
      login: false,
      logout: false,
      retrieveSession: false,
      retrieveSessions: false,
      deleteInactiveSessions: false,
    },
  }),

getters: {
    admin: (state) => state.session?.admin,
  },

  actions: {
     async deleteInactiveSessions(id) {
          const apiRoute = `/api/inactive-sessions`;
          try {
            this.loaders["deleteInactiveSessions"] = true;
            const deletedInactiveSessions = await axios.delete(apiRoute);
            console.log(deletedInactiveSessions);
            this.sessions.forEach(() => {
              const deletedInactiveSessionsIndex = this.sessions.findIndex(
                (session) => session.id === deletedInactiveSessions.id
              );
              return this.sessions.splice(deletedInactiveSessionsIndex);
            });
          } finally {
            this.loaders["deleteInactiveSessions"] = false;
          }
        },

This is what deletedInactiveSessions returns me:

{data: {…}, status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
config
:
{transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data
:
{count: 3}
headers
:
AxiosHeaders {access-control-allow-credentials: 'true', access-control-allow-origin: '*', connection: 'close', content-length: '11', content-security-policy: "default-src 'self';base-uri 'self';block-all-mixed… https: 'unsafe-inline';upgrade-insecure-requests", …}
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
"OK"
[[Prototype]]
:
Object


text: Q: How should I deduce the conjugate prior and corresponding posterior for a geometric distribution The given pmf is for a geometric distribution and is $f(x_i|\theta) = (1-\theta)^{x_i - 1}\theta; ~x_i = 1, 2 ,\cdots, $ and the 1-parameter exponential family I have obtained is; $$f(x|\theta) = \exp \left\{ \log \left(\frac{\theta}{1 - \theta} \right) + x_i \log (1-\theta)\right\}$$I have tried to obtain the conjugate prior and have arrived at this step; $$f(x_i|\theta) \propto \ \left\{ b \log \left(\frac{\theta}{1 - \theta} \right) + a \log (1-\theta) \right\}$$I know the conjugate prior has to be a Beta distribution. How do I deduce it from this last step? Also, how do I obtain the corresponding posterior distribution?


text:
Q: Does sagemaker inference recommendation job support multi model endpoint I am trying to perform load test on sagemaker multimodel endpoint.I found out that we can't run an instance recommendation job for an existing endpoint from this link https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-existing-endpoint.html but in the inference recommendation job for without endpoint documentation this is not mentioned.So I just wanted to know how can we run inference recommendation job for multi model endpoint.And since the inference recommendation job will create and invoke endpoint on its side where can i provide extra parameters required for multi model endpoint
I checked this links

*

*https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-existing-endpoint.html

*https://docs.aws.amazon.com/sagemaker/latest/dg/inference-recommender-instance-recommendation.html


text:
Q: How to get Swift KVO working for static member? I have a UIViewController with the following code. I want to know when the value of portrait effect is changed (in control center). I have tried AVCaptureDevice.isPortraitEffectEnabled and .portraitEffectEnabled, both have the same result: observeValue() is never called. I have verified that the value itself does actually change, and the docs state that KVO is supported for this member.
What am I missing?
To test this I am toggling the value of portaitEffectEnabled by calling AVCaptureDevice.showSystemUserInterface(.videoEffects) and turning it on/off, and expecting the KVO to fire.
@objc class EventSettingsCaptureViewController : UIViewController, ... {

    required init(...) {
        super.init(nibName: nil, bundle: nil)

        if #available(iOS 15.0, *) {
            AVCaptureDevice.self.addObserver(self, forKeyPath: "portraitEffectEnabled", options: [.new], context: nil)
        }
    }

    deinit {
        if #available(iOS 15.0, *) {
            AVCaptureDevice.self.removeObserver(self, forKeyPath: "portraitEffectEnabled", context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // Breakpoint set here: never hits
        if keyPath == "portraitEffectEnabled" {
            guard let object = object as? AVCaptureDevice.Type else { return }

            if #available(iOS 15.0, *) {
                WLog("isPortraitEffectEnabled changed: \(object.isPortraitEffectEnabled)")
            }

        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }

A: That won't work because the AVCaptureDevice class itself doesn't have a portraitEffectSupported property.
The issue is that the portraitEffectSupported property is an instance property.
you can always use class_copyPropertyList to double check that the property you're trying to observe actually exists on that object. Here's an example:
import AVFoundation

func getPropertyNames(of target: AnyObject) -> [String] {
    let itsClass: AnyClass = object_getClass(target)!

    var count = UInt32()
    guard let p = class_copyPropertyList(itsClass, &count) else {
        return []
    }

    defer { p.deallocate() }

    let properties = UnsafeBufferPointer(start: p, count: Int(count))

    return properties.map { String(cString: property_getName($0)) }
}

// `AVCaptureDevice` has no class properties.
let propertiesOfTheClassItself = getPropertyNames(of: AVCaptureDevice.self)
print(propertiesOfTheClassItself) // => []

// Instances of `AVCaptureDevice` have some instance properties.
let propertiesOfASampleInstance = getPropertyNames(of: AVCaptureDevice.default(for: .video)!)
print(propertiesOfASampleInstance) // => ["transportControlsSupported", "transportControlsPlaybackMode", "transportControlsSpeed", "adjustingFocus", "adjustingExposure", "adjustingWhiteBalance"]


text:
Q: Status of Package Deployed in OSGi Bundle of AEM 6.0 is Active but Having Concern upon Usage I deployed a package in OSGi bundle of AEM 6.0 which has a status of Active. But when I tried to use it run-time in a certain page, it shows some exception:
05.06.2015 18:12:29.460 *ERROR* [0:0:0:0:0:0:0:1 [1433499148835] GET /content/g0/en/about-us/career/jobs.html HTTP/1.1] org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Uncaught SlingException
java.lang.NoClassDefFoundError: javax/xml/namespace/QName
...
....
...
Caused by: java.lang.ClassNotFoundException: javax.xml.namespace.QName not found by com.**.wcm.recruitment-client [499]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1557)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:79)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1998)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 240 common frames omitted

I tried to manipulate the Import-Package and Export-Package under pom.xml but still concern persists.
See below for the XML that I am trying to manipulate.
    <plugin>
    ...
    ...
                    <instructions>
                        <Bundle-Activator>com.**.recruitment.Activator</Bundle-Activator>
                        **<Import-Package>
                        !javax.xml.namespace,*
                        </Import-Package>
                        <Export-Package>
                        com.**.recruitment.client,
                        com.**.recruitment.ws
                        </Export-Package>
                        <Embed-Dependency>*;scope=compile|runtime</Embed-Dependency>
      ...
      ...
            </plugin>

A: Instruction: <Import-Package>!javax.xml.namespace, *</Import-Package>
avoids package javax.xml.namespace being imported which is the opposite you need. Just remove !
Make sure javax.xml.namespace package is exported in your OSGi environment: It should be by default in any case you can try by setting this environment variable:
org.osgi.framework.system.packages.extra=javax.xml.namespace;<other  packages>


text:
Q: Differential $\sqrt{1+B(x,x)}$ map in $C^*$-algebra Let $A$ is $C^*$-algebra and $P \subset A$ is subset of all elements $a \in A$ such that $a > 0$ (nonnegative) and $||a|| < \frac{1}{\sqrt{1-q}}$ (norm bounded) for some $0 < q < 1$.
Let $F : P \to A$, $F(x) = \sqrt{1+B(x,x)}$ where $B : A \times A \to A$ - is sesquilinear with norm $q$, and suppose that $B$ such that $1+B(x,x)>0$ when $x \in P$. What is Frechet derivative of $F$?


text:
Q: Why the animation of a function gives different results from the integral? My function is:
A1[B_, x_, t_] := (AiryAi[B*(x - (B^3*t^2)/4)])^2

(B is a constant) and if I use "Manipulate" :
BB1[t_] := Plot[Re[A1[1, x, t]], {x, -20, 22}, PlotRange -> {{-20, 22}, {-0.5, 2}}, AxesOrigin
-> {0, 0}, Axes -> None, Frame -> True, FrameTicks -> None, FrameLabel -> {Style["x", Italic],
Row[{"|", Style["\[Psi]", Italic], "(", Style["x", Italic], ")\!\(\*SuperscriptBox[\(|\), \
(2\)]\)"}]}, AspectRatio -> .25, ImageSize -> {550, 175}]

Manipulate[BB1[t], {{t, 0, "time"}, 0, 5, PerformanceGoal -> "Quality", PlotPoints ->
ControlActive[500, 150], MaxRecursion -> 2,
Appearance -> "Labeled"}]

I can see that this function remains unchanged in form. Therefore, the integral of this function from -Infinity to Infinity should be constant for different values of t. However, when I calculate the integral:
F1[B_, t_] := Re[NIntegrate[A1[B, x, t], {x, -\[Infinity], \[Infinity]}, Method ->
 "DoubleExponential", WorkingPrecision -> 20, AccuracyGoal -> 5, MaxRecursion -> 20]]

and then try different values for t (B is a constant and it can be equal to 1), it comes out that F1 is not a constant value. Why does this happen?

A: Don't know which problems arise using Plot.
Here a workaround:
First add , MaxIterations -> 1000 in the definition of ProfitRandomization[..., MaxIterations -> 1000]
Second enclose your codee with Module
Third try
Module[{tab},
 Manipulate[
  tab = Table[{CMax,
     ProfitRandomization[p, \[Gamma], \[Delta], \[Alpha],
      CMax]}, {CMax, 0 , 1, .1}];
  ListPlot[tab]
  , {{\[Delta], .317}, 0.01, .9999}, {{\[Alpha], 67.1}, .01,
   100}, {{p, 2.62}, .01, 10}, {{\[Gamma], 195.706}, 1, 10000} ,
  SynchronousUpdating -> False]]

Code runs quite slow but updates ListPlot as expected.
Hope it helps!

A: I get this from Integrate:
Integrate[A1[1, x, 0], {x, -\[Infinity], \[Infinity]}]

Integrate::idiv: Integral of AiryAi[x]^2 does not converge on {-\[Infinity],\[Infinity]}.

Another check:
Integrate[A1[1, x, 0], {x, -A, 0}, Assumptions -> A > 0]
Limit[%, A -> Infinity]

(*  A AiryAi[-A]^2 + AiryAiPrime[-A]^2 - 1/(3^(2/3) Gamma[1/3]^2)  *)
(*  \[Infinity]  *)

It seems the integral diverges.


text:
Q: vba insert range into a specific column Dim CopyRng As Range
LastR = LastRow(Sheets("Sheet3"))
startrow = 1
startrow = startrow + 1
Set CopyRng = Sheets("Sheet3").Range(Sheets("Sheet3").Rows(1), Sheets("Sheet3").Rows(LastR))

    'insert copied data in Sheet3 onto inserted rows
    CopyRng.Copy ActiveSheet.Cells(startrow, 2)

Trying to insert CopyRng into column B, when running the code CopyRng ends up in column A

A: your code is not complete, so I guess you could be after something like follows:
With Sheets("Sheet3") '<--| reference "Sheet3"
    ... your other code

    Set CopyRng = Intersect(.UsedRange, .Range(.Rows(1), .Rows(LastR))) '<--| set 'CopyRng' to a "finite" range (not an entire row)

        'insert copied data in Sheet3 onto inserted rows
        CopyRng.Copy ActiveSheet.cells(startrow, 2) '<--| paste the "finite" range in Activesheet

        ... your other code
End With


text: Q: How to install Microsoft Teams and login to it automatically using PowerShell I'm trying to write a script that will open Microsoft Teams app and login to it automatically. The plan is to automate our process so we do not have to type the email and the password for each computer setup. I tried the Connect-Microsoft Teams command but that will login to Teams in PowerShell not in Teams app. When I open the app it still asking me for credentials.


text:
Q: Submit button fires twice I have the following submit:
 <input type="submit"  id="buttonNext" name="buttoncrd"  value="Prosegui" class="buttonNavProsegui block-ui"/>

When you are on the page, i want to active the submit with the keyboard button "Entry" so i made this simple  js code:
$(document).ready(function() {
    $(document).keypress(function(event){
       if (event.which == 13){
           $("#buttonNext").click();
        }
    });
});

It works correctly but i met some problem when i have the focus on the submit AND i press Enter on the keyboard. I fear that the submit fires twice, can you help me disable one submit when is focused?

A: You can use
 $(document).ready(function() {
    $(document).keypress(function(event){
       if (event.which == 13){
           $("#buttonNext").click();
           event.preventDefault();
        }
    });
});

It will not trigger twice.

A: $("#buttonNext").addEventListener('keypress', e => {
  e.stopPropagation()
})

might do the trick. It prevents the event from propagating up in the hierarchy when a keypress event happens on the button.


text:
Q: Multiple JSONObject jo I need multiple JSONObject jo
I want to show two array each in two text
Example :
                                String objectno = jo.getString("table1");
                                String objectno = jo2.getString("table2");
Code
public class MainActivity extends Activity {

String url = "url";
ProgressDialog PD;

ArrayList<String> countries;

ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView=(ListView)findViewById(R.id.list);
    countries=new ArrayList<String>();

    adapter = new ArrayAdapter(this,R.layout.items, R.id.tv, countries);

    listView.setAdapter(adapter);

    //countries = new ArrayList<String>();

    PD = new ProgressDialog(this);
    PD.setMessage("Loading.....");
    PD.setCancelable(false);

    MakeJsonArrayReq();
}

private void MakeJsonArrayReq() {
    PD.show();

    JsonArrayRequest jreq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject jo = response.getJSONObject(i);
                            String objectno = jo.getString("objectno");
                            countries.add(objectno);

                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }
                    PD.dismiss();
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });

    MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}

}
I need get ,

String objectno = jo.getString("objectno");

//AND
 String objectno = jo.getString("drivername");
LAYOUT ITEMS:
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:src="@drawable/iconlist" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:paddingTop="6dp"/>

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

please need assitance.


text:
Q: Why only 6 php fastcgi workers loaded on IIS 8 I resize picture on the fly 1 per request via imagick. Every request I create
new imagick object, read original file, resize it and return to browser. This is not faster way but I don't want use cache.
I always waiting until 6 workers will end resizing process for the start next new 6 images.

Max number of php fastcgi workers is 6. And I don't like big queue time.
What can I do with it? Is this fastcgi primary problem?
IIS 8.5, php 5.6 win server 2012

A: It look like windows is to blame, no fix. I have same problem on Windows Server 2012 R2 but i found this https://stackoverflow.com/a/3476927/4866851


text:
Q: Perl sprintf integer issue With this line, I expect the output 201
$ perl -e '$e = '2.01'; $c = sprintf("%d", $e * 100); print $c;'

But I get 200 instead. I don't understand why.

A: Because of the binary representation of a float number.
Try:
perl -e '$e = 2.01;printf("%2.25f\n",$e);'

Output:
2.0099999999999997868371793

The intetger part of this number multiplied by 100 gives 200

A: perl -e 'my $e = "2.01"; my $c = sprintf("%.0f", $e * 100); print $c;'

With %d, the integer is truncated.
And if you don't bother with printf :
perl -e 'my $e = "2.01"; my $c = $e * 100; print $c;'

A: Floating point representation has a limit to its accuracy, and the binary representation of 2.01 just happens to be fractionally less than 2.01.
The %d format conversion truncates the value to the next lowest value. It actually does a call to int, whose documentation says

You should not use this function for rounding: one because it truncates towards 0 , and two because machine representations of floating-point numbers can sometimes produce counterintuitive results.

And int(200.99999999999) is 200, which is what you are getting.
The canonical way in Perl to get the closest integer to a floating point value is to use the %f conversion with zero decimal points. So if you write instead
perl -e '$e = '2.01'; $c = sprintf("%.0f", $e * 100); print $c;'

you will get the output
200

A: Following document mentions about floating point and binary representation. This is from python.org, but it also works for perl.
https://docs.python.org/3/tutorial/floatingpoint.html
$ perl -e 'if (2.01 + 2.01 + 2.01 == 6.03) { print "yes" } else { print "no" }'
no

You can try using bignum pragma as a makeshift:
$ perl -Mbignum -e '$e = "2.01"; $c = sprintf("%d", $e * 100); print $c;'
201


text:
Q: How to prove $\dim ( \hom(V_1, ..., V_p ; U) ) =\dim(V_1) \cdot .... \cdot \dim(V_p) \cdot \dim(U)$ by induction?
Let the set $\hom(V_1, ..., V_p ; U) $ be the set of all p-linear maps
  from the space $V_1 \times ... \times V_p \to U$, then we have  $$\dim
 ( \hom(V_1, ..., V_p ; U) ) = \dim(V_1) \cdot .... \cdot \dim(V_p) \cdot
 \dim(U)$$

I know that the maps in the space $\hom(V_1, ..., V_p ; U)$ are determined by by the images of the basis of the spaces $V_1 \times ... \times V_p $, so combinatorially one can easily prove the above theorem.However, I was wondering, how can we prove it by induction if it is possible ?

A: You could prove that for any $k$, $V_1,\dots, V_k$ and $U$, $\dim (\hom (V_1,\dots,V_k;U))=\dim(V_1) \cdot \dim (V_2,\dots,V_{k};U)$. Then you prove by (bounded) induction on $k$ that $\dim (\hom (V_1,\dots,V_p;U))=\left(\prod\limits_{i=1}^k \dim (V_k)\right)\dim (\hom (V_{k+1},\dots, V_p;U))$. The case $k=0$ is trivial, $k \implies k+1$ is the previous property, and $k=p-1$ gives you your result (up to $\dim (\hom(A;B))=(\dim A)\cdot (\dim B)$).

You could also prove the more general fact that $\hom (V_1,\dots,V_p;U)\cong \hom (V_1; \hom (V_2,\dots,V_p;U))=V_1\to_L \hom (V_2,\dots,V_p;U)$ (where  $A\to_L B$ means $\hom (A;B)$). Then, you prove by induction that $\hom (V_1,\dots,V_p;U)\cong V_1\to _L \dots \to_LV_p \to_L U$. You recover the previous result by using the fact that $\dim (A\to_L B) = (\dim A)\cdot (\dim B)$. This property is stronger and I would therefore prefer this version but the fact that $\to_L$ is not associative makes notations a bit more annoying.

Another way would be to use tensor products. $\hom(V_1,\dots ,V_p;U)\cong\hom (V_1\otimes V_2,V_3,\dots, V_p;U)$. Then again, by induction, $\hom(V_1,\dots ,V_p;U)\cong \hom (V_1 \otimes \dots \otimes V_p;U)$ and you can conclude using $\dim (\hom (A;B))=(\dim A)\cdot (\dim B)$ and $\dim (A\otimes B)=(\dim A)\cdot (\dim B)$. The tensor product tends to be introduced a bit later in courses, but if you know it, I'd say that this is the "best" proof.


text:
Q: Click function not working inside div, but works outside I'm having a strange problem where my jQuery code will execute just fine outside of #panel but not in it.
The code below toggles #panel. When a.close_panel is clicked, nothing happens, no console log and the div does not hide. When I a.close_panel outside #panel, it works as expected. Essentially, jQuery interactions are not working in any way when coming from inside #panel.
Any help would be appreciated.

        close X

        Show Panel

$(document).ready(function() {
    $( "a.show_panel" ).click( function(e) {
        e.preventDefault();

        // Show Panel
        $( "#panel" ).show();
        console.log( "show" );
    });

    $( "a.close_panel" ).click( function(e) {
        e.preventDefault();

        $( "#panel" ).hide();
        console.log( "hide" );
    });
});

#panel {
    display: none;
    position: fixed;
    overflow-y: scroll;
    top: 0;
    right: 0;
    padding: $gap/2;
    background-color: $white;
    z-index: 999;
}


text:
Q: Is it possible to implement In-App Purchases only for a subset of countries? Is there a way to use In-App Purchases such that they're NOT available in the USA, and at the same time figure out if they're available or not - and if not, perform special tasks for customers in the USA who can't use them?

A: You could use CLLocationManager to find the users location and then use MKReverseGeocoder to figure out what country they are in.
Some people will deny access to location information. As a backup you could use the language that the current device is in (but there are some obvious issues with this approach):
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes

Then you just need to use a conditional statement:
if(in USA){
  do whatever, don't allow in-app purchases
} else {
  allow in app purchases
}

A: Perhaps you could send a product request in the background, and only display the purchase button if something comes back. The drawback is that there could be issues (store outages, network issues, you take the product down temporarily) that would make the product request fail, so you'd have to design the alternative UI appropriately.
SKProductsRequest *productRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productId]];
productRequest.delegate = self;
[productRequest start];

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    if ([[response products] count] > 0) {
        // display purchase link
    } else {
        // display alternative UI
    }
}


text:
Q: How can I determine if the desktop window is visible in Xfce? I have a Conky script that I always update to increase the delay before it starts. The delay has to be at least how long it must wait till the background is displayed otherwise Conky is hidden behind the wallpaper. Bad.
Now that is to happen when I log on. When I am already logged on I would like the script not to wait but start immediately.
My desktop environment is Xfce 4.12 on Manjaro 16. Is there a way to reliably determine when the desktop is ready/visible?

EDIT: Following Edgar Gril's answer, I've updated my script. It reads as follows:
#!/bin/sh

# Try to detect screen width to correctly position Conky
# to the right of the first monitor
eval $(xdpyinfo | sed -e '/screen\s\+#0/,+1!d' \
    -e '/screen/d' \
    -e 's@\s\+dimensions:\s\+\([0-9]\+\)x\([0-9]\+\).*@WIDTH=\1; HEIGHT=\2@g') 2>/dev/null \
    || WIDTH=1920

# Wait till the desktop window is ready (more or less)
# Method 1:
#while ! xwininfo -name Bureau 2>&1 > /dev/null; do sleep 1s; done
# Method 2:
while ! xwininfo -tree -root | \
    grep -qE '\("xfdesktop"\s+"\w+"\)\s+'${WIDTH}x${HEIGHT}'\+0\+0'; \
do sleep 1s; done

cd $HOME/.conky
exec /usr/bin/conky ${WIDTH:+-x $WIDTH -y 48} "$@"

It's saved as /usr/local/bin/conky.sh and is typically called as follows from .config/autostart:
conky.sh -p 2 -q -c ringrc

with 2 seconds being not enough in this case.

A: Knowing that the desktop wallpaper could be a child window created by xfdesktop, a lead to follow could be exploring the content of the X windows list with the command:
xwininfo -tree -root

excerpt of the output ("Scrivania" simply meaning "Desktop" in english):
    0x800744 (has no name): ()  4x538+736+30  +755+50
    0x800743 (has no name): ()  4x541+0+30  +19+50
 0x8005f9 (has no name): ()  1920x1080+0+0  +0+0
    16 children:
    0x1400003 "Scrivania": ("xfdesktop" "Xfdesktop")  1920x1080+0+0 +0+0
       1 child:
       0x1400004 (has no name): ()  1x1+-1+-1  +-1+-1
    0x800608 (has no name): ()  1x1+0+0  +0+0
    0x800607 (has no name): ()  1x1+0+0  +0+0

Following this hypothesis it is relatively simple in your script to check if the window belonging to xfdesktop exists and/or has children


text:
Q: Display a text file onto a text block which is already within the app I have a text file in an app. Can someone please explain, algorithmically, how would I display the contents of the file on a text block.
PS: I would be obliged if you didn't downvote this question as I'm banned from questioning further and trying to rectify my mistakes. Thank you, good sir.

A: This code loaded file from your project directory and show it in TextBlock with a name textBlock
var rs = Application.GetResourceStream(new Uri("file.txt", UriKind.Relative));
StreamReader sr = new StreamReader(rs.Stream);
textBlock.Text = sr.ReadToEnd();

Where file.txt saved like Content in your project


text:
Q: Podcasts missing from new blog The blogs used to have links to the old Joel & Jeff Stack Overflow podcasts. These are now all gone. Instead, there is now a sad and dismal [display_podcast] line at the bottom; see podcast #41 for example.
Can these be reinstated please?
To be clear, these are not the new Stack Exchange podcasts which were started much later and are embedded into blog pages with a SoundCloud widget.


text:
Q: org.springframework.data.mapping.model.MappingException: Cannot use a complex object as a key value am working with spring boot and mongoDB. have written the repository for my model and have written my own logic to increment id by using mongo inc.  while doing

gradle test

the tests are failing with the following exception.
org.springframework.data.mapping.model.MappingException: Cannot use a complex object as a key value.
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeMapInternal(MappingMongoConverter.java:669)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createMap(MappingMongoConverter.java:585)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:471)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:430)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:418)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:322)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:418)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:392)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:356)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:79)
at org.springframework.data.mongodb.core.MongoTemplate.toDbObject(MongoTemplate.java:853)
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1014)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:963)
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy94.save(Unknown Source)
at org.springframework.data.repository.CrudRepository$save.call(Unknown Source)
at com.auth.mongo.impl.ApplicationRepositoryImpl.save(ApplicationRepositoryImpl.groovy:26)
at com.auth.repository.ApplicationRepository$save$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)

can any one suggest me what am doing wrong
EDIT:
FOR Example: Application Class is the domain
class Application implements Serializable {

String id
APIKey apiKey
Map actions = [:]

Application() {
}

Application(APIKey apiKey) {
    this.apiKey = apiKey
    List customerActionsList = [] // added some actions
    actions.put(Role.User, customerActionsList)
}

APIKey:
String apiKey
String application
DateTime whenCreated
boolean active

APIKey() {
}

APIKey(String application, DateTime whenCreated, boolean active) {
    this.apiKey = generateAPIKey(application)
    this.application = application
    this.whenCreated = whenCreated
    this.active = active
}

repository class is as follows:
@Component
class ApplicationRepositoryImpl implements ApplicationRepository {

private final Logger logger = LoggerFactory.getLogger(ApplicationRepositoryImpl.class)

@Autowired
ApplicationRepositoryMongo applicationRepositoryMongo

@Autowired
SequenceRepository sequenceRepository

@Override
Serializable save(Application application) {
    application.id = application.id?:sequenceRepository.getNextSequenceId(Application.simpleName).sequence
    return applicationRepositoryMongo.save(application).id
}

@Override
Application find(String id) {
    return applicationRepositoryMongo.findOne(id)
}

I am incrementing the id of Application class as follows
public SequenceId getNextSequenceId(String type) {
    //get sequence type
    Query query = new Query(Criteria.where("id").is(type))
    //increase sequence id by
    Update update = new Update()
    update.inc('sequence', 1)
    //return new increased i
    FindAndModifyOptions options = new FindAndModifyOptions()
    options.returnNew(true)
    //this is the magic happened
    SequenceId seqId = mongoOperation.findAndModify(query, update, options, SequenceId.class)
    return seqId
}

While saving the domain object getting the above exception. I have done all mongo configuration. the configuration is working for other domains.

A: There's an open Improvement in Spring Don't require Converters for Complex classes that are used as Ids. Currently Spring decided to not support it.

decided not to support it at all


text:
Q: Call same function on multiple urls django urls.py
 url(r'^level/ajax/reload/$', views.ajax_change_status,
 name='ajax_change_status'),
 url(r'^level/(\d+)/ajax/reload/$', views.ajax_change_status,
 name='ajax_change_status'),
 url(r'^level/(\d+)/(\d+)/ajax/reload/$', views.ajax_change_status,
 name='ajax_change_status'),

In my urls.py i have these urls.Im trying to call an ajax function in my view basically to update the notification badge to 0 after user clicks on the bell icon.The notification badge is in the base.html template.Im calling the url with the name "ajax_change_status" . I want all these urls to call the same ajax funtion.Is it possible to do this or is there a better way?Im getting a 500 server error when i click on the bell icon from the second and third url
My ajax function in views.py:
def ajax_change_status(request):
  if request.is_ajax():
   try:
     Notification.objects.filter(receiver=request.user)
     .update(viewed=True)
     Addnotify.objects.filter(receiver=request.user)
     .update(viewed=True)
     FollowNotify.objects.filter(receiver=request.user)
     .update(viewed=True)
     HubNotify.objects.filter(receiver=request.user)
     .update(viewed=True)
    return JsonResponse({"success": True})
   except Exception as e:
      print(e)
      return JsonResponse({"success": False})

My ajax jquery:
var clicks = 0;

 $("#notify").on('click', function () {

    $.ajax({
    url: 'ajax/reload/',
    data: {
     },

    success: function (data) {

      if (data.success) {
                    console.log('ajax call  success.');

        $('#badge').html('0')
        $('#headnotify').html('NOTIFICATIONS (0)')
        // here you update the HTML to change the active to innactive
      }else{
        console.log('ajax call not success.');
      }
    clicks++;
    }
    });
   });

Seems like it is not getting into the ajax function when i try it on the second and third url!!

A: Each one of those urls should have different names. It's going to be pain to allow for optional url arguments. You'll be much better off (and more sane) if you just name them differently. Your view function probably should allow for those to be passed in though, otherwise what's the purpose of them?
def ajax_change_status(request, param1=None, param2=None):
    ...

And personally I like using keyword arguments as it better explains the url path, but that's up to you.


text:
Q: Changing Property Attributes Via Utility functions I have following piece of JavaScript code
function freezeProps(o) {
var props = (arguments.length == 1) // If 1 arg
? Object.getOwnPropertyNames(o) // use all props
: Array.prototype.splice.call(arguments, 1); // else named props
props.forEach(function(n) { // Make each one read-only and permanent
// Ignore nonconfigurable properties
if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
Object.defineProperty(o, n, { writable: false, configurable: false });
});
   return o; // So we can keep using it
}

// Make the named (or all) properties of o nonenumerable, if configurable.
  function hideProps(o) {
  var props = (arguments.length == 1) // If 1 arg
  ? Object.getOwnPropertyNames(o) // use all props
  : Array.prototype.splice.call(arguments, 1); // else named props
   props.forEach(function(n) { // Hide each one from the for/in loop
  // Ignore nonconfigurable properties
   if (!Object.getOwnPropertyDescriptor(o,n).configurable) return;
   Object.defineProperty(o, n, { enumerable: false });
  });
     return o;
   }

 function Range(from, to) { // Constructor for an immutable Range class
      this.from = from;
      this.to = to;
       freezeProps(this); // Make the properties immutable
 }

Range.prototype = hideProps({ // Define prototype with nonenumerable   properties
 constructor: Range,
 includes: function(x) { return this.from <= x && x <= this.to; },
  foreach: function(f) {for(var x=Math.ceil(this.from);x<=this.to;x++)    f(x);},
  toString: function() { return "(" + this.from + "..." + this.to + ")"; }
 });

  var range = new Range(10, 12);
  var result = range.includes(10.9666);
  alert(result);

What I'm not able to understand in both the functions freezeProps() and hideProps() is that lets say that I pass in more than one argument to hideProps(arg1,arg2,arg3) then
  arguments.length != 1

and  the following line of code will be executed
 var props =  Array.prototype.splice.call(arguments, 1);

But props will contain a resulting array like [arg2,arg3] if that is the case then how come one can still change named properties (as is clear from the comments in the code) on object arg1 to nonenumerable. This is not making sense to me. Any suggestions will be highly appreciated.


text:
Q: require is not replaced by webpack-specific require (__webpack_require__) After upgrading to webpack 5, I am noticing that some of my build files contain plain require statements. As a result, I am getting ReferenceError: require is not defined. For some reason, Webpack is not converting those requires to the webpack-specific webpack_require
I compared my webpack 4 bundle to my webpack 5 bundle. The Webpack 4 bundle clearly replace require with webpack_require as shown in the images below
Webpack 4 bundle showing line 63 require is transpiled to webpack_require
Similar case in some other file
My Webpack 5 configuration simply contains plain require statement which gives me error in browser because require is not defined there.
The require here is not transpiled by webpack 5
Similar case in some other file Webpack5
I have tried switching my babel-preset-env options and it doesn't solve the problem. I have checked my package.json and webpack config do not specify any "type" key. The code that is present in the images and giving me errors is coming from terriajs-cesium package. The following is my webpack configuration (For simplicity, I have removed all css and style loaders along with static loaders):
'use strict';

/*global require*/
var configureWebpackForTerriaJS = require('terriajs/buildprocess/configureWebpack');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var path = require('path');
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
// const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function(devMode, hot) {
    var config = {
        mode: 'development',
        entry: './entry.js',
        output: {
            path: path.resolve(__dirname, '..', 'wwwroot', 'build'),
            publicPath: hot ? 'http://localhost:3003/build/' : 'build/',
            filename: "MAP.js"
        },
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    include: [
                        path.resolve(__dirname, '..', 'index.js'),
                        path.resolve(__dirname, '..', 'entry.js'),
                        path.resolve(__dirname, '..', 'lib')

                    ],
                    use:{
                        loader: 'babel-loader',
                        options: {
                            sourceMap: false, // generated sourcemaps are currently bad, see https://phabricator.babeljs.io/T7257
                            presets: ["@babel/preset-env", '@babel/preset-react'],
                            plugins: [
                                'babel-plugin-jsx-control-statements',
                                '@babel/plugin-transform-modules-commonjs'
                            ]
                        }
                    }
                },
               // some assets and css rules
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({filename: "MAP.css", ignoreOrder: true}),
            new NodePolyfillPlugin(),

        ],
       resolve: {
            alias: {},
            modules: ['node_modules']
        }
    };
   // The following line sends this config to a file in our core project to further
   // add rules. This core project contains an npm package that spits out the require
   // error.

    return configureWebpackForTerriaJS(path.dirname(require.resolve('CORE PROJECT DIRECTORY')), config, devMode, hot, MiniCssExtractPlugin);
};

The following is the code in configureWebpack.js which is part of our core project:
var path = require('path');
var webpack = require('webpack');

function configureWebpack(terriaJSBasePath, config, devMode, hot, MiniCssExtractPlugin, disableStyleLoader) {
    const cesiumDir = path.dirname(require.resolve('terriajs-cesium/package.json'));

    config.resolve = config.resolve || {};
    config.resolve.extensions = config.resolve.extensions || ['*', '.webpack.js', '.web.js', '.js'];
    config.resolve.extensions.push('.jsx');
    config.resolve.alias = config.resolve.alias || {};
    config.resolve.modules = config.resolve.modules || [];
    config.resolve.fallback = {
        fs: false,
    }

    config.resolve.modules.push(path.resolve(terriaJSBasePath, 'wwwroot'));
    config.module = config.module || {};
    config.module.rules = config.module.rules || [];

    // Use Babel to compile our JavaScript files.
    config.module.rules.push({
        test: /\.(js|jsx)$/,
        include: [
            path.resolve(terriaJSBasePath, 'lib'),
            path.resolve(terriaJSBasePath, 'test'),
        ],
        use: {
            loader: require.resolve('babel-loader'),
            options: {
                sourceMap: false, // generated sourcemaps are currently bad, see https://phabricator.babeljs.io/T7257
                presets: ["@babel/preset-env", '@babel/preset-react'],
                plugins: [
                    'babel-plugin-jsx-control-statements',
                    '@babel/plugin-transform-modules-commonjs',
                    '@babel/plugin-syntax-dynamic-import'
                ]
            }
        }

    });

    config.module.rules.push({
        test: /\.xml$/,
        include: path.resolve(terriaJSBasePath, 'lib', 'Models'),
        type: 'asset/source'
    });

    config.module.rules.push({
        test: /\.json|\.xml$/,
        include: path.resolve(cesiumDir, 'Source', 'Assets'),
        type: 'asset/resource'
    });

    config.module.rules.push({
        test: /\.js$/,
        include: path.resolve(path.dirname(require.resolve('terriajs-cesium/package.json')), 'Source'),
        loader: require.resolve('./removeCesiumDebugPragmas')
    });

    // Don't let Cesium's `buildModuleUrl` see require - only the AMD version is relevant.
    config.module.rules.push({
        test: require.resolve('terriajs-cesium/Source/Core/buildModuleUrl'),
        loader: 'imports-loader'

    });

    // Don't let Cesium's `crunch.js` see require - only the AMD version is relevant.
    config.module.rules.push({
        test: require.resolve('terriajs-cesium/Source/ThirdParty/crunch'),
        loader: 'imports-loader'
    });

    config.devServer = config.devServer || {
        stats: 'minimal',
        port: 3003,
        contentBase: 'wwwroot/',
        proxy: {
            '*': {
                target: 'http://localhost:3001',
                bypass: function (req, res, proxyOptions) {
                    if (req.url.indexOf('/proxy') < 0 &&
                        req.url.indexOf('/proj4lookup') < 0 &&
                        req.url.indexOf('/convert') < 0 &&
                        req.url.indexOf('/proxyabledomains') < 0 &&
                        req.url.indexOf('/errorpage') < 0 &&
                        req.url.indexOf('/init') < 0 &&
                        req.url.indexOf('/serverconfig') < 0) {
                        return req.originalUrl;
                    }
                }
            }
        },
    };

    config.plugins = (config.plugins || []).concat([
        new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/})
    ]);

    config.resolve = config.resolve || {};
    config.resolve.alias = config.resolve.alias || {};
    config.resolve.alias['react'] = path.dirname(require.resolve('react'));
    config.resolve.alias['react-dom'] = path.dirname(require.resolve('react-dom'));

    return config;
}

module.exports = configureWebpack;

I do not understand why Webpack is not transpiling these require statements.


text:
Q: Apparent altering of Tex Live Utility's "umask" Yesterday, I installed the TeX Live Utility update to version 1.15. After downloading and installing and relaunching TeX Live Utility, I got the following message:

You have altered the system's umask
The normal umask is 022 and yours is set to 022. This more restrictive
umask may cause permission problems with TeX Live.

I have three questions:

*

*What exactly is a umask?

*Should I be concerned about this message? (I've never done anything, as far as I'm aware, to alter the umask, so I'm not sure why I'm getting this message to begin with.)

*And, finally, as far as I can tell "022" is the exact same as "022", so does anyone have any idea why I might be getting this message?


text:
Q: How do I find out what Firestore snapshot listeners are still active in my iOS app? I'm currently implementing snapshot listeners in my app, and want to print out a list of active listeners (in my Firebase console I see that I have 2, but it doesn't have any more data than that). Is there a property in my iOS app that I can access or print to find out?

A: No. You should record for yourself which listeners are active at any given moment.  You might want to consider writing a wrapper library for yourself to make this easier to apply to your entire app.


text:
Q: C# can't read emails with webdav and fba Summary:
I am having trouble connecting to an exchange 2007 mailbox that is running FBA with my C# code using webdav.
Details:
This code below has to work against an exchange 2007 server, connect, and read email from a mailbox.
I've tried EWS but it made no sense and I couldn't get it working.
Below is my code. I am using the outlook url to get the cookies I need to login via webdav to the exchange url.
Error:

440 login timeout on the request.

Area where my code breaks:
Response = (HttpWebResponse)Request.GetResponse();

Code:
namespace logintomailbox
{
    class Program
    {
        #region auth dont exapnd
        //Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C#
        internal static string dUser = "user";
        internal static string dDomain = "domain";
        internal static string dPassword = "password";
        #endregion
        internal static string MailBoxAliasName = "mailbox;
        internal static string ExchangeServerName = "appews.host.com";
        internal static string outlookServerName = "outlook.host.com";
        internal static string ReadAttachments = "1"; //1 means read attachments, 0 means dont
        internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from

        static void Main(string[] args)
        {
            //FBA code
            //once i get a 302 response code i am authenticated
            DoExchangeFBA("https://" + outlookServerName, dDomain + "/" + dUser, dPassword);

            //login via webdav
            QueryMailBoxViaDAV();

            //exit application
            //ExitProgram((int)ExitReturnCodes.NormalShutdown);
        }
        private static void QueryMailBoxViaDAV()
        {
            //create http web request object
            System.Net.HttpWebRequest Request;
            //Request.CookieContainer = newCookieContainer();
            //create http web response object
            System.Net.WebResponse Response;

            //create needed components of web request/response
            byte[] bytes = null;
            System.IO.Stream RequestStream = null;
            System.IO.Stream ResponseStream = null;
            XmlDocument ResponseXmlDoc = null;
            string strRootURI = null;

            //check if exchange server is 2007 or 2003
            if (ExchangeServerName == "appews.host.com")
            {
                //exchange 2007
                strRootURI = "https://" + ExchangeServerName + "/exchange/" + MailBoxAliasName;
            }
            else
            {
                //exchange 2003
                //example of previously used url for exchange 2003 mailboxes
                strRootURI = "https://" + ExchangeServerName + "/exchange/" + MailBoxAliasName + "/Inbox";
            }

            //begin webdav query
            string strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D=\"DAV:\" >"
                        + "<D:sql>SELECT \"DAV:displayname\", "
                        + "\"urn:schemas:mailheader:message-id\", "
                        + "\"urn:schemas:mailheader:date\", "
                        + "\"urn:schemas:mailheader:from\", "
                        + "\"urn:schemas:mailheader:to\", "
                        + "\"urn:schemas:mailheader:subject\", "
                        + "\"urn:schemas:httpmail:hasattachment\", "
                        + "\"urn:schemas:httpmail:textdescription\" "
                        + " FROM \"" + strRootURI + "\""
                        + "WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false "
                        + "AND \"urn:schemas:mailheader:date\" > CAST(\"" + MailBoxEarliestDateToRead.ToString() + "\" as \"dateTime.tz\")"
                        + "</D:sql></D:searchrequest>";

            //build http web request
            Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);
            Request.KeepAlive = false;
            Request.Credentials = new System.Net.NetworkCredential(
               dUser,
               dPassword,
               dDomain);
            Request.Method = "SEARCH";

            //now that everything is created try sending a request
            try
            {
                bytes = Encoding.UTF8.GetBytes((string)strQuery);
                Request.ContentLength = bytes.Length;
                RequestStream = Request.GetRequestStream();
                RequestStream.Write(bytes, 0, bytes.Length);
                RequestStream.Close();

                Request.ContentType = "text/xml";
                Request.KeepAlive = true;
                Response = (HttpWebResponse)Request.GetResponse();
                ResponseStream = Response.GetResponseStream();
                ResponseXmlDoc = new XmlDocument();
                ResponseXmlDoc.Load(ResponseStream);

                ResponseStream.Close();
                Response.Close();

                Console.WriteLine("Authentication Successful");
                Console.ReadLine();
            }
            //catch all exceptions and sent to console if they occur
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.ReadLine();
            }
        }
        private static CookieCollection DoExchangeFBA(string server, string userName, string password)
        {

            var uri = server + "/owa/auth/owaauth.dll";

            var request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = "POST";
            request.CookieContainer = new CookieContainer();
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = false;
            request.ServicePoint.Expect100Continue = false;

            server = HttpUtility.UrlEncode(server);
            userName = HttpUtility.UrlEncode(userName);
            password = HttpUtility.UrlEncode(password);
            var bodyString = "destination={0}&flags=0&username={1}";
            bodyString += "&password={2}&SubmitCreds=Log+On&";
            bodyString += "forcedownlevel=0&trusted=0";
            bodyString = string.Format(bodyString, server,
                                        userName, password);

            var body = Encoding.ASCII.GetBytes(bodyString);

            request.ContentLength = body.Length;
            ServicePointManager.Expect100Continue = false;

            var stream = request.GetRequestStream();
            stream.Write(body, 0, body.Length);
            stream.Close();

            //Console.WriteLine((HttpWebResponse)request.GetResponse());

            var response = (HttpWebResponse)request.GetResponse();

            if (response.Cookies.Count < 2) throw
                new AuthenticationException("Failed to login to OWA!");
            return response.Cookies;
        }
    }
}

A: The server issues a HTTP/1.1 440 Login Timeout, whenever FBA is enabled and there is a HTTP request or a WebDav request made against exchange 2003/2007 ..Here's some sample code and here are details on FBA
Answer Source

A: HttpWebRequest pass credentials to next HttpWebRequest
How to insert CookieCollection to CookieContainer?
Why is one cookie missed?


text:
Q: Wirecloud and IDM server hiccup I linked wirecloud and Idm recently. When i login into wirecloud and i land into my wirecloud i got the following error:
Sorry, but the requested page is unavailable due to a server hiccup.
Our engineers have been notified, so check back later.

My idm configuration is:
URL
http://151.80.41.166:50002

Callback URL
http://151.80.41.166:50002/complete/fiware/

I cant get more error info
Exception Type:     AuthStateMissing
Exception Value:    Session value state missing.

Exception Location:     /usr/local/lib/python2.7/site-packages/social_core/backends/oauth.py in validate_state, line 90
Python Executable:  /usr/local/bin/python
Python Version:     2.7.14
Python Path:

['/opt/wirecloud_instance',
 '/usr/local/lib/python27.zip',
 '/usr/local/lib/python2.7',
 '/usr/local/lib/python2.7/plat-linux2',
 '/usr/local/lib/python2.7/lib-tk',
 '/usr/local/lib/python2.7/lib-old',
 '/usr/local/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/site-packages']

A: The problem was i got in the same machine idm and Wirecloud and they use the same cookie.
I add the follow lines on settings.py
SESSION_COOKIE_NAME = "wcsessionid"
CSRF_COOKIE_NAME = "wccsrftoken"


text:
Q: JSON Decode Error when requesting JSON response from Google I'm trying to get my head around the requests python package
import requests

url = "https://www.google.com/search?q=london"

response = requests.get(url, headers={"Accept": "application/json"})

data = response.json()

And i'm receiving the following error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
However this code does work with some other websites.. is there a reason this would error on specific websites and is there a way around it? For example if i wanted the search results when searching London on Google?
Thanks

A: response.json() does not convert any server response to a JSON, it simply parses 'stringified' JSONs. So if the server returns a string that is not a JSON, then this will throw a decode error.
Some servers do return JSON objects, in which case your code will work. In the case of https://www.google.com/search?q=london this actually returns HTML code (as you would expect since it's a webpage).
You can test this by printing the response:
print(response.text)

which outputs:
# some very long output that ends with:
...();})();google.drty&&google.drty();</script>

Notice the  tag at the end? So this cannot be parsed into a JSON.
So how do you parse this into a usable HTML? You can use beautiful soup:
import requests
from bs4 import BeautifulSoup

url = "https://www.google.com/search?q=london"

response = requests.get(url, headers={"Accept": "application/json"})

soup = BeautifulSoup(response.text)

print(soup.prettify())


text:
Q: exc_bad_access even with starship example project I'm trying to create my first iOS game, but I have a weird problem. When I try to launch my game on device, I get a "exc_bad_access". At first, I thought I was deleting something, or doing something wrong, but after great headaches, and figure out it cannot be something in my code, so I tried to create a vanilla SpriteKIT project (the one with rotating starships).
On Simulator all it's ok (as for my game), but, once run on device, the application crash with an exc_bad_access error on main. The problems seems to present whenever a "[self addChild: node]" it's called.
Any idea??? I'm running iOS 7.1 on my device and using Xcode 5.
Thank you!


text:
Q: How to do mod_rewrite for a url with parameters Given that i have the following url in my site: http://localhost/test/example.php?a=1&b=2
How can i specify a redirect rule in my .htaccess file, such that this url is called when i enter the following in my browser:  http://localhost/test/example/1.html
In other words, if a user enters the url: http://localhost/test/example/1.html, he should be displayed the page: http://localhost/test/example.php?a=1&b=2
I have tried the following mod_rewrite code in my .htaccess file, but it does not work:
RewriteRule ^/([^/]+).html /example.php?a=$1&b=$2 [QSA]

This is the code in my .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/? /example.php?a=$1&b=$2 [QSA]

Note: I am using WAMP2.0, Apache 2.2.6 and PHP 5.2.5

A: It does not work because you have an error in your rule, you must remove the slash at the beggining :
RewriteRule ^test/example/([0-9]+)\.html? /test/example.php?a=$1&b=2 [QSA]


text:
Q: Cannot populate fields in express and Mongodb I have two models Post and Users and I want to populate the posts fields
const PostSchema = new Schema({
    text: {
        type: String
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    }
})

const UserSchema = new Schema({
    username: {
        type: String,
    }
})

router.post('/', async (req,res) => {
    try {
        let joe = new User({username: "joe"})
        await joe.save()

        let postText = {text: "my name is joe", author: joe._id}
        let postByJoe = new Post(postText)
        await postByJoe.save()

        let users = User.find().populate('author')
        res.json({users})
    } catch (error) {
        console.log(error.message)
        res.json(error.message)
    }

})

The problem is that I get an error and I don't know what to make of it. I'm not sure at all what the issue is. Any help would be greatly appreciated
"Converting circular structure to JSON\n    --> starting at object with constructor 'NativeTopology'\n    |     property 's' -> object with constructor 'Object'\n    |     property 'sessionPool' -> object with constructor 'ServerSessionPool'\n    --- property 'topology' closes the circle"

A: What you have in your schema is different, you can only populate the  Schema.Types.ObjectId field in your schema. Seems you are trying to populate the author field of the Post model.
Replace this line let users = User.find().populate('author')  with this let users = Post.find().populate('user')  Your code should be like the one below:
router.post('/', async (req,res) => {
try {
    let joe = new User({username: "joe"})
    await joe.save()

    let postText = {text: "my name is joe", author: joe._id}
    let postByJoe = new Post(postText)
    await postByJoe.save()

   let data = await Post.find().populate('user')
    // map through the object returned
    const users = data.map((user) => user)
    res.json({users})
} catch (error) {
    console.log(error.message)
    res.json(error.message)
}

})

Read more about mongoose population here


text:
Q: Ignore columns in ActiveRecord I am trying to merge an old, legacy Rails 3 app into a more recent Django app.
Both apps used to use different databases, which are being merged into one unique database usable by both apps. The Django app will slowly take over the functionality of the old Rails app, starting with the migrations.
Django enforces strict database constraints in its migrations (e.g. NOT NULL fields with defaults). Any new fields on a table that is used by both apps will prevent Rails from updating records on that table, because ActiveRecord forcefully inserts NULL values instead of defaults.
Since we won't be adding new features to the Rails app, I'd like it to stick to a list of fields and ignore any newly-added fields.
The following answer using default_scope breaks other scopes, so I'd like to avoid it.
Triggers are an option, but I'm not keen on adding cruft to the Django app, just to deal with legacy code in the Rails app.
Hence : Can I manually define columns in my models instead of letting ActiveRecord inspect the database automatically?

A: You can accomplish what you want even in ancient versions of Rails (e.g. Rails 2.3) by overriding ActiveRecord::Base.columns:
class Model < ActiveRecord::Base
  def self.columns
    super.reject { |c| c.name.in?(['column1', 'column2']) }
  end
end

This is equivalent to ignore_columns in Rails 5.

A: Rails 5 solves your problem by providing ignore_columns option.
class User < ActiveRecord::Base
  self.ignored_columns = %w(employee_email)
end

User.columns will not give employee_email in the output.

A: You can use the ignorable gem if you are on a lower version of Rails
https://github.com/nthj/ignorable
ignore_columns :attributes


text:
Q: How to convert 24-hour time to 12-hour and send it through Django RestFramework
The above image shows 24 hours timing using angular.

The above image shows timing in 12 hours in the admin panel.

This is the model I want to fetch records sent to Angular
class Appointment(models.Model):

    service_requested = models.TextField()
    customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
    appointment_date_time = models.DateTimeField()

I tried this but I got a 24-hour time. Is there any way to convert time to 12-hours. and then send it
queryset = Appointment.objects.all()

Is it the correct way to convert time to 12-hour?
from datetime import datetime

queryset = Appointment.objects.all().annotate(

           date_time = datetime.strptime('appointment_date_time','%Y-%m-%d %I:%M %p')

           ).values('service_requested','customer','date_time')

A: It is simple, see this:
<td>{{book.appointment_date_time| date:'medium'}}</td>

In html file i just add template filter.
For more detail about the date format see this https://docs.angularjs.org/api/ng/filter/date


text:
Q: Column to nested list separated by / I have a column where each row element is serpearted by "/":
data.frame(column=c("a","a/air","a/aero/breath","b","b/boy","b/bag/band/brand"))

How can I convert it into nested lists after each "/". So the aim is to get:
list(a=list("air"=1,aero=list("breath"=1)),b=list("boy"=1,bag=list(band=list("brand"=1))))

I need this for the shinyTree package to make a tree out of the column.
I have added the "=1" at the end of the last elements in the hierarchy as it is required to show up in the shinyTree output. The list can then be put in the code below to get the tree:
library(shiny)
library(shinyTree)

tree <- list(a=list("air"=1,aero=list("breath"=1)),b=list("boy"=1,bag=list(band=list("brand"=1))))

typeof(tree)

ui <- fluidPage(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        actionButton('reset', 'Reset nodes')
      ),
      mainPanel(
        shinyTree("tree", ),
        hr(),
        "Selected nodes:",
        verbatimTextOutput("idSelected")#,
      )
    )
  )
)

server <- function(input, output, session) {

  treeSelection <- reactiveVal(list())

  output$tree = renderTree({
    tree
  })

  observeEvent(input$reset, {
    updateTree(session, "tree", data = tree)
    treeSelection(list())
  })

  observeEvent(input$tree, {
    treeSelection(get_selected(input$tree, format = "classid"))
  })

  output$idSelected <- renderPrint({
    treeSelection()
  })

}

shinyApp(ui, server)

A: Since the variables look like paths, I created the sample data as vector like
paths <- c(
  "a",
  "a/air",
  "a/aero/breath",
  "b",
  "b/boy",
  "b/bag/band/brand"
)

Then you can use the following function to get your nested list. I hope the choice of variablenames is explanatory enough.
pathsToNestedList <- function(x) {
  pathSplit <- strsplit(x,"/")
  pathStarts <- sapply(pathSplit,"[[",1)
  uniquePathStarts <- unique(pathStarts)

  pathEnds <- sapply(pathSplit, function(pathParts) {
    if(length(pathParts) <= 1) return("")
    paste0(pathParts[2:length(pathParts)],collapse="/")
  })

  splitLengths <- sapply(pathSplit,length)
  stillToParse <- unique(pathStarts[splitLengths > 1])

  endedIndices <- pathEnds == ""
  endedHere <- pathStarts[endedIndices]
  endedHere <- setdiff(endedHere,stillToParse)

  if(length(endedHere)) {
    pathEnds <- pathEnds[!endedIndices]
    pathStarts <- pathStarts[!endedIndices]
    uniquePathStarts <- unique(pathStarts)
    return(c(
      setNames(as.list(rep(1,length(endedHere))),endedHere),
      setNames(lapply(uniquePathStarts, function(ps) {
        pathsToNestedList(pathEnds[pathStarts == ps])
      }),uniquePathStarts)
    ))
  } else {
    return(
      setNames(lapply(uniquePathStarts, function(ps) {
        pathsToNestedList(pathEnds[!endedIndices & (pathStarts == ps)])
      }),uniquePathStarts))
  }
}

Note: I updated my answer according to your updated question.
Update: The function can be simplified to:
pathsToNestedList <- function(x) {
  nonNaIndices <- !is.na(x)
  nonEmptyIndices <- x != ""
  x <- x[nonNaIndices & nonEmptyIndices]
  if(!length(x)) return()

  pathSplit <- strsplit(x,"/")
  pathStarts <- sapply(pathSplit,"[[",1)

  pathEnds <- sapply(pathSplit, function(pathParts) {
    if(length(pathParts) <= 1) return("")
    paste0(pathParts[2:length(pathParts)],collapse="/")
  })

  splitLengths <- sapply(pathSplit,length)
  stillToParse <- unique(pathStarts[splitLengths > 1])

  endedIndices <- pathEnds == ""
  endedHere <- pathStarts[endedIndices]
  endedHere <- setdiff(endedHere,stillToParse)

  pathEnds <- pathEnds[!endedIndices]
  pathStarts <- pathStarts[!endedIndices]
  uniquePathStarts <- unique(pathStarts)

  #Concatenate the list of paths that ended with a list that is parsed again.
  #If one of those lists is empty, the concatenation behaves like
  #one would expect: It does nothing.
  return(
    c(setNames(as.list(rep(1,length(endedHere))),endedHere),
      setNames(lapply(uniquePathStarts, function(ps) {
        pathsToNestedList(pathEnds[pathStarts == ps])
      }),uniquePathStarts)
    )
  )
}

Moreover I recognized that it crashes with NA and empty strings. Hence I added a removal part in the beginning of the function.

A: Another option is to use rrapply() in the rrapply-package, which has a dedicated option how = "unmelt" to unmelt a data.frame to a nested list:
library(rrapply)
library(data.table)

paths <- c("a","a/air","a/aero/breath","b","b/boy","b/bag/band/brand")

## create data.frame/data.table with node paths
paths_melt <- as.data.table(tstrsplit(paths[grepl("/", paths)], split = "/"))
paths_melt[, value := 1L]
paths_melt
#>    V1   V2     V3    V4 value
#> 1:  a  air   <NA>  <NA>     1
#> 2:  a aero breath  <NA>     1
#> 3:  b  boy   <NA>  <NA>     1
#> 4:  b  bag   band brand     1

## unmelt to nested list
rrapply(paths_melt, how = "unmelt")
#> $a
#> $a$air
#> [1] 1
#>
#> $a$aero
#> $a$aero$breath
#> [1] 1
#>
#>
#>
#> $b
#> $b$boy
#> [1] 1
#>
#> $b$bag
#> $b$bag$band
#> $b$bag$band$brand
#> [1] 1