text:
Q: PHP Facebook login - suddenly not working I am implementing a website and I implemented a facebook login(PHP).
Suddenly it is not working anymore. When I am trying to login with facebook, it redirects me
to facebook.com when I am logged in facebook. But when I am not logged in facebook the script is working fine.
Could anyone help me?
the url of the website is: http://beta.noteslib.com/

A: It seems that you are using the old authentication method. Start reading the updated documents to implement the right method.
Basically you can provide two methods for your users:

*

*Client-side authentication with the JS SDK.

*Server-side authentication with/or without the official PHP-SDK.


text:
Q: Derivative of $x \mapsto \operatorname{tr}((A-xx^T)^{1/2})$ Let $A$ be an $n \times n$ positive definite matrix and let $x \in \mathbb{R}^n$ such that $A-xx^T$ is positive semidefinite.
I would like to find the derivative of
$$x \mapsto \operatorname{tr} \left( (A-xx^T)^{1/2} \right)$$

A: There is an important point.
Proposition. Let $f$ be an analytic function and let $\phi:U\in Z\subset M_n\rightarrow trace(f(U))$. Then $D\phi_U:H\in M_n\rightarrow trace(f'(U)H)$.
Proof. Locally, $f(U)=\sum_{i=0}^\infty u_iU^i$ and
$D\phi_U(H)=\sum_{i=0}^\infty u_itrace(D(U^i)(H))=\sum_{i=0}^\infty u_i\;i\;trace(U^{i-1}H)=trace(f'(U)H)$.  $\square$
Application. Let $\phi: U\in S_{>0}\rightarrow trace(U^{1/2})$ where $S_{>0}$ is the set of $>0$ symm. matrices. Then $D\phi_U(H)=1/2trace(U^{-1/2}H)$.
Here we consider $g=\phi\circ f:x\rightarrow trace((A-xx^T)^{1/2})$ where $f:x\rightarrow A-xx^T$ and $A-xx^T>0$.
Then $Dg_x:h\in\mathbb{R}^n \rightarrow 1/2trace((A-xx^T)^{-1/2}(-hx^T-xh^T)  )=-trace(x^T(A-xx^T)^{-1/2}h)$.
If you prefer the gradient, then we deduce $\nabla g(x)=-(A-xx^T)^{-1/2}x$.
Remark. Of course, I find the same result as @greg.

A: Assume the matrix $$M=A-xx^T$$ is positive definite, and let
$$\eqalign{
  B &= \frac{1}{2}M^{-1/2}
}$$
Then  you can find the differential and gradient of the function as
$$\eqalign{
 \phi &= {\rm tr}(M^{1/2}) \cr
d\phi &= B^T:dM = -B^T:(dx\,x^T+x\,dx^T) = -(B+B^T)x:dx \cr
\frac{\partial\phi}{\partial x} &= -(B+B^T)x \cr
}$$
where colon was used as a handy product notation for the trace, i.e.
$$A:B={\rm tr}(A^TB)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subspace $spanE$ Let $V$ be a vector space and let $E\subseteq V$.
How to show that span($E$)$=\bigcap\ \{U\ |\ U $$\ \ $is a subspace of $V$ and $U$ contains $E \ \}?$
I know the theorem ; If $\ V$ is a vector space and  $E\subseteq V$, then span($E$) is a subspace of $V$
Could anyone help me?

A: $U$ contains $E$, and $U$ is subespace of $V$, then $U$ contains $\text{span} (E)$: If $x \in  \text{span} (E)$, then $x = \sum_{i=1}^{n}\alpha_i x_i$, with $x_1, \ldots, x_n \in E$, and $\alpha_1, \ldots, \alpha_n$ scalars. But, since $U$ is subespace and $x_1, \ldots, x_n \in U$, the linear combination $x = \sum_{i=1}^{n}\alpha_i x_i$ belongs to $U$. Then $U \supset \text{span} (E)$, and $\text{span} (E) \subset \bigcap\ \{U\ |\ U $$\ \ $is a subspace of $V$ and $U$ contains $E \ \}$. What we did means that $\text{span} (E)$ is the small subespace that contains $E$.
In the other hand, then $\text{span} (E) $ is also a subespace of $V$, and contains $E$. Soon it is one of the subspaces that is part of the intersection, it follows that $\text{span} (E) \supset \bigcap\ \{U\ |\ U $$\ \ $is a subspace of $V$ and $U$ contains $E \ \}$.


text:
Q: How to use a PMML model in C++? I have converted a R model into PMML, using r2pmml.
I am now supposed to use this model in the C++ calculation module of machine but I'm a bit lost (I have never used C++ before).
I can't use Java PMML evaluation engines (as proposed in this answer) so I guess I have to find a "C++ based PMML evaluation engine".
PMMLlib seems to be used to create PMML files from C++, not to read them.
I have found numerous XML parsers (pugixml, tinyxml2, XmlLite) for C++ but I don't know if any of these can be used to read PMML.
And if they can and I understood correctly the way the work, they will create a Document Object Model which will contain my model and I will be able to use this object with XPath ?
Otherwise, I would like to know how to parse a PMML file in C++ and how to use the resulting object.


text:
Q: Vaadin can't find my themes I've got below error:

INFO: Requested resource [/VAADIN/themes/mytheme/styles.css] not found
  from filesystem or through class loader. Add widgetset and/or theme
  JAR to your classpath or add files to WebContent/VAADIN folder.

I'm using intellij.
Here is my folder structure:

My mytheme.scss:
@import "../valo/valo.scss";
@mixin mytheme {
    @include valo;
    .v-button {
        color: blue;
        background: yellow;
    }
}

My styles.scss:
@import "mytheme.scss";
@import "addons.scss";
.mytheme {
    @include mytheme;
    @include addons;
}

My web.xml:
http://wklej.org/id/2144139/
My pom.xml:
http://wklej.org/id/2144140/
I have compiled scss like in docs https://vaadin.com/docs/-/part/framework/themes/themes-compiling.html#themes.compiling.maven and I'm not in production mode.
I don't know what I'm doing wrong.

A: Manually marking directory as resources root solved it.
Did it like that in Intellij:

*

*Right click on webapp folder

*then "Mark Directory As"

*then choose "Resources Root"

It's surprising that simply marking the folder solves the problem.


text:
Q: JSF lazy datatable with different types of columns I'm using p:dataTable from Primefaces 3.5 with lazy loading and dynamic columns.
I have three types of columns, the difference is in input for filtering. One has p:inputText, one has p:selectCheckboxMenu and last one hasn't anything.
Columns are rendered via c:foreach tag.
<c:forEach var="col" items="#{cc.attrs.bean.sortedModelColumns}">

Everything works fine, but not "lazy". I also have p:tabView, where each tab includes this dataTable and with every request, all beans are initialized. I know, that c:forEach is being evaluated in build time so it's before tabView.
Therefore, my question is: How to render different columns inside p:dataTable?
I've tried ui:repeat as follows:
<p:dataTable 'datatableDefinition' />
    <ui:repeat var="#col" value="#{cc.attrs.bean.sortedModelColumns}">
        columnsRendering
    </ui:repeat>
</p:dataTable>

but that will an empty dataTable. When I put the ui:repeat outside the p:dataTable it works.
I've also tried p:columns it renders everything just fine, but the listeners for filtering on p:inputText
<p:ajax event="keyup" listener="#{cc.attrs.bean.filterListener}" />

don't work.
I think, I've two options. First: make p:columns work somehow or try to use c:if in p:tabView, but I don't know how to trigger evaluation the test inside c:if on tab switch event.
Anyway, I'll be glad for any help.
EDIT: Full code of datatable
<p:dataTable widgetVar="entityTable" var="entity" value="#  {cc.attrs.bean.loadEntities(cc.attrs.groupId)}"
                     resizableColumns="true" lazy="true"
                     rowStyleClass="#{entity.updated ? 'updatedRow' : ''}"
                     paginator="true" rows="10"
                     paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                     rowsPerPageTemplate="5,10,20" paginatorPosition="bottom"
                     scrollable="true" scrollWidth="#{userSessionBean.windowWidth -35}">
            <p:ajax event="colReorder" listener="#{cc.attrs.bean.onReorder}" />
            <p:ajax event="sort" listener="#{cc.attrs.bean.sortListener}" />
            <p:column style="width:20px" >
                <f:facet name="header">
                <p:selectBooleanCheckbox value="#{cc.attrs.bean.checkbox}">
                    <p:ajax onstart="return selectAll('#{component.clientId}');"/>
                </p:selectBooleanCheckbox>
                </f:facet>-->
                <p:selectBooleanCheckbox value="#{cc.attrs.bean.checkbox}" styleClass="entitySelectCheckbox">
                    <p:ajax listener="#{cc.attrs.bean.onEntitySelected(entity.id)}"/>
                </p:selectBooleanCheckbox>
                <p:commandLink id="notifIcon" styleClass=" #{entity.notification?'notification':''}" />
            </p:column>
            <p:column style="width:13px" rendered="#{not empty cc.attrs.subview}">
                <p:commandLink process="@this" value="   " id="loadEntity" styleClass="loadEntity"
                               immediate="true" onstart="hideRows('#{component.clientId}');" actionListener="#{cc.attrs.bean.setSelectedRowId(component.clientId)}" action="#{cc.attrs.bean.selectEntity(entity.id)}"
                               update="@(##{pe:escapeSelector(cc.clientId)}\\\\:entityTableForm)"/>
            </p:column>
            <p:columns var="col" value="#{cc.attrs.bean.sortedModelColumns}">
                <f:attribute name="property" value="#{col.property}" />
                <f:facet name="header">
                    <div style="width: #{col.width}">
                        #{col.header}
                    </div>
                    <p:outputPanel rendered="#{not cc.attrs.bean.isColDate(col.property)}" >
                        <p:inputText id="#{col.property}Id" styleClass="filterInput" rendered="#{not cc.attrs.bean.isColEnum(col.property) and not cc.attrs.bean.isColVisual(col.property)}" size="10" onkeyup="delay(function(){entityTable.filter();console.log('x');}, 500 );" >
                            <p:ajax event="keyup" listener="#{cc.attrs.bean.filterListener}" />
                            <f:attribute name="property" value="#{col.property}" />
                            <f:attribute name="operator" value="#{col.operator}" />
                            <f:event id="filterEvent" type="javax.faces.event.PreRenderComponentEvent" listener="#{cc.attrs.bean.filterRendered}"/>
                        </p:inputText>

                        <p:selectCheckboxMenu rendered="#{cc.attrs.bean.isColEnum(col.property)}" label="Choose" styleClass="filterInput">
                            <f:attribute name="property" value="#{col.property}" />
                            <f:selectItems value="#{cc.attrs.bean.getEnumStrings(col.property)}" var="item" />
                            <p:ajax event="change" listener="#{cc.attrs.bean.onEnumFilterChange}" oncomplete="setTimeout('entityTable.filter()',200);"/>
                        </p:selectCheckboxMenu>
                    </p:outputPanel>
                    <p:outputPanel rendered="#{cc.attrs.bean.isColDate(col.property)}" >
                        <p:calendar pattern="#{userSessionBean.person.settings.timeFormat}" styleClass="filterInput filterInputDate">
                            <f:attribute name="property" value="#{col.property}" />
                            <f:attribute name="operator" value=">=" />
                            <p:ajax event="dateSelect" listener="#{cc.attrs.bean.onDateFilterChange}" oncomplete="setTimeout('entityTable.filter()',200);" />
                        </p:calendar>
                        <p:calendar pattern="#{userSessionBean.person.settings.timeFormat}" styleClass="filterInput filterInputDate">
                            <f:attribute name="property" value="#{col.property}" />
                            <f:attribute name="operator" value="<=" />
                            <p:ajax event="dateSelect" listener="#{cc.attrs.bean.onDateFilterChange}" oncomplete="setTimeout('entityTable.filter()',200);" />
                        </p:calendar>
                    </p:outputPanel>
                </f:facet>
                <p:outputPanel rendered="#{not cc.attrs.bean.isColDate(col.property)}">
                    <p:outputPanel rendered="#{not cc.attrs.bean.isColVisual(col.property)}">
                        <h:outputText rendered="#{empty col.chainedProperty}"
                                          value="#{entity[col.property]}" />
                        <h:outputText rendered="#{not empty col.chainedProperty}"
                                          value="#{entity[col.primaryProperty][col.chainedProperty]}" />
                        <h:outputText rendered="#{not empty col.middleProperty}"
                                          value="#{entity[col.primaryProperty][col.middleProperty][col.chainedProperty]}" />
                    </p:outputPanel>
                </p:outputPanel>
                <kwe:inlineprogress status="#{entity.status}" rendered="#{cc.attrs.bean.isColVisual(col.property)}" />
                <h:outputText rendered="#{cc.attrs.bean.isColDate(col.property)}" value="#{cc.attrs.bean.dateTimeDisplay(entity[col.property])}"/>
        </p:columns>
        <f:event id="event2" type="javax.faces.event.PreRenderComponentEvent" listener="#{cc.attrs.bean.allRendered}"/>
    </p:dataTable>

A: You can´t use ui:repeat or c:forEach in p:dataTable, but i think that you can use p:columns


text:
Q: Why can I access the private variable in this case? I have private int a variable and I access to this variable via test.a. Why this is ok? I thought that this way is possible only if I had public int a variable, not private.
public class Test {

    private int a;

    public static void main(String[] args) {
        Test test = new Test(5);
        System.out.println(test.a);
    }

    public Test (int a) {
        this.a = a;
    }
}

A: According to the documentation :

The private modifier specifies that the member can only be accessed in its own class.

This includes everything you can have in a class : static methods, inner classes (static or not), anonymous classes, ...

A: You can access it because your main method is in the same class.


text:
Q: Two binomial probability Researcher paradox A researcher knows that the probability that a person will respond his letter is 10%
If the researcher sends a post-paid letter the probability that the reciever will respond is 40%. The researcher sends 5 post-paid letters and 5 non post-paid letters.
What is the probability that he recieves less then 3 responses?
Answer should be : 0,5193
How can you calculate this?

A: Can I assume this is not homework? So what you have to calculate are the probabilities for 0, 1, and 2 responses.  Let's take 0 as the simplest case  It will only happen if all five post=paid letters and all five non post-paid letters are answered.  By independence it is (0.90)$^5$ (0.60)$^5$.  Now add to that the probability that only 1 is returned.  There are two ways this can happen,  It can be a post-paid returned or a non-postpaid.  The disjoint events can have their probabilities summed.  For the post-paid case this is
(0.60)$^4$ (0.40)$^1$ (0.90)$^5$ But there are 5 ways that 1 post-paid letter can be answered and only 1 way that all five non-post paid letters will not be answered.  So this term is 5 (0.60)$^4$ (0.40)$^1$ (0.90)$^5$ and similarly for one non post paid 5 (0.90)$^4$ (0.10) (0.60)$^5$.  Last of all you need to add all the cases where 2  letters are answered.  This can happen by having 2 non-post-paid letters returned or 1 non-post-paid and 1 post-paid or 2 post-paid.  You and the results for these possibilities to the others to get the final answer.  The calculations are done in the same way with the number of combinations to get 2 out of 10 letters selected.  When they are both from the post-paid group the factor is number of combinations for choosing 2 out of 5 which is 10.  The same factor when both are from the non-post-paid group.  When it is one from each there are 5 ways for post-paid to match with any one of the 5 non-post-paid.  So that factor is 5x5 =25.

A: If you have R you can get to that by a proper case disjunction. The function dbinom(k, ...) is the probability that you observe exactly $k$ successes and the function pbinom(k, ...) is the probability that you observe $k$ or less successes.
The solution comes out as
dbinom(0, 5, prob=.4)*pbinom(2, 5, prob=.1) +
dbinom(1, 5, prob=.4)*pbinom(1, 5, prob=.1) +
dbinom(2, 5, prob=.4)*pbinom(0, 5, prob=.1)

which is 0.519.


text:
Q: Development mode on Symfony2 virtual hosts I was boring about my large url http://localhost:8888/site/web/app_dev.php, so, I created apache virtual hosts. When I write http://site.dev in my browser, everything is working, my website appears.
The problem is that my Symfony2 website seems to be in dev / prod mode whereas I point to app_dev.php (in the .htaccess).
I have the debug bottom toolbar (it shows me "dev environment"), I can do dumps, but when I modify a file (JS, Twig, and so on), I have to execute, each time, php app/console assetic:dump (I hadn't before).
My virtual host :
<VirtualHost *:80>
    ServerName site.dev
    ServerAlias www.site.dev

    DocumentRoot /Applications/MAMP/htdocs/bo/web
    <Directory /Applications/MAMP/htdocs/bo/web>
        AllowOverride All
        Order Allow,Deny
        Allow from All
    </Directory>
</VirtualHost>

EDIT : I noticed that the website is so much faster like that (site.dev) than before (with the localhost URL). Don't know why, and still don't know how to fix the php app/console assetic:dump problem...

A: Don't you have any other problems but worrying about the lengths of the URL? :)
But seriously, try starting the internal PHP/Symfony server with the following command:
$ app/console server:start

The development version of your app will be at http://localhost:8000. Nice and short.

Based on your comment, it turns out that the actual problem you have is hardcoding URLs in your JS. The solution for that is https://github.com/FriendsOfSymfony/FOSJsRoutingBundle.
Basically, that bundle lets you expose routes to your JS so that you avoid hardcoding URLs there.

A: You need add this line DirectoryIndex  app.php
<VirtualHost *:80>
     ServerName site.dev
     ServerAlias www.site.dev

     DocumentRoot /Applications/MAMP/htdocs/bo/web
     DirectoryIndex  app.php
     <Directory /Applications/MAMP/htdocs/bo/web>
         AllowOverride All
         Order Allow,Deny
         Allow from All
     </Directory>
</VirtualHost>


text:
Q: Executing Dissolve method in ArcGIS Engine? I'm always having a problem in GP.execute() when trying to execute this method. Here is my code:
 Friend Function DissolveFeatures(ByVal pInFLayer As ESRI.ArcGIS.Carto.IFeatureLayer, ByVal DissolveField As String, ByVal OutName As String) As ESRI.ArcGIS.Carto.IFeatureLayer

            Dim GP As New ESRI.ArcGIS.Geoprocessor.Geoprocessor
            Dim Dissolve As ESRI.ArcGIS.DataManagementTools.Dissolve = New ESRI.ArcGIS.DataManagementTools.Dissolve
            Dim pFLayer As ESRI.ArcGIS.Carto.IFeatureLayer = New ESRI.ArcGIS.Carto.FeatureLayer

            Try
                GP.AddOutputsToMap = True
                GP.OverwriteOutput = True
                GP.SetEnvironmentValue("workspace", "Database Connections\IFE connexion.sde")

                Dissolve.in_features = pInFLayer
                Dissolve.dissolve_field = DissolveField
                Dissolve.out_feature_class = "Database Connections\IFE connexion.sde\" & OutName

                RunTool(GP, Dissolve, Nothing)

                pFLayer.FeatureClass = CType(GP.Open(OutName), IFeatureClass)
                pFLayer.Name = pFLayer.FeatureClass.AliasName

            Catch ex As Exception
                MsgBox(ex.Message & "Dissolve Features")
            End Try

            Return pFLayer

        End Function

Private Shared Sub RunTool(ByVal geoprocessor As ESRI.ArcGIS.Geoprocessor.Geoprocessor, ByVal process As IGPProcess, ByVal TC As ITrackCancel)

        ' Set the overwrite output option to true
        geoprocessor.OverwriteOutput = True

        Try
            geoprocessor.Execute(process, Nothing)
            ReturnMessages(geoprocessor)

        Catch err As Exception
            Console.WriteLine(err.Message)
            ReturnMessages(geoprocessor)
        End Try
    End Sub

    ' Function for returning the tool messages.
    Private Shared Sub ReturnMessages(ByVal gp As ESRI.ArcGIS.Geoprocessor.Geoprocessor)
        ' Print out the messages from tool executions
        Dim Count As Integer
        If gp.MessageCount > 0 Then
            For Count = 0 To gp.MessageCount - 1
                Console.WriteLine(gp.GetMessage(Count))
            Next
        End If
    End Sub

This returns an error:

Error HRESULT E_FAIL has been returned from a call to a COM component

A: I solved it. probleme is because you use iFeatureLayer as an input. Use a IFeatureClass.
 Friend Function DissolveFeatures(ByVal pFC As IFeatureClass, ByVal DissolveField As String, ByVal OutName As String) As iFeatureClass

        Dim GP As New ESRI.ArcGIS.Geoprocessor.Geoprocessor
        Dim Dissolve As ESRI.ArcGIS.DataManagementTools.Dissolve = New ESRI.ArcGIS.DataManagementTools.Dissolve

        Try

            Dissolve.in_features = pFC
            Dissolve.dissolve_field = DissolveField
            Dissolve.out_feature_class = "Database Connections\IFE connexion.sde\" & OutName

            RunTool(GP, Dissolve, Nothing)

            pFC.FeatureClass = CType(GP.Open(OutName), IFeatureClass)
            pFC.Name = pFC.FeatureClass.AliasName

        Catch ex As Exception
            MsgBox(ex.Message & "Dissolve Features")
        End Try

        Return pFC

    End Function


text:
Q: How to start/stop Glassfish 2.1.1 with Java Service Wrapper? I'm trying to install Glassfish 2.1.1 as a Service on a Windows server.
I followed this article without any luck:
http://www.ryandelaplante.com/2009/08/in-past-i-have-chosen-to-use-commercial.html
Has anyone been able to install Glassfish 2.1.1 as a Windows Service using Tanuki Java Service Wrapper ?
http://wrapper.tanukisoftware.com/doc/english/download.jsp

A: I'm using Project Kenai to run Glassfish 3.0 as a service.  I don't see any reason that it wouldn't work for 2.1.1.  http://projectkenai.com/projects/winsw/pages/Home


text:
Q: How to load DynamoDB tables from YAML template to Java I'm testing a service that accesses dynamo DB tables, using test containers.
The necessary tables are being created in java test class before the tests run (partial code below) and everything works fine.
        CreateTableRequest request = new CreateTableRequest()
            .withTableName(TABLE_NAME)
            .withKeySchema(keySchema)
            .withAttributeDefinitions(attributeDefinitions)
            .withProvisionedThroughput(new ProvisionedThroughput()
                .withReadCapacityUnits(5L)
                .withWriteCapacityUnits(6L));

        Table table = dynamoDB.createTable(request);
        table.waitForActive();

However, the "real" tables are deployed to AWS via a cloudformation template (in YAML).
My question is: Is there any way to use that template on tests? I mean, import and create those tables from it and not with the code above?
Maybe via an AWS CLI command or some library that I could use to read the YAML file, and create the tables used for testing based on the template.
Searched a lot about this, and can't find anything in Java.
Thanks in advance.

A: Your question  - "that I could use to read the YAML file, and create the tables "
To read YAML from Java, you would need to use a supported API - for example:
https://dzone.com/articles/read-yaml-in-java-with-jackson
Once you are able to read YAML, you can use the Java SDK for Java (preferably V2) to interact with the DynamoDB service.


text:
Q: Angular merge routes of child modules I am dividing my angular application into modules. For a module i have a view component and an edit component. The view components have their own url (e.g. '/users').
The edit components have a common parent url (e.g. '/admin/users').
 - UserModule
     - UserPageComponent ('/user/:username')
     - UserEditComponent ('/admin/user/:username')
 - GroupModule
     - GroupPageComponent ('/group/:groupname')
     - GroupEditComponent ('/admin/group/:groupname')

This does work and the urls are accessible.
If i look at the routes with augury i see that angular defined each '/admin' route as a separate route:
(3 admin routes with 1 child each)
- Root
    - Admin
        - Users
    - Admin
        - Groups
    - Admin
        - Permissions

But because of this the wrapping admin component is reloaded every time a user switches between a pages (resetting the menu state in the admin component).
Is it possible to define these routes like this?
(1 admin route with 3 children)
- Root
    - Admin
        - Users
        - Groups
        - Permissions

currently i define the routes in each submodule using this code (Replacing Users for each other module).
export const routes: Routes = {
  path: 'admin',
  component: AdminComponent,
  children: [
    {
      path: 'Users',
      component: UserEditComponent
    }
  ]
}];

@NgModule({
  imports: [RouterModule.forChild(routes)]
})
export class UserRoutingModule{}

And in the main routing module i just do:
@NgModule({
  imports: [RouterModule.forRoot([])],
  exports: [RouterModule]
})
export class AppRoutingModule {}

i tried setting onSameUrlNavigation to 'ignore' on the forRoot() call but unfortunately this didn't change anything.

A: You can have and AdminModule, and inside this module inject your child modules (with their own routing)
For example I have a main app routing that load 2 lazy modules:

*

*Authentication, here I have a routing for register and login (both components)

*Dashboard (Admin), inside here I have another modules such as ClientModule and ProductModule wich are display in a outer-outlet inside dashboard component that also contain a sidenav and a toolbar.

OBSERVATION:
I would advice to use lazy modules at some routes for clean code, independency at unit testing and improve app performance.

I have this example at my github repo, if you have some questions or suggestions Im available to listen: https://github.com/danidelgadoz/ngx-admin

A: To define routes like
Root - Admin - Users
             - Groups
             - Permissions

for Angular will be something like
Root - Admin - Users
     - Groups
     - Permissions

So in your app.routing.module.ts define the routes normally.
export const routes: Routes = {
  path: 'admin',
  component: AdminComponent,
  children: [
    {
      path: 'Users',
      component: UserEditComponent
    }
  ],
  { path: 'groups' component: GroupComponent},
  { path: 'permissions' component: PermissionComponent}
}];


text:
Q: Weid Pagination layout and double icons in datatables and bootstrap integration I am trying to fix some shape issues when I integrate Datatables with Bootstrap
To be considered: I do not use any CDN. All external files are imported in my project manually.
Issue 1: Double Icons
I see both JQuery and Bootstrap icons in DataTable sorting area. I can fix this removing the following images from my project:

*

*sort_asc.png

*sort_both.png

*sort_desc.png

*...

However, if I do so this will trigger an error in the developer console which tells that those files are missing. I would like to have only the bootstrap ones.
Issue 2: Pagination
The pagination icons are not next to each other I would like to have something like the image below:

Issue 3: Alignment
The header labels do not align with the row labels. Rows are a bit on the left. Why?
I have created this jsfiddle for your consideration
https://jsfiddle.net/d6rw4xyx/
This is how I have initialized my DT
jQuery(document).ready(function() {
    jQuery('#table').DataTable( {
        renderer: "bootstrap"
    } );
});

Thanks

A: Try to remove jquery.dataTables.min.css from external libs. It seems that this lib overrides bootstrap classes. See the example here


text:
Q: Bib label in alphabetic style but with full 4-digit year Consider the following bibliography example using alphabetic style, maxalphanames = 1 and deactivated + in case of multiple authors:

How can achieve a complete 4-digit year in the label?
So in this case the desired output would be: Baa1989
I found a source explaining how to define a complete custom label. But I have a hard time believing that there is no simpler more generic switch to switch. Couldn't find any in the manual.
I'm looking for a solution for biblatex + biber.
Thank you.

MWE
\begin{filecontents}{references.bib}
@InProceedings{Baader1989,
  Title                    = {Direct self control of inverter-fed induction machine, a basis for speed control without speed-measurement},
  Author                   = {Baader, U. and Depenbrock, M. and Gierse, Georg},
  Booktitle                = {Industry Applications Society Annual Meeting, 1989., Conference Record of the 1989 IEEE},
  Year                     = {1989},
  Month                    = {Oct},
  Pages                    = {486-492 vol.1},
}
\end{filecontents}

\documentclass{article}

\usepackage[style=alphabetic,%
            backend=biber,
            maxnames=99,
            maxalphanames=1,
            backref=true,
            doi=false,isbn=false,url=false,
            backref=false,
            ]{biblatex}
\renewcommand*{\labelalphaothers}{}

\bibliography{references.bib}

\begin{document}
Citation: \cite{Baader1989}
\printbibliography
\end{document}

A: As far as I can see you will have to resort to \DeclareLabelalphaTemplate, but that is not too bad.
We can just copy the default from biblatex.def and change \field[strwidth=2,strside=right]{year} to \field{year}
\DeclareLabelalphaTemplate{
  \labelelement{
    \field[final]{shorthand}
    \field{label}
    \field[strwidth=3,strside=left,ifnames=1,pcompound=true]{labelname}
    \field[strwidth=1,strside=left,pcompound=true]{labelname}
  }
  \labelelement{
    \field{year}
  }
}

and that's it.
MWE
\begin{filecontents}{\jobname.bib}
@InProceedings{Baader1989,
  Title                    = {Direct self control of inverter-fed induction machine, a basis for speed control without speed-measurement},
  Author                   = {Baader, U. and Depenbrock, M. and Gierse, Georg},
  Booktitle                = {Industry Applications Society Annual Meeting, 1989., Conference Record of the 1989 IEEE},
  Year                     = {1989},
  Month                    = {Oct},
  Pages                    = {486-492 vol.1},
}
\end{filecontents}

\documentclass{article}

\usepackage[style=alphabetic,%
            backend=biber,
            maxnames=99,
            maxalphanames=1,
            backref=true,
            doi=false,isbn=false,url=false,
            backref=false,
            ]{biblatex}
\renewcommand*{\labelalphaothers}{}

\addbibresource{\jobname.bib}

\DeclareLabelalphaTemplate{
  \labelelement{
    \field[final]{shorthand}
    \field{label}
    \field[strwidth=3,strside=left,ifnames=1,pcompound=true]{labelname}
    \field[strwidth=1,strside=left,pcompound=true]{labelname}
  }
  \labelelement{
    \field{year}
  }
}

\begin{document}
Citation: \cite{Baader1989}
\printbibliography
\end{document}


text:
Q: How to elimate names which start with "." when files are listed I am trying to mimic the ls -l command via c program
But unfortunately didn't get how to ignore files like
"." , ".." and ".filename" but not filename.c
I managed to find . in the filename and ignore, but later realized that i lost even filename.c
Acuatual contents were
.
..
.bitfile
.gnupg
krishna
program.c
temp

Now my code is
while ((dir = readdir(d)) != NULL)
        {
            if (strstr(dir->d_name, ".") != NULL || strstr(dir->d_name, "..") != NULL)
                continue;
            strcpy(array[i], dir->d_name);
            i++;
        }

The contents in arrays were:
krishna
temp

But expected output was
krishna
program.c
temp

A: Why do not simply:
if (dir->d_name[0] == '.') continue;


text:
Q: Creating credentials file on server via Dockerfile & Google cloud secret manager I'm using Google cloud build for CI/CD for my django app, and one requirement I have is to set my GOOGLE_APPLICATION_CREDENTIALS so I can perform authenticated actions in my Docker build. For example, I need to run RUN python manage.py collectstatic --noinput which requires access to my Google cloud storage buckets.
I've generated the credentials and it works well when simply including it in my (currently private) repo as a .json file, so it gets pulled into my Docker container with the COPY . . command and setting the env variable with ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json. Ultimately, I want to grab the credential value from secret manager and create the credentials file during the build stage, so I can completely remove the credentials from the repo. I tried doing this with editing cloudbuild.yaml (referencing this doc) with various implementations of the availableSecrets config, $$SECRET syntax, and build-args in the docker build command and trying to access in Dockerfile with
ARG GOOGLE_BUILD_CREDS
RUN echo "$GOOGLE_BUILD_CREDS" >> credentials.json
ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json

with no success.
If someone could advise me how to implement this in my cloudbuild.yaml and Dockerfile if its possible, or if there's another better solution altogether, would be much appreciated.
This is the relevant part of my cloudbuild.yaml
steps:
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - '--no-cache'
      - '-t'
      - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
      - .
      - '-f'
      - Dockerfile
    id: Build
availableSecrets:
  secretManager:
  - versionName: projects/PROJECT_ID/secrets/CREDENTIALS/versions/latest
    env: 'CREDENTIALS'

A: If your container will run on Cloud Run, it's super easy: Remove the service account key file (and roughly, in most use cases, you never ever need it).
Keep in mind that a service account key file is a secret with a private key. And if you put it in your container, you simply store it in plain text. So bad for a secret!! (with dive, you can explore your container content, and steal the secret if you have access to the container directly)
But, I'm sure you know that because you want to store the secret in a secret manager. Now a question? How do you access a secret manager? Do you need a service account key file to be authenticated to access it?
In fact not.

The solution is to use ADC (Application default credentials). With the client libraries, use the get default credential method to let the library determine automatically the platform and the credential to use
On Cloud Run (as any other Google Cloud services), you have a metadata server that allows client libraries to get credentials information from the runtime service account.
On your local environment, you have 2 options:

*

*Use your own credential. For that run the command gcloud auth application-default login. It's your own credential and permissions, not exactly the same as the Cloud Run runtime environment

*Impersonate the Cloud Run runtime service account and act as itself to run your container/code locally. For that run the command gcloud auth application-default login --impersonate-service-account=<service account email>, Be sure to have the role service account token creator on the service account.

And then, run your app locally, and let the ADC use the credentials

A: I think I've worked out a fix. To solve the error I mentioned in my reply to @guillaume-blaquiere, I updated my build args in cloudbuild.yaml to include --network=cloudbuild, allowing me access to the correct service account credentials (credit to this answer).
The next issue I faced is with the django-storages library, returning this exception
AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. see https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account for more details.

I then came across this suggestion to add the setting GS_QUERYSTRING_AUTH = False to my django config and this seems to do the trick. My only conern is the documentation here does not go into too much detail on impacts or risks of disabling this (the bucket is public-read as it recommends). It seems to be working as intended however. So I will go with this configuration unless a better solution is put forward.


text:
Q: Mapping for Entity FW TablePerHierarchy I tried to map hierarchy of classes to specific table but could not.
This is the source i used as explanation:
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
In may case i have Users table :
ID | Name | Company | Discriminator

And two models - Users with properties :
ID | Name

And Corporates entity which inherits Users entity with only one property :
Company

I created field "Discriminator" by hands and now need to understand how to check field "Company" when i use polymorphic query? E.g. I need to get some row from DB and check whether it has Company field set or not ... should i always convert all data to specific entity (e.g. Corporates) to check whether this field exists?
OR
I thought that EF can choose relevant entity automatically when similar rule is defined :
modelBuilder.Entity<Users>()
.Map<Corporates>(m => m.Requires("Discriminator")
.HasValue("Corporates"))

But the problem is that whenever i try to add any mapping rule to OnModelCreating i always get an error when model is creating first time.
Could someone tell me what am i doing wrong?
Thanks in advance, Art


text:
Q: Chip Card sample data I have successfully send ARQC to host, In response I have field 55 (ISO 8583) with different tagged data, I want to just clarify it by comparing it to sample field 55 response data. Can any one provide me sample response data of field 55 ?

A: In ISO8583 standard DE55 is allocated for EMV related data in request and response. In the response you can receive [ARPC][ARC] or [ARPC][CSU]. At times you can see template 71 or 72 which are issuer scripts with tag 9F18 optionally to identify the issuer script. Refer the payment scheme documentation for exact implementation details.


text:
Q: Python Script For Loop So I have these python program:
for index, row in data.iterrows():

    self.session.findById("wnd[0]/tbar[1]/btn[17]").press()
    self.session.findById("wnd[1]/usr/subSUB0:SAPLMEGUI:0003/ctxtMEPO_SELECT-EBELN").text = row.Document
    self.session.findById("wnd[1]/usr/subSUB0:SAPLMEGUI:0003/ctxtMEPO_SELECT-EBELN").caretPosition = 10
    self.session.findById("wnd[1]/tbar[0]/btn[0]").press()
    self.session.findById("wnd[0]/tbar[1]/btn[7]").press()
    self.session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0016/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/btnEDITFILTER").press()
    self.session.findById("wnd[1]/usr/subSUB_DYN0500:SAPLSKBH:0600/btnAPP_WL_SING").press()
    self.session.findById("wnd[1]/usr/subSUB_DYN0500:SAPLSKBH:0600/btn600_BUTTON").press()
    self.session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-LOW").text = row.Position
    self.session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").text = row.Position
    self.session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").setFocus
    self.session.findById("wnd[2]/usr/ssub%_SUBSCREEN_FREESEL:SAPLSSEL:1105/ctxt%%DYN001-HIGH").caretPosition = 3
    self.session.findById("wnd[2]/tbar[0]/btn[0]").press()
    self.session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0016/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-NETPR[10,0]").text = row.New_Price
    self.session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0016/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-NETPR[10,0]").setFocus
    self.session.findById("wnd[0]/usr/subSUB0:SAPLMEGUI:0016/subSUB2:SAPLMEVIEWS:1100/subSUB2:SAPLMEVIEWS:1200/subSUB1:SAPLMEGUI:1211/tblSAPLMEGUITC_1211/txtMEPO1211-NETPR[10,0]").caretPosition = 14
    self.session.findById("wnd[0]/tbar[0]/btn[11]").press()

And I want to run this line:
self.session.findById("wnd[0]/tbar[1]/btn[7]").press()

only once in the loop.
How do I run it once only? (only that line)

A: Like Olvin Roght said, try moving the code outside the loop because that specific line has nothing to do with the loop in the first place. You are not using the row or the index for that line. So it makes no sense to keep it inside the loop unless you aren't telling us something.
However, to answer your question, you could create a boolean variable outside the loop to track if the loop has been run and do your action on the first try. Something like this:
firstRun = True
for index, row in data.iterrows():
    self.session.findById("wnd[0]/tbar[1]/btn[17]").press()
    self.session.findById("wnd[1]/usr/subSUB0:SAPLMEGUI:0003/ctxtMEPO_SELECT-EBELN").text = row.Document
    self.session.findById("wnd[1]/usr/subSUB0:SAPLMEGUI:0003/ctxtMEPO_SELECT-EBELN").caretPosition = 10
    self.session.findById("wnd[1]/tbar[0]/btn[0]").press()
    if firstRun: # THIS IS TRUE on the first run
        self.session.findById("wnd[0]/tbar[1]/btn[7]").press() # Do the click once.
        firstRun = False # Set it to False so that subsequent runs are not treated as first run.
    # Run All other clicks and stuff in your loop as usual.


text:
Q: i want to know how i get corresponding value of columns to the selective columns value I am trying to get those rows from the table which is corresponding to the selective indexes. For example, i have one xls file in which different columns of data. currently my code search the selective two columns and their indexes also, know i want to search those selective rows corresponding elements which is in different rows.
Lets A B C D E F G are columns name in which 1000 of rows of numbers
like
 A B c D E F G
 1 3 4 5 6 3 3
 3 4 5 6 3 2 7
 .............
 4 7 3 2 5 3 2

So Currently my code search two specific columns (lets suppose B and F selective values which is in some range), now i want to search column A value which is present in those selective ranges.
B F A
3 4 5
3 5 3
7 7 3
5 4 6
...

like this
This is my current code VI

A: I hope we've finally gotten to the bottom of it. How about this one?


text:
Q: If $S\subseteq R$ is uncountable then $S$ has a super limit point $x\in S$ is said to be a super limit point if $\forall \epsilon >0, (x-\epsilon,x+\epsilon)\cap S$ is uncountable.
I wondered if $S\subseteq R$ is uncountable then $S$ has a super limit point? I can prove this in the case $S$ is closed: One of the intervals $([n,n+1], n\in \mathbb{Z})$ contains  uncountably many points of $S$, wlog $[0,1]$. Then one of the intervals $[0,{1\over2}] ,[{1\over2},1]$ contains uncountably many points of $S$, call it $I_1$. Now keep subdividing inside $I_1$ in the same way. $J_i=S\cap I_i$ is compact so the intersection is nonempty and in fact is contained in $S$ by closure. Then clearly any point in this intersection is a super limit point.
What happens when $S$ isn't closed?

A: Assume not, that S has no super limit points. Then for each $x\in S$ let $I_x$ be an open interval with rational endpoints such that $I_x\cap S$ is countable. Then $S=\cup (S\cap I_x)$ is countable, as there are only countably many distinct $I_x$.


text:
Q: How to Sum Price from 6:00am till next day 6:00am I need to sum price from current day 6:00am till next day 6:00am (24hour). The problem is what if will run my code from 6:00am till 24:00(00:00) and what if I will run it from 24:01 till 6:00am?
Should I create two exceptions for this or I can run it with one code?
My Sql Table Contains a DateTime column.
    var date = DateTime.Now;
            if ((date.Hour>=6&& date.Minute >0) && (date.Hour <= 24 && date.Minute < 59))
            {

            }
else if ((date.Hour>=0&& date.Minute >0) && (date.Hour <= 5 && date.Minute < 59))
            {

            }

Or if I can do it immediately with a sql query?
SELECT SUM(sumtotal) from customertrans where DATEPART(HOUR, DateTime)>=6 and DATEPART(HOUR, DateTime)<=24 and DATEPART(HOUR, DateTime)=DATEPART(HOUR, GETDATE())

If hour is from 24:00 till 6:00 I need to add also the previous day from 6:00 am till 24:00
Check this approch below:
var date = DateTime.Now;
        if ((date.Hour >= 6 && date.Minute >= 0) && (date.Hour <= 23 && date.Minute <= 59))
        {
            SqlCommand cmd = new SqlCommand("Select sum(sumTotal) from customertrans where datetime>='" + DateTime.Now.ToString("MM/dd/yyyy") + "' and DateTime >= DATEPART(HOUR, '6:00') ", con);
            string test = cmd.ExecuteScalar().ToString();
            MessageBox.Show(test);
        }
        else if ((date.Hour >= 0 && date.Minute >= 0) && (date.Hour <= 5 && date.Minute <= 59))
        {
            SqlCommand cmd = new SqlCommand("Select sum(sumTotal) datetime from customertrans where datetime>='" + DateTime.Now.AddDays(-1).ToString("MM/dd/yyyy") + "' and DateTime >= DATEPART(HOUR, '6:00') ", con);
            string test = cmd.ExecuteScalar().ToString();
            MessageBox.Show(test);
        }

A:
from current day 6:00am till next day 6:00am (24hour)

Not true. Some days have 23:00 and others have 25:00, so bear that in mind. Given that you are calling this from C#, I find it a bit odd that you are doing stuff with DATEPART. Why not just do a ranged query on DateTime? If the field is indexed then you will avoid a table scan.
Why not something like:
        TimeSpan cutoverTime = TimeSpan.FromHours(6); // or however you have this defined

    // DateTime.Now is unstable, and the date may change between two consecutive calls
    // so read it into a temporary variable

    DateTime currentTime = DateTime.Now;
    DateTime startTime = currentTime.Date.Add(cutoverTime); // guess today
    if (startTime > currentTime)
    {
        // ok, guessed wrong, it was yesterday
        startTime = startTime.AddDays(-1);
    }
    DateTime endTime = startTime.AddDays(1);

    // And use parametised queries, not string concatenation (please)
    // SELECT SUM(sumtotal) from customertrans where DateTime >= @startTime and DateTime < @endTime

A further word of caution, you need to probably be thinking about timezones, maybe doing something with respect to UTCNow instead.

A: Use this in your where statement.
WHERE date BETWEEN FORMAT(GETDATE(), 'MM/dd/yyyy') + ' 06:00' AND FORMAT(GETDATE() + 1, 'MM/dd/yyyy') + ' 06:00'

This formats the current date in MM/dd/yyyy format then appends the time of 6:00 am to it (for start date), then does the same but adds 1 (which adds 1 day) to it to get tomorrows date.
For SQL 2008 you can do this:
where date BETWEEN CONVERT(VARCHAR(10), GETDATE(), 110) + ' 06:00' AND  CONVERT(VARCHAR(10), GETDATE() + 1, 110) + ' 06:00'

A: You can try this
DateTime start = date.Date.AddHours(6);
if ((date.Hour >= 6 && date.Minute >= 0) && (date.Hour <= 23 && date.Minute <= 59))
{
     sum = Sum(start, start.AddDays(1));
}
else if ((date.Hour >= 0 && date.Minute >= 0) && (date.Hour <= 5 && date.Minute <= 59))
{
     sum = Sum(start.AddDays(-1), start);
}

Where your sum method is declared like
public int Sum(DateTime start, DateTime end)


text:
Q: Thread for Background Music I have a homework assignment. I am supposed to make a calculator and add background music. I use Dev-C++ and C on windows.
 I need a thread when I want to use music and calculator. I am going to use process.h for thread. I tried using _beginthread but it raised an error.
#include<stdio.h>
#include<process.h>

void asd()
{
    printf("hello");
}

int main()
{
    _beginthread(asd(),333,(void*)NULL);    _endthread();
}

and error is
[invalid use of void expression]

How can I do this assignment?

A: You're calling asd instead of passing its address. Since the function has a void return, you are incorrectly passing void where a function pointer is expected. Remove the parentheses.
int main()
{
    _beginthread(asd, 333, (void*)NULL);
}

And the function asd must accept a void pointer parameter as well.
void asd(void*)
{
    printf("hello");
}


text:
Q: How can I use Math Formula in a MySQL query? I am creating a CPM and I am trying to get all the CPM that are not on track. I have the follow code below and I have put the formula in the WHERE clause, but it shows all results. Instead of only results that are less than 0.9.
SELECT cpms.*, site_images.*

FROM ( cpm_images

INNER JOIN site_images ON ( cpm_images.site_image_id = site_images.site_image_id ) )

INNER JOIN cpms
  ON
    ( cpms.cpm_id = cpm_images.cpm_id )
WHERE (
    ( cpms.cpm_views_count * ( $data - cpms.cpm_date_start ) ) /
    ( cpms.cpm_views_total * (cpms.cpm_date_end - $data ) )
      ) < 0.9

No matter what number is calculated it show the all the results. If the number is below 0.9 it shows, if it is above 0.9, it shows.
UPDATE:
the following data is what is being pulled from the datbase.
This is the data from the table.

[cpm_id] => 1
[cpm_title] => Ad Special
[cpm_date_start] => 1556746806
[cpm_date_end] => 1559425206
[cpm_views_total] => 1000
[cpm_views_count] => 500
[cpm_image] =>
[cpm_active] => 1
[site_image_id] => 137
[site_image_file] => cars/3.jpg
[site_image_file_tn] => cars/3.jpg
[site_image_file_org] => cars/3.jpg
[site_image_title] =>
[site_image_description] =>
[site_image_upload_date] => 0

When i places numbers in place of the table row names
    ( 500 * ( 1557665447 - 1559425206 ) )
    /
    ( 1000 * ( 1556746806 - 1557665447 ) )
it works, so is it possible that the table row names are not showing as int. yet the table is as follows
`cpm_id` int(11) UNSIGNED NOT NULL,
`cpm_title` varchar(255) NOT NULL,
`cpm_date_start` int(11) NOT NULL,
`cpm_date_end` int(11) NOT NULL,
`cpm_views_total` int(11) NOT NULL,
`cpm_views_count` int(11) NOT NULL,
`cpm_image` varchar(255) DEFAULT NULL,
`cpm_active` int(1) DEFAULT NULL

if I have the numbers
( 0 * ( 1557665447 - 1559425206 ) )  /  ( 1000 * ( 1556746806 - 1557665447 ) )

it equals to 0 so it shows as it is below 0.9
BUT if i have the follow
( 1000 * ( 1557665447 - 1559425206 ) )  /  ( 1000 * ( 1556746806 - 1557665447 ) )

which equals to 1.91561121265 which it shows in the results, but it shouldn't as it is not smaller then 0.9
UPDATE:
if i use the follow
WHERE ( ( cpms.cpm_views_count * ( 1557665447 - 1559425206 ) )  /  ( cpms.cpm_views_total * ( 1556746806 - 1557665447 ) ) ) < 0.9

It works, and the following works too
WHERE ( ( cpms.cpm_views_count * ( $date - 1559425206 ) )  /  ( cpms.cpm_views_total * ( 1556746806 - $date ) ) ) < 0.9

but as soon as i change it to
WHERE ( ( cpms.cpm_views_count * ( $date -  cpms.cpm_date_start  ) )  /  ( cpms.cpm_views_total * ( cpms.cpm_date_end - $date ) ) ) < 0.9

it does not work, I even try putting brackets around cpms.cpm_date_end and cpms.cpm_date_start and it still failed.

A: I have found the issue, I had the cpm_views_start and cpm_views_end wrong way around
( ( cpms.cpm_views_count * ( $date - cpms.cpm_date_end  ) )  /  ( cpms.cpm_views_total * (  cpms.cpm_date_start - $date) ) )

How I realized this was when I put it in as follows
 SELECT ( ( cpms.cpm_views_count * ( $date - cpms.cpm_date_end  ) )  /  ( cpms.cpm_views_total * (  cpms.cpm_date_start - $date) ) ) AS sum_2

it came back a different number. I realize somewhere during coding the string I change the cpm_date_end and cpm_date_start around, yet in where i had it showing on the screen for testing, it was the correct way, so the data on the screen was correct but when it was calculating it in the query, it was wrong way about.
Thank you #nick for doing what you can to help me.


text:
Q: Dialog built from divs and css doesn't layout correctly I've got a dialog box that isn't displaying correctly, but I can't figure out why. The dialog is made up of a few divs.
The dialog is made up of a parent div that contains three sub divs for the title, body and footer. Each of the sub divs is further divided into 3 sub sub divs for left, center and right. What I can't figure out is why my left footer sub sub div appears to the right of the right side body sub sub div.
I've simplified the html below so the structure is clear.

Most of the CSS is the same with each of the 3 main sections (titlebar, body, footer)
Title:
.titlebar {
    height: 38px;
    width: 100%;
}

Content:
.con {
    background: url("../images/dialog/vertical.png") repeat-y scroll 0 0 #FFFFFF;
    font-family: Tahoma,"Lucida Grande",Verdana,Arial,Helvetica,sans-serif;
    font-size: 11px;
    width: 100%;
}

Footer:
.footer {
    font-family: Tahoma,"Lucida Grande",Verdana,Arial,Helvetica,sans-serif;
    font-size: 11px;
    height: 37px;
    width: 100%;
}

Here's the left footer CSS:
.footerleft {
    background: url("../images/dialog/static.png") no-repeat scroll 0 -83px transparent;
    float: left;
    height: 100%;
    width: 9px;
}

Here's a picture of the problem: http://s9.postimage.org/ebj6w7ynj/Dialog_Corner.jpg

A: all div elements is display:inline . so if you write a div after a div element , the width of parent element will break div to new line (just if two div width was more than parent width).
now you can set clear:both (floats)  to .footer class to break line before this element .
.footer {
    font-family: Tahoma,"Lucida Grande",Verdana,Arial,Helvetica,sans-serif;
    font-size: 11px;
    height: 37px;
    width: 100%;
    clear:both;
}

but i am not sure that works in all browsers .


text:
Q: Why does my FORM element have a random JQuery attribute? I'm using Approval Tests and WatiN to test the integration of my ASP.NET MVC2 pages. WatiN launches IE to hit the given URL and then gives me the browser's html response in a variable. Then, Approval Tests allow me to compare the html response with an "approved" version of the html response. This system works great except that something (either IE or JQuery) is adding an unexpected attribute to my  element.
Here's a copy of the form tag from IE's html response:
<FORM method=post action=/Account/LogOn jQuery1314030136323="2">

Notice the jQuery1314... attribute in the form element. It is always set to "2", but the name of the attribute is always different (jQuery###########). Since it's different every time, my Approval Tests fail. I need to either run a regex on the html output and remove the param with brute force, find a way to make the attribute name the same every time, or remove is altogether. Any ideas?
I'm intentionally -not- tagging this with ASP.NET because I really think this is specific to IE or JQuery.

A: That's the uuid/jQuery.expando that jQuery adds to every DOM element it interacts with, to work around browser memory leaks.
Older style code waited for window.onunload to unbind Javascript data from DOM tags to prevent memory leaks. JQuery avoids this by using a simple number (like the one in your code example) in an attribute and then keeping a hashmap in Javascript of tags and numbers (which it calls the uuid).
The weird attribute name is the value of jQuery.expando, which you can search for easily in the code and see it's set to a random value each time. This is done to allow multiple copies of jQuery to coexist on the page without interfering with each other.
I'm not aware of a use case I've ever needed where I need more than one jQuery on the same page, and I suspect you don't need this functionality either - you could easily resolve this by just eliminating this feature. Modify the code to set jQuery.expando to some hard-coded value, like 'jquery', instead of a random number, and you're good to go.
Be careful not to ever use jQuery twice in the same page though! Although doing so by accident introduces a lot of other strange side effects as well (like reuse of $), so that point may be moot.
I go into a little more detail about jQuery.expando/uuid in this question:
Why Doesn't JQuery Expose its UUID Functionality?
You'll notice in that write-up that the value of the attribute is random-ish - it's a counter based on how many tags have been interacted with by jQuery so far. If your code requires the attribute value to be consistent, you may still run into trouble.
Update
You'll need to modify your jquery source. For example, 1.6.2:
http://code.jquery.com/jquery-1.6.2.js
Includes the following:
jQuery.extend({
    cache: {},

    // Please use with caution
    uuid: 0,

    // Unique for each copy of jQuery on the page
    // Non-digits removed to match rinlinejQuery
    expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),

You can change the expando line as follows:
    // Does not support multiple copies of jQuery on the same page!
    // 0 included to match rinlinejQuery (/jQuery\d+/)
    expando: "jQuery0",

A: I believe it is what jQuery does internally to track all of the elements in the DOM that you have jQuery events wired up for.  You might not be able to remove them without unhooking the events.


text:
Q: php5 copy sub-strings from string separated by space? I am using php5 and have a script which will return IP addresses of the client.
Executing script using shell_exec() function. Now the output is like this: *192.168.10.40 192.168.10.41 *.
Now I need to store this in an array. I used preg_match() but it is not working.
Here is the code using preg_match() :
$test = shell_exec("/www/dhcp.sh");
$pattern='/([^ ]*) /';
preg_match($pattern, $test, $new);

preg_match() is returning 0;
Here is the one I used explode() :
$test = shell_exec("/www/dhcp.sh");
var_dump( explode(' ', $test ) );

I also used explode but I am getting the result as:
array(1) { [0]=> string(28) "192.168.10.40 192.168.10.41 " }
Can anyone tell me how can I split the string into an array?
Regards,
Sowmya

A: You can use explode to split your string:
explode(' ', '192.168.10.40 192.168.10.41'));

which gives you
array(2) {
  [0]=>
  string(13) "192.168.10.40"
  [1]=>
  string(13) "192.168.10.41"
}

http://php.net/manual/fr/function.explode.php


text:
Q: Code not passing final test case on LeetCode #451, working for all other test cases? I am hoping someone can help me understand why my code isn't working for a certain test case. This is about question 451: Sort Characters by Frequency on LeetCode. Here is the goal: "Given a string, sort it in decreasing order based on the frequency of characters." My code passed 34/35 of the test cases, but not the last one. I am wondering why my code worked for the other test cases but not this last one, and what I can do to fix it so it works for the last test case as well?
 class Solution {
public String frequencySort(String s) {
    Map<Character, Integer> map = new HashMap<>();
    for(char c: s.toCharArray()){
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    StringBuilder sb = new StringBuilder(s.length());
    Map<Character,Integer> sorted = new TreeMap<>(new Comparator<Character>() {
        @Override
        public int compare(Character a, Character b){
            Integer aValue = map.get(a);
            Integer bValue = map.get(b);
            if(aValue == bValue) return 1;
            return bValue.compareTo(aValue);
        }
    });
    sorted.putAll(map);
    for(Map.Entry<Character,Integer> entry: sorted.entrySet()){
        int length = entry.getValue();
        char toAdd = entry.getKey();
        for(int i = 1; i <= length; i++){
            sb.append(toAdd);
        }
    }
    return new String(sb);
}
}

Test Case

A: Simple Scala Solution here if you want:
object Solution {
  def frequencySort(s: String): String = {
    import collection.mutable.Map
    val count: Map[Char, Int] = Map().withDefaultValue(0)
    for {
      c <- s
    } {
      count(c) += 1
    }
    count
      .toList.map(x => (x._2, x._1))
      .sorted
      .reverse
      .flatMap(x => List.fill(x._1)(x._2.toString))
      .foldLeft("")(_ + _)
  }
}


text:
Q: Clap relay using 555timer - not sure about voltages around transistor
Hello!
I am working on a clap relay project and I want to do my own clap relay using timer 555 but I am not sure how the circuit works in details.
I am familiar with the 555 timer and I know that the trigger voltage has to be lower than 1/3 of Vcc (in this circuit 4.3/3=1.43, so lower than that). Electret microphone M1 is also included.
I have posted a part of a clap relay circuit which I found it on the internet and this circuit makes the led turn on(not on the picture). I marked points A and B because I am want to know the potential in those two points.
My assumption how it works(please correct me, because I am not sure!):

*

*before any sound is made:

*

*electret mic is biased with 4.3V voltage and it acts like a capacitor because of its internal structure

*current flows through 470k resistor and base of NPN, so that the potential in point B is around 0.7V and the transistor conducts current

*if the transistor is in active/linear mode and Ic=beta*Ib is valid in active region, therefore potential is calculated to be around 2.6V

But that means that 2.6V>1.43V and the 555timer is not triggered.

*When sound is produced

*

*the 4.3V biased electret mic vibrates which changes the voltage on a microphone and therefore changes current through 220n capacitor and at the same time also changes base current.

*because the base current is changed and the transistor is in linear/active region, that also changes the collector current and also potential in point A.

Please correct me if I am wrong. I would like to make this circuit but before I make it I would like to know if I am understanding it correctly!
Thank you in advance.
EDIT: I have made a circuit on a breadboard and measured voltage across microphone to be around 2.9V. Apparently my knowledge about electret microphone is a problem :) Potential at point A was 0.2V and in point B around 0.7V.
I will experiment further and post what I found out, maybe it will help someone else :)

A: Your assumptions on how it works are correct. However this is a poor design because it is critically dependent on the current gain of T1.
The BC847's HFE can be as low as 110 or as high as 800. The 'A' version is more tightly specified at 110 to 220, but even this narrower range could produce wildly varying results. With HFE = 110 the steady state trigger voltage will be about 1.8V (above the threshold), but at HFE = 220 it is about 0.2V so the 555 will be continuously triggered.
To ensure that it worked with any BC847 you would have to either choose a higher value for R2 that covers the full range of possible HFE values, select the required value on test, or make it a trim pot that is adjusted to suit each individual transistor.
The other alternative is to change the circuit to make it less sensitive to HFE variations. If R2 is connected between the Base and Collector of T1 then the Collector voltage will tend to stabilize at around half the supply voltage, and the circuit should work with a wide range of transistors.

A: I have increased resistance to 2Mohms and is working correctly as planned. When no sound is produced the potential in point A is 3.4V (it is a great match with the calculated result which was 3.5V, active region). When I clap the potential drops and triggers the 555 timer and turns on the LED.


text:
Q: Is integration of $x\operatorname{cosec}(x)$ defined? Is integration of $x\operatorname{cosec}(x)$ possible? If yes, then what is its closed form; if not, then why is it non-integrable ?

A: We have $\sin x = x +O(x^3)$ in a neighbourhood of the origin, so $\frac{x}{\sin x}$ is integrable over any compact interval in $(-\pi,\pi)$. Its primitive, however, is not an elementary function:
$$ \int_{0}^{t}\frac{x}{\sin x}\,dx = t\log\tan\frac{t}{2}-\int_{0}^{t}\log\tan\frac{x}{2}\,dx$$
but has a nice Fourier series:

$$\forall t\in(0,\pi),\qquad \int_{0}^{t}\frac{x}{\sin x}\,dx = t\log\tan\frac{t}{2}+2\sum_{n\geq 0}\frac{\sin((2n+1)t)}{(2n+1)^2}.$$

This is strictly related with the inverse Gudermannian function.

A: Using $u=\tan(x/2)$ so that $\sin(x)=\frac{2u}{1+u^2}$, $\mathrm{d}x=\frac{2\,\mathrm{d}u}{1+u^2}$
$$
\begin{align}
&\int\frac{x}{\sin(x)}\,\mathrm{d}x\\
&=2\int\frac{\arctan(u)}u\,\mathrm{d}u\\
&=2\sum_{k=0}^\infty(-1)^k\int\frac{u^{2k}}{2k+1}\,\mathrm{d}u\\
&=2\sum_{k=0}^\infty(-1)^k\frac{u^{2k+1}}{(2k+1)^2}+C\\
&=\frac{\mathrm{Li}_2(iu)-\mathrm{Li}_2(-iu)}i+C\\[6pt]
&=\frac{\mathrm{Li}_2(i\tan(x/2))-\mathrm{Li}_2(-i\tan(x/2))}i+C
\end{align}
$$
where $\mathrm{Li}_2(x)=\sum\limits_{k=1}^\infty\frac{x^k}{k^2}$
is the Dilogarithm Function.

A: Yes, $x\,\mathrm{cosec}\,x$ is integrable and has a closed form.
Hint:
Using the subsitution $u = \tan \left(\frac{x}{2}\right)$, we get:
$$\int \frac{1}{\sin x} \, \mathrm{d}x = \ln \left(\tan \left(\frac{x}{2}\right)\right) + \mathrm{C}$$
Combine this result with the use of integration by parts, specifically, let $u= x \implies \mathrm{d}u = \mathrm{d}x$ and $\mathrm{d}v = \frac{1}{\sin x}$.
Using integration by parts with the above , we get that $$\int \frac{x}{\sin x} \, \mathrm{d}x = x \ln \left(\tan \left(\frac{x}{2}\right)\right) + \int \ln \left(\tan \left(\frac{x}{2}\right)\right) \, \mathrm{d}x$$
The above evaluates to
$$i\left(\mathrm{Li}_2(e^{-ix}) - \mathrm{Li}_2 (e^{ix})\right) + x \left(\ln(1-e^{ix}) - \ln(1+e^{ix})\right) + \mathrm{C}.$$
Where $\mathrm{Li}_2$ is the Polylogarithm function.

A:
Why is it non-integrable ?

The answer to this question is given by Liouville's theorem and the Risch algorithm. However, understanding them requires advanced knowledge of abstract algebra, such as $($ differential $)$ Galois theory, for instance.


text:
Q: "cannot parse Procfile" error when Heroku uploading Pic of the files in the github repo:

When I try uploading I get the error:

Push failed: cannot parse Procfile. Please try pushing again.

Anyone know why this may be happening?


text:
Q: How to send multiple identical HTTP POST message instantly I have people cheating in my game by sending multiple HTTP POST message the game server (php + apache) to gain items. I have fixed that loophole but I want to test if my fix was correct.
I have tried some of the chrome plugin to send POST messages but I cant imitate sending them in the same instant, for example 5 identical POST message all send out less that 100ms to the same IP in between them.
I have a Centos and a windows machine, would appreciate any script or program recommendation.

A: If you have Python installed (your CentOS machine would), the following will do what you're after using only built-ins. You'll just need to tweak the conn.request line to pass in any body or headers your server requires.
from threading import Thread
import httplib, sys

REQUESTS = 5

def doRequest():
    conn = httplib.HTTPConnection("www.google.com")
    conn.request("POST", '/some/url')

for i in range(REQUESTS):
    t = Thread(target=doRequest)
    t.daemon = True
    t.start()


text:
Q: How can I tell what user Jenkins is running as? I have a bitnami Jenkins VM, how do I tell what user Jenkins is running as? I suspect it is Tomcat.

A: I would use ps to get the uid of the process, and grep for that in /etc/passwd

A: You could also create a Jenkins job containing a shell script box with the "whoami" command.

A: Use this command to see under which process your Jenkins server works on:
ps axufwwww | grep 'jenkins\|java' -

To interpret the results, look for:
jenkins   1087  0.0  0.0  18740   396 ?        S    08:00   0:00 /usr/bin/daemon --name=jenkins
jenkins   1088  1.6 20.7 3600900 840116 ?      Sl   08:00   2:12  \_ /usr/bin/java

1087 and 1088 are the PIDs. They might differ for you.

A: If you have access to the gui, you can go to "manage jenkins" > "system information" and look for "user.name".

A: ps aux | grep '/usr/bin/daemon' | grep 'jenkins' | awk {'print $1'}
The command will show running processes, then grep for a process running as a daemon that includes the string 'jenkins'. Finally, get the first row of the piped output which is the user that is running Jenkins.


text:
Q: function declaration and assignment to a variable I want to ask a question about how functions are assigned to variables.
I am a beginner in Python and studying functions.
Consider the following block of code from w3schools:
def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

I know that a lambda is an anonymous function with only one expression that is evaluated and returned.
This is shown inside myfunc(n):
return lambda a: a * n

myfunc takes in an argument, which in this case is 2, so any number a will be doubled.
However, I'm confused here.
In this line:
mydoubler = myfunc(2)

I thought we assign the result of myfunc to mydoubler but in the print statement:
print(mydoubler(11))

we are passing an argument 11 but we never specified the parameter a anywhere in the function declaration.
How does the python code know that 11 in this case inside the print statement is associated with a?

A: The function created by lambda a: a * n is a closure. When the function is called as mydoubler(11), it uses 11 as the value for a, and 2 (the value of n inside myfunc at the time lambda a: a * n was evaluated) as the value for n.
mydoubler behaves as if it were defined as
def mydoubler(a):
    return a * 2

You can see that the value 2 is stored in the function using a bit of digging:
>>> mydoubler.__closure__[0].cell_contents
2

(In fact, you can change that, though you would only do so if you want to make your code hopelessly complicated:
>>> mydoubler.__closure__[0].cell_contents = 3
>>> mydoubler(2)
6

)

A: In this case you actually assigned the doubler-function to mydoubler:
mydoubler = myfunc(2)

There you also specified the parameter a, namly 2. So when you pass a number to the mydoubler() function, Python know that you already specified n

A: The return value from myfunc(2) is equivalent to this lambda
lambda a: a * 2

That lambda takes 1 argument, and doubles it. When you call it, in this case by assigning it to the name mydoubler, whatever argument you pass to it is a, the one argument that the lambda accepts.
Equivalent code:
mydoubler = lambda a: a * 2
output = mydoubler(11) # returns 11 * 2
print(output) # prints 22


text:
Q: Remote control server dialing out to viewer? I'm looking for a remote control application that satisfies the following requirements:

*

*the server (ie. the application
running on the customer's PC I need
to support) dials out to connect to
the client running on my support PC
and waiting for incoming connections.
No port-mapping on the customer's
firewall required

*the server must be single EXE (no setup software setup required)

*ideally, one application for both XP and Vista

*Direct connection between server and client: I don't want to rely on some web service like CoPilot to act as repeater

*Either open-source or affordable

UltraVNC works fine on XP but doesn't run OK on Vista (screen lags, connection breaks). The new project, PCHelpWare, doesn't run that well either. And the UVNC site is a mess.
Does someone know of an application that satisfies these requirements?
Thank you.

A: What about the built-in Remote Assistance application?

A: Are you looking for a modem based solution, or a web based solution?
For a web based solution to work like this you'd need to have major holes in your companies firewall setup to allow access.
The company I work for uses logmeinrescue.com so that we can access the customers desktop.  We simply have them go to logmein123.com and they enter a 6 digit pin number that the customer service rep gives them.  The rep is then able to see the customers desktop via a web browser.

A: Thanks for the tip. I looks like TeamViewer is almost what I was looking for (both hosts connect out through TCP80 to TeamViewer's servers which act as repeaters).


text:
Q: Sending files via network only working for text files I'm trying to send a file from my PC to my Android Phone via the LAN.
Client (sender, PC):
public class Client {

    public static void main(String[] args) {

    String host = "192.168.0.108"; //IP of phone (I know, hardcoding is evil...)
    int port = 19999;
    String TimeStamp;
    Socket con;
    File f = new File("/home/sebastian/test");

    try {
        InetAddress address = InetAddress.getByName(host);
        con = new Socket(address, port);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    Thread t = new Thread(new Runnable() {

    @Override
        public void run() {
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f));
            BufferedOutputStream bos = new BufferedOutputStream(con.getOutputStream());
            int i;
            System.out.println("Starting transmission");
            while ((i = fis.read()) != -1) {
                bos.write(i);
            }
            System.out.println("Finished");
            bos.flush();
            fis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }}

    });
    t.start();
    }
}

Server (Receiver, phone):
class Server extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startserver();
    }

    private void startserver() {
    try {
        socketl = new ServerSocket(port, 0, InetAddress.getByName("192.168.0.108"));
        Thread t = new Thread (new Runnable() {

            @SuppressLint("SdCardPath")
            @Override
            public void run() {
                while (true) {
                    try {
                        connection = socketl.accept();
                        BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
                            InputStreamReader isr = new InputStreamReader(is);
                            instr = new StringBuffer();
                            int i;
                            File f = new File("/sdcard/jaisb/streamtest");
                            f.delete();
                            f.createNewFile();
                            Log.d("log", "file created");
                            FileOutputStream fos = new FileOutputStream(f);
                            while ((i = isr.read()) != -1) {
                                fos.write(i);
                        }
                        Log.d("log", "file written");
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

        });
    t.start();
    }

}

If I make a textfile called test in my homedir, it wokrs fine, the file arrives without errors... However, if I replace the text by other media (namely picures and music (I've tried JPG and MP3)), the files are corrupted.
Comparing them with the original in hexedit, i noticed that when sending the music file, the problem was that some bytes got lost; the first few bytes of the file were OK, but then it started losing bytes...
When sending a JPG, most bytes were wrong. Even the first four bytes changed from FF D8 FF E0 to FD FD FD FD.
What am I doing wrong? How can I send non-text files via the local network?


text:
Q: Creating multiple tar files in batches duration increases with every batch I've written a script to get all image records from a database, use each image's tempname to find the imagine on disk, copy it to a new folder and create a tar file out of these files. To do so, I'm using PHP's PharData. The problem is the images being TIFF files, and pretty large ones at that (the entire folder of 2000-ish images is 95gb in size).
Initially I created one archive, looped through all database records to find the specific file and used PharData::addFile() to add each file to the archive individually, but this eventually lead to adding a single file taking 15+ seconds.
I've now switched to using PharData::buildFromDirectory in batches, which is significantly faster, but the time to create batches increases with each batch. The first batch got done in 28 seconds, the second in 110, the third one didn't even finish. Code;
$imageLocation = '/path/to/imagefolder';
$copyLocation = '/path/to/backupfolder';

$images = [images];

$archive = new PharData($copyLocation . '/images.tar');

// Set timeout to an hour (adding 2000 files to a tar archive takes time apparently), should be enough
set_time_limit(3600);

$time = microtime(true);
$inCurrentBatch = 0;
$perBatch = 100; // Amount of files to be included in one archive file
$archiveNumber = 1;

foreach ($images as $image) {
    $path = $imageLocation . '/' . $image->getTempname();

    // If the file exists, copy to folder with proper file name
    if (file_exists($path)) {
        $copyName = $image->getFilename() . '.tiff';
        $copyPath = $copyLocation . '/' . $copyName;
        copy($path, $copyPath);
        $inCurrentBatch++;

        // If the current batch reached the limit, add all files to the archive and remove .tiff files
        if ($inCurrentBatch === $perBatch) {
            $archive = new PharData($copyLocation . "/images_{$archiveNumber}.tar");
            $archive->buildFromDirectory($copyLocation);
            array_map('unlink', glob("{$copyLocation}/*.tiff"));
            $inCurrentBatch = 0;
            $archiveNumber++;
        }
    }
}

// Archive any leftover files in a last archive
if (glob("{$copyLocation}/*.tiff")) {
    $archive = new PharData($copyLocation . "/images_{$archiveNumber}.tar");
    $archive->buildFromDirectory($copyLocation);
    array_map('unlink', glob("{$copyLocation}/*.tiff"));
}

$taken = microtime(true) - $time;
echo "Done in {$taken} seconds\n";
exit(0);

The copied images get removed in between batches to save on disk space.
We're fine with the entire script taking a while, but I don't understand why the time to create an archive increases so much in between batch.


text:
Q: Django admin - return the text from a forgeign key as display name I want to have the display name of my drop down in the admin panel to be the location title from the parent model. by default the list shows "SNMPData Object" for all items in the list.
however I want to show the site name, I thought it was as simple as adding self.location but that is throwing the error
error:
coercing to Unicode: need string or buffer, MajorSiteInfoData found

code:
class MajorSiteInfoData(models.Model):
    Location = models.CharField(max_length=200)

    class Meta:
            verbose_name = "Major Site Locations"
            verbose_name_plural = "Major Site Locations"

    def __unicode__(self):
        return self.Location

class SNMPData(models.Model):
    Location = models.ForeignKey(MajorSiteInfoData)
    SNMP_AUTH = models.CharField(max_length=200)
    SNMP_PRIV = models.CharField(max_length=200)

    class Meta:
            verbose_name = "SNMP Data"
            verbose_name_plural = "SNMP Data"

    def __unicode__(self):
        return self.Location

A: The __unicode__ function needs to return a string of what you want to show. Your function should look like:
def __unicode__(self):
    return self.Location.Location

One thing to improve, you shouldn't use the same field names for different models, you might quickly confuse yourself because sometimes you need Location and sometimes you need Location.Location as above. Rename the foreign key to be something else like major_site_info. Also use lower cases with underscores for field names, Camel cases are for class names in python.


text:
Q: "weird" Google Chrome feature, huge address bar pops up I am quite puzzled by this feature since it just seems off.
When I press Ctrl + }* and I'm not in a text box.
*(basically the key below the +, left of Enter)
I get this:

A huge address bar where I can type (in this case I had typed google.com - it's not by default). The with Enter it goes to that address.
I does not have all the extra omnibar functionalities.
I am very intrigued as to why this feature is there, it seems useless (specially having Ctrl + l), it doesn't "fit" the design either.
So if anyone has any ideas as to why that is there, I would like to hear it.
Thank in advance!

A: Looks like a feature of some extension you have installed.


text:
Q: Why are the result of COUNT double when I do two join? I have this tables
device
 id      name         groupId     serviceId
791   Mamie Ortega      205         1832

group
 id   serviceId
205     1832

record
 id          date                      deviceId
792   2017-07-13 13:30:19.740360         784
793   2017-07-13 13:30:19.742799         784

alarms
 id    status    deviceId
241      new        784
242      new        784

I'm running this query
SELECT device.id, device.name, COUNT(records.id) AS "last24HMessagesCount", COUNT(alarms.id) AS "activeAlarmsCount"
FROM device
  INNER JOIN "group" AS "group" ON "device"."groupId" = "group"."id" AND "group"."id" = '205'
  LEFT OUTER JOIN "record" AS "records" ON "device"."id" = "records"."deviceId" AND "records"."date" > '2017-07-12 11:43:02.838 +00:00'
  LEFT OUTER JOIN "alarm" AS "alarms" ON "device"."id" = "alarms"."deviceId" AND "alarms"."status" = 'new'
WHERE "device"."serviceId" = 1832
GROUP BY device.id;

Which give me this result
 id      name       last24HMessagesCount      activeAlarmsCount
791   Mamie Ortega         4                          4

This result is wrong, I'm supposed to have 2 for last24HMessagesCount and activeAlarmsCount.
If I remove one of the count, last24HMessagesCount for example and execute
SELECT device.id, device.name, COUNT(alarms.id) AS "activeAlarmsCount"
FROM device
  INNER JOIN "group" AS "group" ON "device"."groupId" = "group"."id" AND "group"."id" = '205'
  LEFT OUTER JOIN "alarm" AS "alarms" ON "device"."id" = "alarms"."deviceId" AND "alarms"."status" = 'new'
WHERE "device"."serviceId" = 1832
GROUP BY device.id;

The result is correct
 id      name       activeAlarmsCount
791   Mamie Ortega         2

I do not understand, why are the counts double?

A: This is very simple to answer. You have two record and two alarm. You join these and get four records, which you count.
You can workaround this problem by counting distinct IDs:
COUNT(DISTINCT records.id) AS "last24HMessagesCount",
COUNT(DISTINCT alarms.id) AS "activeAlarmsCount"

but I would not recommend this. Why do you join record and alarm anyway? They are not directly related. What you want to join is the number of record and the number of alarm. So aggregate before joining:
SELECT
  device.id,
  device.name,
  records.cnt AS "last24HMessagesCount",
  alarms.cnt AS "activeAlarmsCount"
FROM device
LEFT OUTER JOIN
(
  SELECT deviceId, count(*) AS cnt
  FROM record
  WHERE "date" > '2017-07-12 11:43:02.838 +00:00'
  GROUP BY deviceId
) AS records ON device.id = records.deviceId
LEFT OUTER JOIN
(
  SELECT deviceId, count(*) AS cnt
  FROM alarm
  WHERE status = 'new'
  GROUP BY deviceId
) AS alarms ON device.id = alarms.deviceId
WHERE device.serviceId = 1832
  AND device.groupId = 205;

(I've removed the unnecessary join to the "group" table.)

A: Your joins are producing a Cartesian product along two dimensions.  The simplest solution is to use COUNT(DISTINCT):
SELECT device.id, device.name,
       COUNT(DISTINCT records.id) AS "last24HMessagesCount",
       COUNT(DISTINCT alarms.id) AS "activeAlarmsCount"

This works if the counts are not very large.  An alternative solution is more scalable.  That is to do the aggregation before the LEFT JOINs or using correlated subqueries (or lateral joins).


text:
Q: std::string to char array and char array to string (c++) Right now in my current project i have a string like this :
std::string ordre="0x010x030x000x320x000x01";

And i would like to create a char array looking like this with it (and if possible the reverse action too) :
unsigned char Com[]= {0x01, 0x03, 0x00, 0x32, 0x00, 0x01};

I have no problem working with the string, creating another std::string and getting the 0x01 part in the beginning using ordre.at() for the characters i want. But i can't find a way to put this new string 0x01 into Com[1].
Writing directly :
Com[1]=0x01;

It works but i would like to make something where Com[1] could change.

A:
Right now in my current project i have a string like this :

std::string ordre="0x010x030x000x320x000x01";

And i would like to create a char array looking like this with it (and if possible the reverse action too) :

unsigned char Com[]= {0x01, 0x03, 0x00, 0x32, 0x00, 0x01};

First, "0x01" is different than 0x01. To extract values from the string, you will need to read it in a loop, four characters at a time:
if(ordre.size() % 4)
    throw std::runtime_error{ "invalid string length; format is different" };
std::vector<int> values;

auto b = std::begin(ordre);
const auto e = std::end(ordre);
while(b != e)
{
    std::string s{ b, b+4 };
    values.push_back(std::stoi(s, 0, 16));
    b += 4;
}

A: If you use C++ : use STL structures instead of (strugling with) arrays
If I where you i'll build a std::vector<unsigned char> and fill it dynamically by iterating over the x in the loop.
I would do the vector filling as such:
Note: This code work ith any size input and is not limited to 4 chars substrings. It is therefore more general but less efficient then the other answers code. Choose according to your needs
std::string order = "0x010x020x030x2360x10240x9001";
std::vector<int> coms;

size_t pos = 0, it;
while ((it = order.find("0x", pos + 1)) != std::string::npos)
{
    coms.push_back(std::stoi(order.substr(pos, it-pos), 0, 16));
    pos = it;
}
coms.push_back(std::stoi(order.substr(pos), 0, 16));

gives:
0x01 = 1
0x02 = 2
0x03 = 3
0x236 = 556
0x1024 = 4132
0x9001 = 36865


text:
Q: DataGrid / GridView corrupted columns when saving to Xps I have a table that I need to save as an xps (or pdf) file. To do that, I have a custom control that has a header and the table itself, here's what it looks like in the UI:
http://i.stack.imgur.com/kfGlJ.png (Sorry, I am not allowed to post images yet :) )
 So I just create an instance of this control, pass it a datacontext, measure, rearrange it and write it to an XpsDocument as a visual and it is supposed to be as simple as that. However, in the result xps file it looks different, the columns don't get their width right:
http://i.stack.imgur.com/vgpcz.png
I also tried a ListView with a GridView - same story, the columns shrink.
Here's how I write the xps file:
            var xpsFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Details.xps");
        using (var pack = Package.Open(xpsFileName))
        {
            using (var doc = new XpsDocument(pack))
            {
                var dataContext = SeiteDataContextBekommen(0);
                var visual = BerichtViewErstellen();
                visual.DataContext = dataContext;
                visual.Measure(PageSize);
                visual.Arrange(new Rect(0, 0, PageSize.Width, PageSize.Height));
                visual.UpdateLayout();
                var writer = XpsDocument.CreateXpsDocumentWriter(doc);
                writer.Write(visual);
            }
        }

Here's the Xaml of the DataGrid, although there's not much to see there:
<DataGrid Grid.Row="2" ItemsSource="{Binding MitarbeiterBestellungen}"
              CellStyle="{StaticResource ZelleStyle}"
              AlternatingRowBackground="WhiteSmoke"
              AutoGenerateColumns="False"
              Background="Transparent"
              FontSize="12"
              GridLinesVisibility="None">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Angebeort" Binding="{Binding Standort}" CellStyle="{StaticResource ZentriertZelleStyle}"/>
            <DataGridTextColumn Header="ID" Binding="{Binding MitarbeiterID}"/>
            <DataGridTextColumn Header="Mitarbeiter" Width="*" Binding="{Binding Mitarbeitername}"/>
            <DataGridTextColumn Header="Menge" Binding="{Binding Menge}" CellStyle="{StaticResource ZentriertZelleStyle}"/>
            <DataGridTextColumn Header="Bezeichnung" Width="2*" Binding="{Binding Bezeichnung}"/>
            <DataGridTextColumn Header="Preis" Binding="{Binding Preis, StringFormat=\{0:C\}}"/>
            <DataGridTextColumn Header="OK" Width="64" CellStyle="{StaticResource OkZelleStyle}"/>
        </DataGrid.Columns>
    </DataGrid>

I also tried creating a paginator and wrap my UserControl with a DocumentPage, I tried using VisualsCollator for the Xps writer, but the result is always the same. It looks like I am missing something very simple here, I will be grateful if you could help me find what it is.
BTW, I have to save the control WITHOUT showing it, as it supposed to be done by a windows service later.
P.S. The problem is that I use the * width in some columns. I replaced them with fixed sizes and it now displays correctly. Is there a way to make it work with *s?


text:
Q: How can you place the USB2244 media controller IC into low power or standby modes? I'm using this device - USB2244 and connecting it to an 8-pin NAND flash.
Leaving the TXD pin of this device as NC.
I want to know whether there's an option to make the device go into low power or standby mode.
Like, from the electrical characteristics table, I see two current values. One is for normal active and the other is for suspend current state (page 33).
In that case, there should be an option to make the device go into the suspend state right?
Question 1: In this case, my USB2244 is always connected to NAND flash. In that case, does the USB2244 device always be in the RUN state?
Question 2: Does the SD_clock pin from the USB2244 always generate the frequency to the NAND flash or does it only generate when there's any communication between the devices?
Question 3: As asked before, is there any way to make the USB2244 device go into low power mode as subtly indicated by the suspend current value? Or if not, does the NAND flash through the CMD pin, make the USB2244 device go into low power mode?
Thanks in advance.


text:
Q: how to plot only most abundant species in NMDS? I need to plot an ordination plot showing only let s say the 20 most abundant species.
I tried to do the sum of the species colunm and then select only a certain sum value:
abu <- colSums(dune)
abu
sol <- metaMDS(dune)
sol
plot(sol, type="text", display="species", select = abu > 40)

I get this error: select is not a graphical parameter
I would expect to see only small number of species but it does not happen,
how do you show only a small number of species in the NMDS plot?

A: This is not straightforward. You are getting an error because select is not a parameter for the plot. Unfortunately, the result of the analysis is not a data.frame that could be handled easily (e.g. with tidyverse), and even more unfortunately, the plot() function called is not your standard plot, but a method defined specifically for objects of this class. The authors of this method did not foresee your need, and therefore, we must make the plot manually. But to do that, we need to understand what is plotting and how.
Let us find out more about the object sol:
class(sol)
# [1] "metaMDS" "monoMDS"
methods(class="metaMDS")
# [1] goodness    nobs        plot        points      print       scores      sppscores<- text

Oh good, we have a plot method. After a moment of digging, we find it in the vegan package (not exported, so we need to access it via vegan:::plot.metaMDS). It appears to be a wrapper around a function called ordiplot. We edit the function with edit() to figure out what it is doing. Essentially, it boils down to the following (with loads of unnecessary code):
Y <- scores(sol, display="species")
plot(Y, type="n")
text(Y[,1], Y[,2], rownames(Y), col="red")

This is, more or less, your plot. Choosing the species to show is now trivial, but first we must make sure that rows of Y are in the same order as columns of dune:
all(colnames(dune) == rownames(Y))
Y.sel <- Y[colSums(dune) > 40, ]
plot(Y.sel[,1], Y.sel[,2], type="n", xlim=c(-.8, .8), ylim=c(-.4, .4))
text(Y.sel[,1], Y.sel[,2], rownames(Y.sel), col="red")

We can of course make a much nicer plot. For example, with ggplot (it is definitely possible to make a much nicer plot with base R as well). We could actually show the abundance of the plants using the size esthetics:
library(ggplot2)
library(ggrepel)

Y <- data.frame(Y)
Y$abundance <- colSums(dune)
Y$labels <- rownames(Y)

ggplot(Y, aes(x=NMDS1, y=NMDS2, size=abundance)) +
   geom_point() + geom_text_repel(aes(label=labels)) +
   theme_minimal()

To filter the species by abundance, we now can do the following:
library(tidyverse)
Y %>% filter(abundance > 40) %>%
  ggplot(Y, aes(x=NMDS1, y=NMDS2, size=abundance)) +
    geom_point() + geom_text_repel(aes(label=labels)) +
    theme_minimal()


text:
Q: How did the TARDIS blow up at the every point of the universe? In "The Big Bang" episode the TARDIS was blowing up at the every point of the universe and because of that reason the Doctor could throw Pandorica into the TARDIS and recreates the universe. What does it mean to explode at "every point in the universe"? The TARDIS blew up but why at the every point of universe?

A: The Tardis explosion caused a shock wave in time that led to a "total event collapse" in "The Pandorica Opens".  I think you just have to accept that whatever makes a TARDIS work was sufficiently powerful to destroy space-time if it exploded in such a manner.
To the question "what does this mean". This manifested itself as every star in the universe exploding - presumably in a manner that this would appear simultaneous at Earth if the special effect is taken literally.  That is - a star 4 light years away exploded 4 years in the past and a star ten years away ten years in the past - such that the whole universe goes dark at the same origin moment.
(Note in Doctor Who time can be rewritten in an instant - so those explosions in the past didn't exist until they were caused by the TARDIS.)
However this event also spread cracks in space-time prior to the explosion which was the main plot of Matt Smith Doctor 11's first season.  He was dealing with cracks before the event that caused them happened. In fact the efforts to assassinate the Doctor to prevent the cracks - one of which was blowing up the TARDIS - paradoxically caused them to happen in the first place!
Ultimately the solution was to reboot the universe using the pattern of the old universe.  Thus resulting in a crack free universe and Amy's parent's existing again.  The memories of the season -  which really never happened - as a forked branch in time - gets overlaid onto the memories of the participants like Rory and they proceed to new adventures.  Meanwhile the Silence proceed to plan a new way to deal with the Paradox of the Doctor on Trenzalore.
The transcript of the "Pandorica Opens" from
Chakoteya:

[Pandorica chamber]
(River tries frantically to escape the Tardis as the Doctor is dragged closer and closer to the Pandorica, then fastened into the seat inside it. His arms, torso and head are clamped in place and all his old enemies stare at him.)
DOCTOR: You lot, working together. An alliance. How is that possible?
WHITE: The cracks in the skin of the universe.
STARK: All reality is threatened.
CYBERLEADER: All universes will be deleted.
DOCTOR: What? And you've come to me for help?
STARK: No. We will save the universe from you!
DOCTOR: From me?
CYBERLEADER: All projections correlate. All evidence concurs. The Doctor will destroy the universe.
DOCTOR: No, no, no. You've got it wrong.
CYBERLEADER: The Pandorica was constructed to ensure the safety of the Alliance.
WHITE: A scenario was devised from the memories of your companion.
STARK: A trap the Doctor could not resist.
WHITE: The cracks in time are the work of the Doctor. It is confirmed.
DOCTOR: No. no, no, not me, the Tardis. And I'm not in the Tardis, am I?
WHITE: Only the Doctor can pilot the Tardis.
DOCTOR: Please, listen to me!
WHITE: You will be prevented.
DOCTOR: Total event collapse! Every sun will supernova at every moment in history. The whole universe will never have existed. Please, listen to me!
CYBERLEADER: Seal the Pandorica.
DOCTOR: No! Please, listen to me! The Tardis is exploding right now and I'm the only one who can stop it! Listen to me!
(The Pandorica closes.)
[Tardis]
(River opens the Tardis doors to discover she is parked right up against a rock wall.)
RIVER: I'm sorry, my love.
(The Tardis explodes. As Rory weeps over Amy's body, every star in the universe goes KaBOOM.)

A: The TARDIS is infinite space and time pressed into a police box, at a single time.  When you take infinite space and time and cause it to explode outward, that shatters the fabric of reality at every point in space and time.