text:
Q: Dynamically created  won't position properly I am making a web app that utilizes two textareas, and when a button is clicked one of the textareas is replaced with a div using JavaScript. I am trying to get the div inserted onto the page in the exact position as its textarea predecessor so the user doesn't notice the switch, but for some reason it's not as easy as it should be. The vertical position of the div seems to change based on the content within it. I have a feeling it has to do with
display: inline-block;

in my CSS file, but that's needed to keep the two textareas horizontally centered without a fixed width.
Any help would be appreciated.
The web app can be found on my site: http://lobian.co/code/remove-attributes/. To view the problem, input any amount of text in the left textarea then click "Remove Attributes". The div in question will replace the textarea.
UPDATE:
Musa's answer below fixed the problem.

A: Just give both elements the same vertical-alignment, eg vertical-align:top
DEMO

A: try this
div#color_change {
    padding: 0;
}

You are giving 2px padding of div(44% width) which increases its size.


text:
Q: Missing artifact spring-webmvc:spring-webmvc:jar:4.0.6.RELEASE I am very much new to the world of Java, Spring.
Building my first Maven project today with loads of issues.
I'm unable to get my pom.xml working.
this is the auto XML built in my eclipse and using Maven, Dynamic Web Project.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bapu</groupId>
  <artifactId>SpringMVCDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>spring-webmvc</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet-api</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCDemo</finalName>
  </build>
</project>

A: updated the 4.0.6 to the available version 4.0.3 as per the jars list in WEB-INF\lib folder.
It worked perfect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play framework, best way to search for data, finder vs lists I recently started to use play framework and i have a basic question.
I have this 2 models:
@Entity
public class User extends Model {

...
private int age;
@ManyToOne
private Project project;
...
}

and
@Entity
public class Project extends Model {

...
@OneToMany(mappedBy = "project")
private List<User> members = new ArrayList<User>();
...
}

Now, for one Project p, I want to find all the users with 20 years old.
What is the best way to do it?
Should I create a function in project model to search the list
public List<User> getUsers(int age){
    List<User> temp = new ArrayList<User>();
    for(User u : members)
        if(u.getAge() == age)
            temp.add(u);

    return temp;
}

or should I use a finder
 List<User> temp = User.find.where.eq("age", 20).eq("project", p).findList();

Thanks

A: If you use a list, that means you have to load all users from the database into your application.  If you don't have many users in the database (eg, less than 100), then maybe that's not a problem.  If you have millions of users in the database, your application will fall over, as the database tries to send MB or GB of data to it with all the users.
If you use a finder, that results in a SQL call on the database that just gets the results you want.  Furthermore, if you create an index on the project and the age field, then the database can very efficiently do the search, it doesn't have to loop through each user, it can just go to the index and get the results in a single step.
Also, if the number of users at that age is very large, you may want to do paging.  Using a finder, you can get the database to do the paging, so you only get the current page, instead of having to load all the results into your application and then exclude the pages you aren't interested in.
In general, you should always put the load of finding data on the database, so you should always use a finder.

A: Like many code efficiency question : It depends of your use case.
In one hand, if you load (from the database) a project and display all its members after doing something with specific members (here users with age = 20), to search into a the list already loaded is more efficient.
To search in a list means that all the data in the list will be loaded (if this list is lazy loaded).
In the other hand, if you only doing something with specific users and nothing with other members, only loading the specific members from the database is quickier.
Using a finder let the database limit the data to load in the application (again if the list is lazy loaded), but will reload again the specific members if the list is already eagerly loaded.
Mostly, ORM will lazy load one to many relations. And if you don't need other members for this request you should use the finder method.


text:
Q: Wrong solution for $\int \frac{1 - e^x}{e^x}\, dx$ The solution book gives this as an answer:
$$\int \frac{1-e^x}{e^x}dx = \int \frac{1}{e^x}-\frac{e^x}{e^x}dx = -e^{-x} + C$$
I would think it would be solved this way:
$$\int \frac{1-e^x}{e^x} dx = \int \frac{1}{e^x} -1 \; dx = -e^{-x}-x + C$$

A: Yes, your approach is correct.
But, remember, you can always check your answer when finding an antiderivative:
We have:
$$
{d\over dx} (-e^{-x}+C)=e^{-x}\ne e^{-x}-1={1-e^x\over e^x};
$$
so the book is wrong.
However:
$$
{d\over dx} (-e^{-x}-x+C)=e^{-x}-1 = {1-e^x\over e^x};
$$
so, you are right.

A: The best way to see if you been right in solving your integral is to derive both sides.
As we can see, the books answer:
$$\frac{{d}(-e^{-x}+C)}{dx}\neq \frac{ d\{{\int \frac{1}{e^x}-\frac{e^x}{e^x}dx}\}}{dx} $$


text:
Q: How to find out which random variable was chosen? This question is related to my other question ( Need help with a model, Whatsapp data analysis ).
Suppose we have random variables $X_1,\cdots,X_m$ bernoulli distributed with probability $p$, $D_1,\cdots,D_m \sim Exp(\lambda_d)$, $P_1,\cdots,P_m \sim Exp(\lambda_P)$ and let $d_i := X_i D_i + (1-X_i)P_i$ for $i=1,\cdots,m$.
Suppose further that $\lambda_d >> \lambda_P$. Then how can we find out by observing only $d_i$ for which $X_i = 1$? In my other question it was suggested to take the mean $\widehat{d}$ of $d_i$ and if $d_i > \widehat{d}$ then to infer that $X_i = 0$. But this procedure is more a heuristic than an actual argument. Does somebody have an idea on how to make this to an argument?
I know of Otsu's method in computer vision to cluster an image into black and white. (https://en.wikipedia.org/wiki/Otsu%27s_method) Do you think this method could be applied in this situation?
Edit:
By suggestion of  Anthony Quas, I will sort the $d_i$ and then look for a large gap. The gap is found by maximizing the inter-sum of squares as in Otsu's method. Here is the R-code to find the index $I$ at which the cutoff occurs:
S <- 0
I <- -1
st <- sort(di)
for(i in seq(2,m-2)){
    A <- st[1:i]
    B <- st[(i+1):m]
    mA <- mean(A)
    mB <- mean(B)
    ssInter <- length(A)*(mA-mean(di))^2+length(B)*(mB-mean(di))^2
   if( ssInter > S){ S <- ssInter; I <- i}
}

A: I would do it like this: the log- likelihood with respect  to the measure in which they are all $\lambda_p$ is $ \sum X_i (log(\frac {\lambda_q}{\lambda_p}) - ({\lambda_p} - {\lambda_q})(Z_i)) + log( {N \choose j} p^j (1-p) ^ {n-j})$, where $Z_i$ is your observation and my X_i are 0 or 1,  however, having chose j I am sure that you maximize the expression by choosing the j largest or j smallest $Z_i$ and then it very likely follows that the estimated $\lambda$s should be  the mean of the largest resp smallest. My claim is that this procedure is reasonable because it is based on maximizing the likelihood.  I would be surprised if this exact problem hasn't been considered, and would search under 'missing data' (the X_i) .  I changed your notation to ps and qs so I could warn you  to watch my p's and q's, the signs may be wrong by the idea  should be correct.

A: This first paragraph has been corrected
So assuming everything is known, and that $\lambda_d\gg\lambda_P$, the threshold where you should cut off between assuming $X=1$ and $X=0$ is roughly given by the solution of $pe^{-\lambda_d T}=(1-p)\lambda_P T$.
The left side is the probability that a $d_i$ that is a $D$ value lies above the threshold; and the right side is the probability that a $d_i$ that is a $P$ value lies below the threshold. When I computed the threshold for your parameter values, I got a threshold of 33.
I will assume that $mp$ and $m(1-p)$ are large. Given the very large ratio between $\lambda_P$ and $\lambda_d$, it is quite wasteful to use the mean as the cutoff (it gives too many false $X=1$'s when the $P_i$ happen to be somewhat small relative to $1/\lambda_P$).
Probably quite a good way to locate the cutoff in practice is to sort the $d_i$'s into order and look at the gaps. In the $\lambda_D$ part of the distribution, these should be something like $1/(mp\lambda_d)$, whereas in the $\lambda_P$ part of the distribution, they should be much bigger, around $1/(m(1-p)\lambda_P)$. I would try to find a way to guess where the gaps change; and then maybe double the threshold to be safe (you get very few false $D$'s this way and double the number of false $P$'s), but this number is something like 0.1% for your parameter range.


text:
Q: Connection to SQL Server in ArcMap I want to add database connection to SQL Server from ArcMap.
But, I don't know what to write as 'instance'. I've tried 'NT Service\MSSQLSERVER' but it doesn't work.

A: If you installed SQL server with default instance on your computer, then just write ".\". It means localhost.
You can find instance name from services in windows:
Go to windows services => find SQL Server.The default instance name is MSSQLSERVER.
Other instance names also are between parentheses.

If SQL server installed on a server and you want to connect to this, you should use server IP (You may need a VPN).
In the below image you can see an IP and an instance name (not default instance).You maybe need to use a port for connecting to a server like this:
(192.0.0.0:2222\instancename)

A: I my connections to SQL Server I put the server IP address or the server name in the Instance parameter, but I'm using Database Authentication as Authentication Type.

A: I guess it depends on how the servers/instances are set up. Check with whoever has control on that. At our place we use server name along the lines of this:

The database instance, databases and users are set up by out IT contractor.


text:
Q: ERROR: 'Variable does not exist I have a trigger bellow which calculates a sum of field in a related field  in  custom object . I am getting an error massage Variable does not exist:House_Improvements__c. Any ideas how can I resolve the issue?
Thanks
trigger SumCalculations on House_Improvements__c (after insert,after update, after delete,after undelete) {
    List<id> PropertyIds = new List<id>();
    if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate){
        For(House_Improvements__c himp1 : Trigger.new){
            PropertyIds.add(himp1.Property__c);
        }
    }
    if(Trigger.isDelete){
        For(House_Improvements__c  himp1 : Trigger.old){
            PropertyIds.add(himp1.Property__c);
        }
    }
    List<Property__c> PropertyToUpdate = new List<Property__c>();
    decimal sum = 0;
    if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate){
        For (Property__c q: [SELECT id,SUM_Calculations__c, (SELECT id, Price__c FROM House_Improvements__r) FROM Property__c WHERE id =:PropertyIds]){
            sum = 0;
            for(House_Improvements__c   p : q.House_Improvements__r)
                sum = sum + p.House_Improvements__c ;
            q.SUM_Calculations__c  = sum;
            PropertyToUpdate .add(q);
        }
        try{
            update PropertyToUpdate ;
        }Catch(Exception e){
            System.debug('Exception :'+e.getMessage());
        }
    }
    if(Trigger.isDelete){
        For(Property__c q : [SELECT SUM_Calculations__c ,(SELECT id,Price__c FROM House_Improvements__r) FROM Property__c WHERE id =: PropertyIds]){
            sum = 0;
            for(House_Improvements__c  p : q.House_Improvements__r)
                sum = sum + p.House_Improvements__c ;
            q.SUM_Calculations__c  = sum;
           PropertyToUpdate .add(q);
        }
        try{
            update PropertyToUpdate ;
        }Catch(Exception e){
            System.debug('Exception :'+e.getMessage());
        }
    }
}

A: You can't add a List<SObject> to a Decimal, so sum = sum + p.House_Improvements__c would fail even if you used the correct reference to the child list (House_Improvements__r).
Incorrect:
sum = sum + p.House_Improvements__c;

Correct
for (House_Improvements__c child : p.House_Improvements__r)
    sum += child.Price__c;

Please note, you should always use singular object names. Your code would be much less confusing if you had done so here. If it is not too late, rename your object to House_Improvement__c.


text:
Q: Charles SSL Proxy works for chrome but not for the apps I'm using Nexus 5X device running Android 7. I failed to setup the proxy using the recent instructions from Charles Proxy documentation. I installed certificate, but wifi settings or nugat are extended. I can set charles as a certificate but that won't let me connect to that wifi (authentication problem). So I leave it as "don't check correctness". I don't even know if that's relevant.
The thing is when I try to sniff on my app https calls I see SSLHandshake: Received fatal alert: certificate_unknown
However if I run a web client using chrome on the same device - I can read calls to the same api.
The bottom line is it works for a browser but not for my app. I checked on other apps aswell. Same output.
The reason I ask here is because maybe I have to add some unsafe client to my retrofit api setup - hopefully not.

A: Here is how you need to configure you apk in order to make CharlesProxy work in Android 7.
Android
As of Android N, you need to add configuration to your app in order to have it trust the SSL certificates generated by Charles SSL Proxying. This means that you can only use SSL Proxying with apps that you control.
In order to configure your app to trust Charles, you need to add a Network Security Configuration File to your app. This file can override the system default, enabling your app to trust user installed CA certificates (e.g. the Charles Root Certificate). You can specify that this only applies in debug builds of your application, so that production builds use the default trust profile.
Add a file res/xml/network_security_config.xml to your app:
<network-security-config>
  <debug-overrides>
    <trust-anchors>
      <!-- Trust user added CAs while debuggable only -->
      <certificates src="user" />
    </trust-anchors>
  </debug-overrides>
</network-security-config>

Then add a reference to this file in your app's manifest, as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <applicationandroid:networkSecurityConfig="@xml/network_security_config" ... >
        ...
    </application>
</manifest>

Here you can find more details:
https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

A: In Charles,  select Help -> SSL Proxying -> Install Charles Root Certificates in IOS Simulators, close the iOS Simulator and restart the simulator. It should work now.


text:
Q: Clear Grid Label Output from a For Loop in a Function Tkinter I am trying to clear out my second column of information to which I am printing out in grid format from a for loop within a function using a label. My goal is when I click my Generate button the old output will clear out.
Here is the code:
root = Tk()
root.geometry("700x700")
root.title("NPC Maker")
root.config(bg="light grey")

#Define details label
details_label = Label(root)
npc = {}

#Set NPC Properties list
npc_properties = ["Race",
                "Sex",
                "Name",
                "Height",
                "Weight",
                "Hair Style",
                "Hair Color",
                "Face",
                "Eye Color",
                "Skin Tone",
                "Voice Tone"]

#Print NPC properties as row headers
for index, row in enumerate(npc_properties):
        properties_label = Label(root, text = row + ":", font=("Aerial 12 bold"))
        properties_label.grid(row=index + 1, column=0, sticky=W, pady=18)

#Generate funciton
def generate():
        state = True
        while state == True:
                if sex_choice.get() == "Male":
                        if race_choice.get() == "Dwarf":
                                npc = choose_dwarf_male()
                        elif race_choice.get() == "Elf":
                                npc = choose_elf_male()
                        elif race_choice.get() == "Gnome":
                                npc = choose_gnome_male()
                        elif race_choice.get() == "Halfling":
                                npc = choose_halfling_male()
                        elif race_choice.get() == "Human":
                                npc = choose_human_male()
                elif sex_choice.get() == "Female":
                        if race_choice.get() == "Dwarf":
                                npc = choose_dwarf_female()
                        elif race_choice.get() == "Elf":
                                npc = choose_elf_female()
                        elif race_choice.get() == "Gnome":
                                npc = choose_gnome_female()
                        elif race_choice.get() == "Halfling":
                                npc = choose_halfling_female()
                        elif race_choice.get() == "Human":
                                npc = choose_human_female()
                else:
                        pass

                for index,(key, value) in enumerate(npc.items()):
                        details_label = Label(root, text = value, font=("Aerial 12 bold"))
                        details_label.grid(row=index + 1, column=1, sticky=W, pady=18)
                state = False
        details_label.destroy()

        return npc

#Choose Sex of NPC
sex_options = ["Male", "Female"]
sex_choice = StringVar()
sex_choice.set("Choose Sex")
#Choose Race of NPC
race_options = ["Dwarf", "Elf", "Gnome", "Halfling", "Human"]
race_choice = StringVar()
race_choice.set("Choose Race")
#Sex dropdown menu
sex_dropdown_menu = OptionMenu(root, sex_choice, *sex_options).grid(row=0, column=0, pady=15, padx=5)
#Race dropdown menu
race_dropdown_menu = OptionMenu(root, race_choice, *race_options).grid(row=0, column=1, pady=15, padx=5, sticky=W)

#Generate NPC Button
generate_button = Button(root, text="Generate NPC", command=generate).grid(row=0, column=2, pady=15, padx=5, sticky=W)

root.mainloop()

As you can see I tried to do a while loop and just end the state and destroy the grid output but not seeming to work. I cannot access that details_label Label within that function to clear it out.

A: Since you use same variable details_label in the for loop, so it only references the last created label. Suggest to change details_label to a list to store the instances of labels.  You can then using this list to destroy previously created labels before populating new labels.
Also the while loop is not necessary.
Below is modified generate():
details_label = []
npc = {}

#Generate funciton
def generate():
    # need to declare npc as global, otherwise the global one will not be updated
    global npc
    if sex_choice.get() == "Male":
        if race_choice.get() == "Dwarf":
            npc = choose_dwarf_male()
        elif race_choice.get() == "Elf":
            npc = choose_elf_male()
        elif race_choice.get() == "Gnome":
            npc = choose_gnome_male()
        elif race_choice.get() == "Halfling":
            npc = choose_halfling_male()
        elif race_choice.get() == "Human":
            npc = choose_human_male()
    elif sex_choice.get() == "Female":
        if race_choice.get() == "Dwarf":
            npc = choose_dwarf_female()
        elif race_choice.get() == "Elf":
            npc = choose_elf_female()
        elif race_choice.get() == "Gnome":
            npc = choose_gnome_female()
        elif race_choice.get() == "Halfling":
            npc = choose_halfling_female()
        elif race_choice.get() == "Human":
            npc = choose_human_female()
    else:
        npc = {}

    # destroy current labels
    for w in details_label:
        w.destroy()

    # clear the list
    details_label.clear()
    # populate new labels
    for index,(key, value) in enumerate(npc.items()):
        details_label.append(Label(root, text=value, font=("Aerial 12 bold")))
        details_label[-1].grid(row=index+1, column=1, sticky=W, pady=18)

    # since this function is triggered by a button click
    # the return value will be ignored/discarded
    return npc


text:
Q: The content doesn't show when hitting the back `button` of my browser Below is my router.js  and this is the example of url
    www.myUrl/slugName and the page itself show all the content and data I need.
But when I go to www.myUrl/slugName/cities/1/areas and hit the
    back button of my browser, the content of www.myUrl/slugName doesn't show.
Does anyone had the same experience on why the content of my
    www.myUrl/slugName doesn't show. Is there something wrong on my
    router.js? Also, when I refresh the page the expected content is shown.
this.route('landing-page', { path: ':slug' }, function() {
   this.route('cities', function() {
      this.route('show', { path: ':city_id/areas' });
   });
});

Below is my route.js
model(params) {
 return Ember.RSVP.hash({
   shop:      this.store.findRecord('shop', params.slug)
                .catch(() => this.transitionTo('welcome.shops.index')),
   cities: this.store.query('city', {
     filter: { shop: { slug: params.slug } }
   }),
 });
},


text:
Q: Using a for loop with an if else statement I'm kinda new to this and I was wondering if I could ask for some help. I'm kinda stuck with this function I'm trying to create in googlescript. Let me give you a rundown on how I want it to work. Given 2 worksheets, it looks at the dataset in sheet 1, and if the (i,12) has a value of Open then it will copy the entire row and paste it to the next empty row on sheet 4 (so it offsets down 1 row). If the value is Closed then it would proceed to evaluate the next i. This goes on until last row with values in sheet 1.
function UpdateList(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var dSheet = ss.setActiveSheet(ss.getSheets()[0]);
    var gSheet = ss.setActiveSheet(ss.getSheets()[3]);
    var lRow = dSheet.getLastRow();
    var lCol = dSheet.getLastColumn();
    var i
    var j = 1

    for (i = 0; i < lRow; i++) {
        if (dSheet.getRange(i, 12).getValue() == "Open") {
          dSheet.getRange(i,1,0,lCol).copyValuesToRange(gSheet.setRange(j,1))
        } else {

        }
    }
}

A: You are using getValue() get a single cell value on every loop.  That slows your code down.  Get the entire column of data, then loop through the array. To do that you need to use getValues() which returns a two dimensional array.  If you are only getting data from one column, then every inner array will only have one element.
Getting at the inner arrays of the outer array is different for a single row or a single column.  If you get a 2D array of a single row, then there will only be one inner array.
[[cell one, cell two, cell three, etc]]

In the above 2d array, there is only one inner array.  So you can easily get the inner array simply by using index zero.
var innerArray = outerArray[0];

If you are getting a single column of data from the spreadsheet, you'll have lots of inner arrays.
[[one],[two],[three],[etc]]

In that case, you can't simply get the zero index of the outer array.  In this case you could have two For loops, one nested inside the other one.  The outer loop will get each inner array, and the inner loop will get the contents of the inner array.


text:
Q: xmlsec1 saml signing: failed to find default node with name="Signature" I am having a bit of trouble signing the following saml message:
<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Destination="https://sp/sso/assert" ID="id-qOKj7lEjHF9LLlTjt" InResponseTo="_cd59dfa2245177f214bfc5252c873e702ad29640c3" IssueInstant="2018-07-06T07:34:48Z" Version="2.0">
    <saml2:Issuer>http://myidp/sso</saml2:Issuer>
    <ds:Signature>
        <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
            <ds:Reference URI="#_50247aab9621ee91aaca836e20de20dc">
                <ds:Transforms>
                    <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                </ds:Transforms>
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <ds:DigestValue/>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue/>
        <ds:KeyInfo>
            <ds:X509Data>
                <ds:X509Certificate>MIIC8jCCAlugAwIBAgIJAJHg2V5J31I8MA.....</ds:X509Certificate>
            </ds:X509Data>
        </ds:KeyInfo>
    </ds:Signature>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </saml2p:Status>
    <saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="id-RytehFWT2t5Bem6UH" IssueInstant="2018-07-06T07:34:48Z" Version="2.0">
        <saml2:Issuer>http://myidp/sso</saml2:Issuer>
        <saml2:Subject>
            <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">test@test.com</saml2:NameID>
            <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml2:SubjectConfirmationData InResponseTo="_cd59dfa2245177f214bfc5252c873e702ad29640c3" NotOnOrAfter="2018-07-06T07:34:48Z" Recipient="https://sp/assert"/>
            </saml2:SubjectConfirmation>
        </saml2:Subject>
        <saml2:Conditions NotBefore="2018-07-06T07:34:48Z" NotOnOrAfter="2018-07-08T08:52:24.242Z">
            <saml2:AudienceRestriction>
                <saml2:Audience>test_audience</saml2:Audience>
            </saml2:AudienceRestriction>
        </saml2:Conditions>
        <saml2:AuthnStatement AuthnInstant="2018-07-06T07:34:48Z" SessionIndex="_72c6639cdbf65c0b2eed63847990b13a">
            <saml2:AuthnContext>
                <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml2:AuthnContextClassRef>
            </saml2:AuthnContext>
        </saml2:AuthnStatement>
    </saml2:Assertion>
</saml2p:Response>

Whenever I launch the command to sign using xmlsec1, I get the following message:
Error: failed to find default node with name="Signature"
Error: failed to load template "/tmp/test.xml"
Error: failed to sign file "/tmp/test.xml"

As you can see in my SAML message, I already have a Signature tag, and I checked that my XML is valid, so I am a bit stuck right now. Can anyone locate my problem?

A: It turns out I was missing the signature node in the Assertion part of the message, you need to have both if you want to sign the message AND the assertion.


text:
Q: How do I always download the latest version of phpmyadmin with python? I always want to automatically download the latest version of phpmyadmin using a python script. https://www.phpmyadmin.net/files/ The problem is that if I insert the link of the latest version in my Script (https://files.phpmyadmin.net/phpMyAdmin/5.0.1/phpMyAdmin-5.0. 1-all-languages.zip) and eventually version 5.0.2 comes out, the script still downloads version 5.0.1.
Does anyone have an idea how to always download the latest version using the same link?

A: https://www.phpmyadmin.net/about-website/
https://www.phpmyadmin.net/home_page/version.txt contains all you need to build a script.
For automatically checking version information, we have several file formats available as well:
https://www.phpmyadmin.net/downloads/list.txt - list of all current downloads for latest version
https://www.phpmyadmin.net/home_page/version.txt - version, date and download URL for latest version
https://www.phpmyadmin.net/home_page/version.js - embeddable javascript code with version and release date information
https://www.phpmyadmin.net/home_page/version.json - JSON with version and release date information


text:
Q: Toggle true/false using vuex modules? i am using vuex modules and i have a module named customer.js. In that i have a state showName which is by default set to false. I set a mutation to toggle that state. and in my about.vue file i have a button that calls that mutation but everytime i try to run that mutation, it gives me an error message  Property or method "showCustomerName" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

In my customer.js module

enter code here:    state: {
     showName:false,
 },
  mutations: {
    showCustomerName : state => {
      state.showName = !state.showName
      console.log('works??!!!')
   }
 },
 actions: {

 }
})

In my about.vue file
 <template>
    <div>
   <button @click="showCustomerName">Click Me</button>
   </div>
  </template>

 <script>
   import {mapMutations} from "vuex"

 export default {
 methods : {
   ...mapMutations ([
    "customer/showCustomerName"
    ])
  }
 }
 </script>

I would assume this would work, but not sure what i am doing wrong. Thank you.

A: Okay so figured it out, instead of ...mapMutations ([
    "customer/showCustomerName"
    ])
change to
...mapMutations ('customer',{
showCustomerName: "showCustomerName"
})


text:
Q: Find coordinates of equidistant points in Bezier curve I have to find points (say 10 points) in Bezier curve with 2 control points such that they are at equidistant positions in the curve. Currently I am using the following formula which gives me points but they are not equidistant.
t = ………..from (1/10 to 10/10);
q1 = t * t * t * -1 + t * t *  3 + t * -3 + 1;
q2 = t * t * t *  3 + t * t * -6 + t *  3;
q3 = t * t * t * -3 + t * t *  3;
q4 = t * t * t;

coordinates of a point:
x = q1 * startPointxValue + q2 * controlPoint1xValue + q3 * controlPoint2xValue + q4 * endPointxValue;
y = q1 * startPointyValue + q2 * controlPoint1yValue + q3 * controlPoint2yValue + q4 * endPointyValue;

I tried to use this but due my bad understanding, still unable to correct the values :(. Please help me in finding the values.
attaching sample image of required points (here 11):

A: The brute force approach is to just use a polyline approximation. If this is just for graphics, it will certainly be accurate enough. Even for more rigorous applications, it will probably be OK.
Compute a large number of points $n$ along the curve. I'd recommend somewhere in the range $n=50$ to $n=1000$, depending on your accuracy requirements and processor speed. Specifically, let the step-length be $s = 1/n$, and let $t_i = i*s$, and let $P_i = C(t_i)$ be a point on the curve, for $i = 0,1, \ldots , n$. Also, let $c_i = \Vert P_i - P_{i-1} \Vert$ be the $i$-th chord length, and let
$$d_i = \frac{\sum_{j=0}^i c_j}{\sum_{j=0}^n c_j}$$
So, in words, $d_i$ is the fractional distance along the polyline $P_0P_1 \ldots P_n$ at the $i$-th point $P_i$.
Now suppose you want to distribute $m+1$ points $Q_0, \ldots , Q_m$ at equal arclengths along the curve. Here's how you locate the $r$-th point $Q_r$.
Let $d = r/m$. Find $i$ such that $d_{i} \le d \le d_{i+1}$. Then let
$$ u = \frac{d - d_i}{d_{i+1} - d_i} $$
$$ t = t_i + u*s = (i+u)*s$$
$$ Q_r = C(t)$$
Getting all the indexing correct is a chore -- there are lots of opportunities for off-by-one errors. But, other than that, it's straightforward. The basic idea is that distances along the curve can be approximated by distances measured along the polyline $P_0P_1 \ldots P_n$.
You can use your existing code to calculate any point $(x,y) = C(t)$ on the curve.
Here's an implementation in C#:
class Program
{
   static void Main()
   {
      Position endpt0, endpt1, control0, control1;
      endpt0 = new Position(100,100);    control0 = new Position(200,200);
      endpt1 = new Position(100,200);    control1 = new Position(400,200);
      BezierCurve curve = new BezierCurve(endpt0, control0, control1, endpt1);

      // Construct polyline with large number of points
      int n = 1000;
      double s = 1.0/(n-1);
      double[] tt = new double[n];
      Position[] PP = new Position[n];
      double[] cc = new double[n];
      for (int i = 0 ; i < n ; i++)
      {
         tt[i] = i*s;
         PP[i] = curve.Position(tt[i]);
         if (i > 0) cc[i] = Distance(PP[i], PP[i-1]);
      }

      // Get fractional arclengths along polyline
      double[] dd = new double[n];
      dd[0] = 0;
      for (int i = 1 ; i < n ; i++) dd[i] = dd[i-1] + cc[i];
      for (int i = 1 ; i < n ; i++) dd[i] = dd[i]/dd[n-1];

      // Number of points to place on curve
      int m = 10;
      double step = 1.0/(m-1);
      Position[] QQ = new Position[m];

      for (int r = 0 ; r < m ; r++)
      {
         double d = r*step;
         int i = FindIndex(dd, d);
         double u = (d - dd[i]) / (dd[i+1] - dd[i]);
         double t = (i + u)*s;
         QQ[r] = curve.Position(t);
      }
   }

   // Find index i such that dd[i] < d < dd[i+1]
   public static int FindIndex(double[] dd, double d)
   {
      int i = 0;
      for (int j = 0 ; j < dd.Length ; j++)
      {
         if (d > dd[j]) i = j;
      }
      return i;
   }
}

A: As said by Bubba, an option is to flatten the curve (sample it as a polyline) then approximate the curvilinear abscissas by accumulation of chord lengths.
Another option if to solve the ODE
ds / dt = √(x'² + y'²)

for constant increments of s. So we formulate as
dt = √(x'(t)² + y'(t)²) ds

and integrate for example by Runge-Kutta.
Note that the first approach does the same thing, but integrating by a first order method.


text:
Q: Style Radio Button and Text inside AlertDialog I want to show a radio list inside an AlertDialog with custom styling, something like .
So I created a custom theme and provided that as an argument to AlertDialog.Builder's constructor.
Here's the code for showing the dialog :
private void showSortDialog() {
final CharSequence[] options = new String[] {"Relevance", "Newest"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivityReference(),
                                                          R.style.RadioDialogTheme);
    builder.setTitle("Sort by");
    builder.setSingleChoiceItems(options, -1, new DialogInterface.OnClickListener() {
    . . . .
    builder.create().show();
}

Here's the style :
<style name="RadioDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:textColorAlertDialogListItem">@drawable/radiobutton_textcolor_selector
    </item>
    <item name="android:listChoiceIndicatorSingle">@drawable/apptheme_btn_radio_holo_light
    </item>
</style>

I was able to find a couple of attributes which I added in my style to change the color of the radio button / text based on their state. But I'm not able to customize the text appearance (I want to change the size, provide padding etc).
I'm sure there is some attribute using which I can style the text but I'm not able to find it. Can anyone please help me with this? Thanks.

A: I guess it's almost you need:
fun showSortDialog(context: Activity) {
    val options = arrayOf(
        "Relevance",
        "Price - Low to High",
        "Price - High to Low",
        "Newest"
    )
    val builder = AlertDialog.Builder(context, R.style.MultiChoiceAlertDialog)
    val view = context.layoutInflater.inflate(R.layout.dialog_custom, null, false)
    val radioGroup = view.findViewById<RadioGroup>(R.id.radiogroup)

    val purpleColor = ContextCompat.getColor(context, R.color.purple)
    val radioStyle = ContextThemeWrapper(radioGroup.context, R.style.MyRadioButton)
    for (option in options) {
        val radioButton = RadioButton(radioStyle)
        radioButton.setText(option)
        radioGroup.addView(radioButton)
    }
    radioGroup.setOnCheckedChangeListener { group, checkedId ->
        for (child in radioGroup.children) {
            child as RadioButton
            if (child.id == checkedId) {
                child.setTextColor(purpleColor)
            } else {
                child.setTextColor(Color.BLACK)
            }
        }
    }
    builder.setView(view)
    builder.show()
}

styles:
 <style name="YourAlertDialog.Button" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/colorPrimary</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:gravity">left</item>
    <item name="android:letterSpacing">0</item>
</style>
<style name="MultiChoiceAlertDialog" parent="Theme.MaterialComponents.Light.Dialog.Alert">
    <item name="buttonBarPositiveButtonStyle">@style/YourAlertDialog.Button</item>
    <item name="buttonBarNegativeButtonStyle">@style/YourAlertDialog.Button</item>
    <item name="buttonBarNeutralButtonStyle">@style/YourAlertDialog.Button</item>
    <item name="android:background">#fff</item>
    <item name="android:textColorPrimary">#000</item>
    <item name="android:textColor">@drawable/selector_custom</item>
    <item name="android:colorActivatedHighlight">#0f0</item>
    <item name="android:colorControlActivated">#00f</item>
    <item name="colorControlNormal">@color/gray</item>
    <item name="colorControlActivated">@color/purple</item>
    <item name="dialogCornerRadius">8dp</item>
</style>

<style name="MyRadioButton" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/gray</item>
    <item name="colorControlActivated">@color/purple</item>
</style>

and the custom layout(dialog_custom.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:text="Sort by"
    android:textColor="#000"
    android:textSize="20sp" />
<RadioGroup
    android:id="@+id/radiogroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</RadioGroup>

A: First of All, make dialog layout like this:
<androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_title"
                android:layout_width="match_parent"
                android:layout_height="@dimen/_40sdp"
                android:layout_gravity="center|start"
                android:layout_marginStart="@dimen/_25sdp"
                android:layout_marginTop="@dimen/_20sdp"
                android:layout_marginEnd="@dimen/_25sdp"
                android:layout_marginBottom="@dimen/_10sdp"
                android:fontFamily="@font/lato_bold"
                android:gravity="center|start"
                android:text="@string/text_select_speciality"
                android:textColor="@color/color_dark_grey"
                android:textSize="@dimen/_20ssp" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rv_speciality_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/_15sdp"
                tools:listitem="@layout/item_speciality" />

Then make an item for Recyclerview like this In my case with Checkbox but you can use Radiobutton:
<androidx.appcompat.widget.AppCompatCheckBox
        android:id="@+id/rb_title"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_40sdp"
        android:layout_marginStart="@dimen/_25sdp"
        android:layout_marginEnd="@dimen/_25sdp"
        android:button="@drawable/radio_button_selector"
        android:gravity="center|start"
        android:paddingStart="@dimen/_20sdp"
        android:paddingEnd="@dimen/_20sdp"
        android:text="@string/text_speciality"
        android:textColor="@color/color_dark_grey"
        android:textSize="@dimen/_14ssp" />

Then Initialize dialog & Recyclerview like below:
private void showDialog() {
        dialog = new Dialog(LastActivity.this, R.style.DialogSlideAnim);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog);
        Objects.requireNonNull(dialog.getWindow()).setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        if (dialog.getWindow() != null)
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        AppCompatTextView tv_title = dialog.findViewById(R.id.tv_title);
        tv_title.setText(getString(R.string.text_select));

        FrameLayout fl_close = dialog.findViewById(R.id.fl_close);
        fl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        LinearLayoutCompat btn_ok = dialog.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        RecyclerView rv_list = dialog.findViewById(R.id.rv_list);
        if (Adapter == null) {
            Adapter = new Adapter(LastActivity.this);
        }
        Adapter.doRefresh(specialityList);
        if (rv_list.getAdapter() == null) {
            rv_list.setHasFixedSize(true);
            LinearLayoutManager layoutManager = new LinearLayoutManager(DoctorRegisterLastActivity.this);
            rv_list.setLayoutManager(layoutManager);
            rv_list.setAdapter(specialityAdapter);
        }
        dialog.show();
    }

A: The attribute textSize works for me:
<item name="android:textSize">18sp</item>


text:
Q: 3-column divs with dynamic middle - right div dropping down Started a project involving a 3-column div at the top - 300px/dynamic/350px.  The right div falls below the others:  http://jsfiddle.net/tspencer103/b49mfno4/1/.
I have tries several suggestions here like http://jsfiddle.net/22YBU/.  No luck.  Any suggestions? Thanks.
 div #div_1 {
   float: left;
   height: 50px;
   background-color: red;
   width: 300px;
 }

 div #div_2 {
   height: 50px;
   margin: 0px 350px 0px 300px;
   background-color: green;
   text-align: center;
 }

 div #div_3 {
   float: right;
   height: 50px;
   background-color: blue;
   width: 350px;
 }

LEFT STATIC 300px

CENTER DYNAMIC

RIGHT STATIC 350px

A: If you're interested in a simple, more modern approach, drop the floats and use flexbox:
HTML (no changes)

LEFT STATIC 300px

CENTER DYNAMIC

RIGHT STATIC 350px

CSS
#container {
  display: flex;
  }

#div_1 {
  background-color: red;
  width: 300px;
  height: 50px;
  }

#div_2 {
  background-color: green;
  text-align: center;
  height: 50px;
  flex: 1; /* flexible width */
  }

#div_3 {
  background-color: blue;
  width: 350px;
  height: 50px;
  }

DEMO
Flexbox benefits:

*

*minimal code; very efficient

*centering, both vertically and horizontally, is simple and easy

*equal height columns are simple and easy

*multiple options for aligning elements

*it's responsive

*unlike floats, which offer limited layout capacity because they were never intended for building layouts, flexbox is a modern (CSS3) technique with a broad range of options.

Note that flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer.


text:
Q: How to test a \newif conditional in expl3 Suppose I want to test an \ifSomething conditional that is defined by a package which may or may not be loaded. I know how to do this in plain LaTeX, but I'd like to define an expl3 conditional to do the same job. How would I go about doing this?
The MWE illustrates the case with the bidi package and its \if@RTL conditional.
% !TeX program = xelatex
\documentclass{article}
\usepackage{xparse}
\usepackage{bidi}

\makeatletter
% traditional method
\newcommand{\TestRTL}{%
  \@ifundefined{if@RTL}{NO BIDI}%
  {%
    \if@RTL%
    YES%
    \else
    NO%
    \fi%
  }%
}

\ExplSyntaxOn

% non-working first attempt
\prg_new_conditional:Nnn \stdt_if_rtl: {p,T,F,TF}
{
  \bool_lazy_and:nnTF {\bool_if_exist_p:N \if@RTL}  {\bool_if_p:N \if@RTL}
  { \prg_return_true: }
  { \prg_return_false: }
}

\NewDocumentCommand{\TestRTLAlt}{}{
  \stdt_if_rtl:TF {YES} {NO}
  }

\ExplSyntaxOff
\makeatother

\begin{document}

\TestRTL % \TestRTLAlt

\begin{RTL}
  \TestRTL % \TestRTLAlt
\end{RTL}

\end{document}

A: After some experimentation, this appears to do the trick.
% !TeX program = xelatex
\documentclass{article}
\usepackage{xparse}
\usepackage{bidi}

\makeatletter
\ExplSyntaxOn

\prg_new_conditional:Nnn \stdt_if_rtl: {p,T,F,TF}
{
  \bool_lazy_and:nnTF {\bool_if_exist_p:N \@RTLtrue}  {\cs_if_eq_p:NN \if@RTL \iftrue}
  { \prg_return_true: }
  { \prg_return_false: }
}

\NewDocumentCommand{\TestRTLAlt}{}{
  \stdt_if_rtl:TF {YES~IT~IS} {NO~IT~ISN'T}
}

\ExplSyntaxOff
\makeatother

\begin{document}
\TestRTLAlt

\begin{RTL}
  \TestRTLAlt
\end{RTL}
\end{document}


text:
Q: sum the values at the end of duplicate strings (special format) [UNIX] I'm trying to find a commend or an idea for a script which does the following:
Consider the following example of the content of a file:
a,b,c,d,5
x,y,d,4,9
l,s,y,10
s,9
some,text,does,not,matter,15

the rule is simple: a bunch of strings separated (possible numbers but no commas) with commas in between and a number at the end: str,str,str,...,number
I know how to sort the file using the sort command, but I would like to sum all the lines with the same string until the number. consider the following example:
a,b,c,d,e,5
a,b,c,d,4
a,b,c,d,e,10

output will be:
a,b,c,d,e,15
a,b,c,d,4

order of the lines isn't important.
I think that the first step is to sort the file. then we should somehow split the lines and get the values so we could sum them, but how?

A: Awk solution:
awk 'BEGIN{ FS = OFS = "," }
     { num = $NF; $NF = ""; a[$0] += num }
     END{ for (i in a) print i a[i] }' file

The output:
a,b,c,d,e,15
a,b,c,d,4


text:
Q: How to tell UINavigationBar to ignore a custom category? I'm having a little problem with customising an app's navigation bar and using an image picker.
I have a category that overrides the drawRect method of the app's nav bar, it changes the background image to a mostly white image. This works fine except when I call an image picker to let the user choose a pic from their library.
Firstly the image picker's nav bar displays the custom image but its title text is white which gets lost on the white background. And secondly the status bar is semi transparent which looks weird against the white navbar.
Is there anyway I can tell the image picker's nav bar to ignore the category I created and to use its default drawRect method?
Many thanks for any advice.

A: You cannot make a category apply only sometimes. The way categories work means that you use it always or never. The only workaround I can think of is to somehow check inside of the categories' overridden method to see what instance you're in.


text:
Q: Variadic class function called with shared_ptr I'm updating some of my old (<c++11) c++ projects to use some of the new features introduced and I'm stuck at making my EventHandler class variadic.
The old version looked like this:
template < class T >
class EventHandler : public virtual IEventHandler
{
  public:

    virtual void onEvent( const T& event ) = 0;

    std::type_index getEventType()
    {
        return std::type_index( typeid( T ) );
    }

    void dispatch( const EventSP &spEv )
    {
        const T* pEv( dynamic_cast< const T* >( spEv.get() ) );

        if( pEv != 0 )
        {
            onEvent( *pEv );
        }
    }
};

And used like this:
class EventConsumer : public event::EventHandler< event::EvA >
{

public:

    EventConsumer( event::IEventService* pEventService )
    : m_pEventService( pEventService )
    {
        pEventService->addEventHandler( this );
    }

    ~EventConsumer()
    {
        m_pEventService->removeEventHandler( this );
    }

    void onEvent( const event::EvA& event )
    {
        event.printMe();
    }

private:

    event::IEventService* m_pEventService;
};

And events declared like this:
namespace event {

class EvA : public Event
{
public:
    EvA()
    {
    }

    void printMe() const
    {
        ::std::cout << "Event A" << ::std::endl;
    }
};

class EvB : public Event
{
public:
    EvB()
    {
    }

    void printMe() const
    {
        ::std::cout << "Event B" << ::std::endl;
    }
};

}

And now my plan is to make EventHandler variadic to support more than one event but I can't seem to figure out how to write the dispatch function.
I would like to use it like this:
class EventConsumer : public event::EventHandler< event::EvA, event::EvB >
{

public:

    EventConsumer( event::IEventService* pEventService )
    : m_pEventService( pEventService )
    {
        pEventService->addEventHandler( this );
    }

    ~EventConsumer()
    {
        m_pEventService->removeEventHandler( this );
    }

    void onEvent( const event::EvA& event )
    {
        event.printMe();
    }

    void onEvent( const event::EvB& event )
    {
        event.printMe();
    }

private:

    event::IEventService* m_pEventService;
};

This is what I got so far:
template <typename T>
class t_impl
{
public:
    virtual void onEvent( const T& event ) = 0;
};

template < class... Ts >
class EventHandler : public t_impl<Ts>..., public IEventHandler
{
  public:

    EventHandler()
    {
        m_types = { typeid( Ts ) ... };
    }

    using t_impl<Ts>::onEvent...;

    std::list<std::type_index> getEventTypes()
    {
        return m_types;
    }

private:
    std::list<std::type_index> m_types;

};

I'm guaranteed that the call to dispatch( const EventSP &spEv ) is called with a shared_ptr with a pointer to one of the types that EventHandler is templated with.
It's dispatch responsibility to call the onEvent function.
Any ideas on how to write the dispatch function?
Thanks,
Linus

A: You can use a fold expression:
void dispatch( const std::shared_ptr<Event> &spEv ) {
    (((std::dynamic_pointer_cast< const Ts >( spEv ) != nullptr) && (onEvent( *std::dynamic_pointer_cast< Ts >( spEv ) ), true))
    || ...);
}

Demo
You can do the same with variadic templates and recursion (taking one T at a time from Ts), but it requires much more code. This fold expression might not be the cleanest, but it's concise. It basically creates a series of ifs with the nullptr check for each T in Ts, and for the first one that passes, it executes the rest (what is after the &&).


text:
Q: LPOVERLAPPED_COMPLETION_ROUTINE is incompatible with function I want to asynchronously write data to file using WriteFileEx from winapi, but I have a problem with callback.
I'm getting follow error:
 an argument of type "void (*) (DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)" is incompatible with parameter of type "LPOVERLAPPED_COMPLETION_ROUTINE"
What am I doing wrong?
Here is code:
// Callback
void onWriteComplete(
        DWORD dwErrorCode,
        DWORD dwNumberOfBytesTransfered,
        LPOVERLAPPED lpOverlapped) {
    return;
}

BOOL writeToOutputFile(String ^outFileName, List<String ^> ^fileNames) {
    HANDLE hFile;
    char DataBuffer[] = "This is some test data to write to the file.";
    DWORD dwBytesToWrite = (DWORD) strlen(DataBuffer);
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;

    pin_ptr<const wchar_t> wFileName = PtrToStringChars(outFileName);

    hFile = CreateFile(
        wFileName,              // name of the write
        GENERIC_WRITE,          // open for writing
        0,                      // do not share
        NULL,                   // default security
        CREATE_NEW,             // create new file only
        FILE_FLAG_OVERLAPPED,
        NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) {
        return FALSE;
    }

    OVERLAPPED oOverlap;
    bErrorFlag = WriteFileEx(
        hFile,           // open file handle
        DataBuffer,      // start of data to write
        dwBytesToWrite,  // number of bytes to write
        &oOverlap,      // overlapped structure
        onWriteComplete),

    CloseHandle(hFile);
}

A: You should start by reading the documentation carefully. This part is of particular import:

The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that can go out of scope while the write operation is pending completion.

You are not meeting that requirement, and you need to tackle that issue urgently.
As for the compiler error, that's simple enough. Your callback does not meet the requirements. Again consult the documentation where its signature is given as:
VOID CALLBACK FileIOCompletionRoutine(
  _In_     DWORD dwErrorCode,
  _In_     DWORD dwNumberOfBytesTransfered,
  _Inout_  LPOVERLAPPED lpOverlapped
);

You have omitted CALLBACK which specifies the calling convention.


text:
Q: DAX Rolling Average Applying at Year Level, But Not Month Level I am trying to get a rolling 3/6/12 month average of revenue by month using DAX in a SSAS Tabular model. There is a date table in my model and I have created inactive links between my fact table and my date table for each date in the fact (Date of Service, Invoice Date, etc.). I have created a measure that uses USERELATIONSHIP to activate the specific link I need.
Revenue by DOS:=
    CALCULATE( [Total Gross Revenue],
    USERELATIONSHIP(D_DATE[W_DT_ID],Fact_Charge[W_SERVICE_DT_ID])
)

Here is the code I am using to create the rolling average, which I copied from a SQLBI video on the same subject:
Net Revenue R3M:=
VAR NumOfMonths = 3
VAR LastSelectedDate = MAX(D_DATE[Calendar_Date])
VAR Period =
    DATESINPERIOD( D_DATE[Calendar_Date], LastSelectedDate, -NumOfMonths, MONTH)
VAR Result =
    CALCULATE(
        AVERAGEX(
            VALUES(D_DATE[Month Year]),
            [Revenue by DOS]
        ),
        Period
    )
Return
    Result

For some reason when I deploy the model and try to use it in Power BI, it runs this rolling average at the year level, but not the month. For instance, the Power BI matrix visual will show the year 2021 and will have a value that is equal to the average of the last 3 months of 2021, but the individual months show the same value that is contained in the Revenue by DOS measure itself.
Snip From Power BI
The goal is to have each individual month in the Revenue R3M column to be the 3 month average of the Revenue by DOS column.


text:
Q: Find $\lim_{n\to \infty}((n+1)!)^{\frac{1}{n+1}}-((n)!)^{\frac{1}{n}}.$
Find $\lim_{n\to
 \infty}((n+1)!)^{\frac{1}{n+1}}-((n)!)^{\frac{1}{n}}.$

We need to deal the limit $\lim_{n\to \infty} \frac{\log(1)+\log(2)+...+\log(n)}{n}$. We know that $\lim_{n\to \infty} \log(n)=\infty \implies \lim_{n\to \infty} \frac{\log(1)+\log(2)+...+\log(n)}{n}=\infty$(since, By Cauchy's first theorem on limit). Hence we get $\infty-\infty$. How do I show that there exists finite limit?

A: HINT:
Using Stirling's Formula we have
$$\begin{align}
\left((n+1)!\right)^{1/(n+1)}-\left(n!\right)^{1/n}&=\left(\left(\sqrt{2\pi(n+1)}\left(\frac{n+1}{e}\right)^{n+1}\right)\left(1+O(1/n)\right)\right)^{1/(n+1)}\\\\
&-\left(\left(\sqrt{2\pi n}\left(\frac{n}{e}\right)^{n}\right)\left(1+O(1/n)\right)\right)^{1/n}
\end{align}$$
Can you finish now?

Alternatively, I provided a different, less "brute force" approach in THIS ANSWER.


text:
Q: Weird symbols when inputting a word with length 9 or 10 So I'm creating a program which translate any word into "Malang slang". It's basically just a reversal of the letters in a word except for "ng".
Everything to plan, except when I encounter this problem. When I input a word with length of nine or ten, the program shows additional characters to the screen:
1. Translate to/from Malang slang
2. Exit
Choose your option: 1

Insert your sentence/word here: tenletters
Malang slang: srettelnet╨o

Malang Slang Translator
1. Translate to/from Malang slang
2. Exit
Choose your option: 1

Insert your sentence/word here: nineletter
Malang slang: rettelenin╨o

//How it should be:
Malang Slang Translator
1. Translate to/from Malang slang
2. Exit
Choose your option: 1

Insert your sentence/word here: tenletters nineletter
Malang slang: srettelnet rettelenin

The code that I use is this:
#include <iostream>
#include <string.h>
#include <sstream>
using namespace std;

void ignoreLine()                                                       //ignore line
{
    cin.clear();
    cin.ignore(100, '\n');
}

void clearArray(string word, char* reversed_word)                       //function to clear char array
{
    for(int i = 0; i < sizeof(reversed_word)+1; i++)
        reversed_word[i] = NULL;
}

void swapChar(char* char1, char* char2)                                 //Swaps char
{
    char temp = *char1;
    *char1 = *char2;
    *char2 = temp;
}

void reverseWord(string word, char* reversed_word)                      //function to reverse words [used inside tokenizer]
{
    clearArray(word, reversed_word);

    for(int i = 0, j = word.size() - 1; i < word.size(); i++, j--)
        reversed_word[j] = word[i];

    for(int i = 0; i < word.size() - 1; i++)
    {
        if((reversed_word[i+1] == 'n' || reversed_word[i+1] == 'N') && (reversed_word[i] == 'g' || reversed_word[i] == 'G'))
            swapChar(&reversed_word[i], &reversed_word[i+1]);
    }
}

void tokenizer(string sentence, char* reversed_word)                    //function to tokenize/separate strings per spaces
{                                                                       //using stringstream
    stringstream ss(sentence);
    string word;

    cout << "Malang slang: ";
    while(ss >> word)
    {
        reverseWord(word, reversed_word);
        cout << reversed_word << ' ';
    }
    cout << endl << endl;
}

void translateMalang()
{
    string sentence;
    fflush(stdin);                                                      //Clears buffer

    cout << "\nInsert your sentence/word here: ";
    getline(cin, sentence);
    if(sentence.empty())                                                //If no input, return to main menu
    {
        cout << "No words inputted." << endl;
        return;
    }

    char reversed_word[sentence.size()];                                //declare reversed_word variable as char array

    tokenizer(sentence, reversed_word);                                 //execute tokenizer function
}

void mainMenu(bool* finished)
{
    int option = 0;
    cout << "Malang Slang Translator\n1. Translate to/from Malang slang\n2. Exit\nChoose your option: ";
    cin >> option;

    switch(option)
    {
    case 1:
        translateMalang();
        break;
    case 2:
        *finished = 1;
        break;
    default:
        cout << "Invalid input!" << endl << endl;
        break;
    }
}

int main()
{
    bool finished = 0;

    while(!finished)
    {
        while(cin.fail())
        {
            ignoreLine();
            cout << "Please enter an integer!" << endl;
        }

        mainMenu(&finished);
    }

    return 0;
}

Does anyone know why this happens and what's the solution for this? Thanks!

A: This call of the function fflush with the input stream
fflush(stdin);

has undefined behavior.
In this declaration
char reversed_word[sentence.size()];

there is declared a variable length array. Variable length arrays are not a standard C++ feature. Actually there is no sense to declare the variable length array. You could deal as usually with an object of the type std::string.
For example to reverse the string stored in the object word you could use the standard algorithm std::reverse
std::reverse( std::begin( word ), std::end( word ) );

It is also easy to reverse a string in place using a for loop. For example
for ( std::string::size_type i = 0, n = word.size(); i < n / 2; i++ )
{
    std::swap( word[i], word[n - i - 1] );
}

Moreover the array does not contain a string because it is not ended with the terminating zero character '\0'. So this statement
cout << reversed_word << ' ';

invokes undefined behavior.
Pay attention to that there is already standard function std::swap that allows to swap two objects.


text:
Q: Azure DB & Schema Change Tracking I'm new to Azure and I have been asked to generate a daily report of added/changed databases, table or columns in Azure SQL Server. Specifically, we want to know when new datbases are created, new tables are added or existing ones altered and the same for columns. In non-Azure SQL Server you can use the Schema Changes History in standard reports but this is not available in Azure.
I have seen some suggestions you can do this with Extended Events but I've not found any resources to show how this can be done. Any help would be appreciated.

A: DDL Triggers can really help you to keep track schema changes on your Azure SQL Database. Below is an example:
CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
   PRINT 'Save change on a log'
   SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)');

Database Auditing can help with schema changes and dropped objects. Below an example:
Set-AzureRmSqlDatabaseAuditing `
 -State Enabled `
 -ResourceGroupName "resourcegroupname" `
 -ServerName "ssqlinstancename" `  #ssqlinstancename.database.windows.net
 -StorageAccountName "strageaccountname" `
 -DatabaseName "dbname" `
 -AuditActionGroup 'SCHEMA_OBJECT_CHANGE_GROUP' `
 -RetentionInDays 8 `
 -AuditAction "DELETE ON schema::dbo BY [public]"

If you want to track DML operations also, you can use Temporal Tables but Database Auditing can help also:
Set-AzureRmSqlDatabaseAuditing -ResourceGroupName "resourceGroup"
 -ServerName "SQL Server Name" -DatabaseName "AdventureWorksLT"
 -StorageAccountName "storageAccount"
-AuditActionGroup "SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP", "FAILED_DATABASE_AUTHENTICATION_GROUP", "BATCH_COMPLETED_GROUP"
 -AuditAction "UPDATE ON database::[AdventureWorksLT] BY [public]"
 -RetentionInDays 60


text:
Q: Autorotating video played from HTML5  in UIWebView My app, for some reasons, only supports portrait orientation.
However, in some cases I need to display videos from a UIWebView (with video tag) and it would be nice if the user can view it either in portrait or landscape.
The controller is configured like this:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return UIInterfaceOrientationIsPortrait(toInterfaceOrientation);
}

Result: the video is played only in portrait mode (ok, quite expected).
I tried:
- setting this to support all orientations when the user starts a video
- when the video stops, back to "portrait only"
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    // autorotationEnabled is toggled when a video is played / stopped
    return autorotationEnabled ? YES : UIInterfaceOrientationIsPortrait(toInterfaceOrientation);
}

Result: landscape mode is available (great!) but if the user taps 'Done' while playing in landscape, the previous view will appear in landscape mode once the player is dismissed (not so great).
Does anybody have an idea on how to prevent the controller from being displayed in landscape mode when the player is dismissed?
(using the private method setInterfaceOrientation of UIDevice is not an option)

A: I've have done something very similar. You have to modify the UIView stack to force the app to call shouldAutorotateToInterfaceOrientation when you pop the controller.
In your WebViewController set to allow the autorotate:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}

In the parent controller disallow autorotate:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

Create and assign a UINavigationControllerDelegate.
In the delegate, temporarily modify the UIView stack when the controller pops or pushes:
- (void)navigationController:(UINavigationController *)navigationController
  willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

// Force portrait by changing the view stack to force autorotation!
if ([UIDevice currentDevice].orientation != UIInterfaceOrientationPortrait) {
    if (![viewController isKindOfClass:[MovieWebViewController class]]) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        UIView *view = [window.subviews objectAtIndex:0];
        [view removeFromSuperview];
        [window insertSubview:view atIndex:0];
    }
}

It's kind of a dirty hack, but it works.


text:
Q: "Since first grade" versus "Since the first grade" Is "the" used in the following, and why?

I've been learning Latin since [the / no "the"] first grade.

I think that "I've been learning Latin since first grade" and "I've been learning Latin since the first grade of high school" both sound more natural than their alternatives "I've been learning Latin since the first grade" or "I've been learning Latin since first grade of high school", but I'm not certain why.
I suspect that it depends on whether the main focus of the sentence is the learning of Latin, or whether the main focus is the year of school. Is it kind of like saying "I've been learning Latin since 2011" versus "I've been learning Latin since the year 2011"?
The post With or without 'the' in "in (the) present participle form"? doesn't seem relevant, and this one is about "after" rather than "since".

A: No, it has to do with the "of high school" part. Since you could mean the first grade of elementary school, or the first grade of high school, each of which are a first grade, you use the to emphasize you mean a certain first grade, the first grade of high school.
Also, in American English, "first grade of high school" sounds very strange. We generally number grades from the beginning of elementary school, and keep using higher numbers through middle school and occasionally high school. (High school grades are often called "freshman year" "sophomore year" "junior year" and "senior year" instead of the equally correct but less common ninth, tenth, eleventh and twelfth grades.)


text:
Q: Unit-testing multithreaded applications Has anyone got any advice or know of any frameworks for unit-testing of multithreaded applications?

A: Do not unit test multithreaded applications. Refactor the code to remove coupling between work that is done in different threads. Then test it separately.

A: Typically you don't unit test the concurrency of multi threaded applications as the unit tests aren't dependable and reproducible - because of the nature of concurrency bugs its not generally possible to write unit tests that consistently either fail or succeed, and so unit tests of concurrent code generally don't make very useful unit tests.
Instead you unit test each single threaded components of your application as normal and rely on load testing sessions to identify concurrency issues.
That said, there are some experimental load testing frameworks for testing concurrent applications, such as Microsoft CHESS - CHESS repeatedly runs a given unit test and systematically explores every possible interleaving of a concurrent test.  This makes your unit tests dependable and reproducible.
For the moment however CHESS is still experimental (and probably not usable with the JVM) - for now stick with load testing to weed out concurrency issues.

A: Try multithreadedTC
http://code.google.com/p/multithreadedtc/
http://code.google.com/p/multithreadedtc-junit4/


text:
Q: Trim unprintable characters using python I have text content which is coming from different languages like chines, Hebrew and so on. By using google translator API converting the text into 'en'. Here problem is google translator is failing when its identifies some special characters like \x11,\x01(unable to display those characters over here) and dropping that set of records. Please suggest some safest way to do this conversion with out dropping records.

A: data = ''.join(c for c in data if c.printable)


text:
Q: Como hacer una $scope de ubicacion con geodjango, django y angularjs Como hacer un $scope.cities por que no me sale en PHPStorm me da error de "Expression statement is not assignment or call" y no se cual es el error

/**
 * Created by gamba on 20/10/2016.
 */
var app = angular.module("mapas",[]);

app.controller("myctrl",function ($scope,$http) {
    //CONEXION
    $scope.coordenadas=[];
    $scope.cities=[];
    var url = "http://192.168.137.11:8000/conductores/";
    $http({
        method: 'GET',
        url: url
    }).then (function successCallback(data) {
        $scope.coordenadas=data;
        $scope.cities = [
            {'Bus 1',$scope.coordenadas[1].ubicacion.geometry.x,$scope.coordenadas[1].ubicacion.geometry.y},
            {'Bus 2',$scope.coordenadas[2].ubicacion.geometry.x,$scope.coordenadas[2].ubicacion.geometry.y},
            {'Bus 3',$scope.coordenadas[3].ubicacion.geometry.x,$scope.coordenadas[3].ubicacion.geometry.y}
        ];
    },function errorCallback(err) {
        console.log("No funciona la conexion");
    });
    //GOOGLE MAPS API CODE
    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(40.0000, -98.0000),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);

    $scope.markers = [];

    var infoWindow = new google.maps.InfoWindow();

    var createMarker = function (info){

        var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            title: info.city
        });
        marker.content = '
' + info.desc + '
';

        google.maps.event.addListener(marker, 'click', function(){
            infoWindow.setContent('
' + marker.title + '
' + marker.content);
            infoWindow.open($scope.map, marker);
        });

        $scope.markers.push(marker);

    };

    for (i = 0; i < $scope.cities.length; i++){
        createMarker($scope.cities[i]);
    }

    $scope.openInfoWindow = function(e, selectedMarker) {
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }
});

A: Tienes un error en la forma en que estas escribiendo el arreglo en la linea 16 tienes:
$scope.cities = [
        {'Bus 1',$scope.coordenadas[1].ubicacion.geometry.x,$scope.coordenadas[1].ubicacion.geometry.y},
        {'Bus 2',$scope.coordenadas[2].ubicacion.geometry.x,$scope.coordenadas[2].ubicacion.geometry.y},
        {'Bus 3',$scope.coordenadas[3].ubicacion.geometry.x,$scope.coordenadas[3].ubicacion.geometry.y}
    ];

cuando debería ser:
$scope.cities = [
    ['Bus1',$scope.coordenadas[1].ubicacion.geometry.x,$scope.coordenadas[1 ].ubicacion.geometry.y],
    ['Bus2',$scope.coordenadas[2].ubicacion.geometry.x,$scope.coordenadas[2].ubicacion.geometry.y],
    ['Bus3',scope.coordenadas[3].ubicacion.geometry.x,$scope.coordenadas[3].ubicacion.geometry.y]
];

En otras palabras confundiste "{" por "]".


text:
Q: DateTime.now not setting timezone in Rails I have a column called "Archived" in my message table and a button that when pushed will write the current time and date into the db column. Right now I can get it to write the time, however it's in the wrong timezone. After looking online I created the following code which is currently saving, but not in the correct timezone:
Controller Code
def archive_message
  @message = Message.find(params[:id])
  @message.archived = DateTime.now.in_time_zone "Central Time (US & Canada)"
  @message.save

  redirect_to '/messages'
end

My route (I believe this is ok as is)
post 'messages/:id/archive_message' => 'Messages#archive_message', :as => 'archive_message'

Any suggestions are well appreciated.

A: EDIT AGAIN: OK this is UTC time, so it's working. Thank you everyone.
EDIT: I just closed an restarted everything and now it is NOT WORKING, it is saving the time as 5 hours ahead again and I have no idea why.
In config/application.rb
added the following to module code

config.time_zone = 'Central Time (US & Canada)'
config.active_record.default_timezone = :local

and my controller

@message.archived = DateTime.current

thanks everyone


text:
Q: Android camera intent should not allow to save the image to gallery and store it in specified path when i use this code ->
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

I am able to save the image to specified path but it is also saving to the gallery. I dont want to save the image to gallery. Please help here.
Thanks in advance for your valuable time.

A: Capture Image using below Intent -
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

// create a file to save the image
File MyDir = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir");
if (!MyDir.exists()){
    MyDir.mkdirs()
}

File fileUri = new File(MyDir.getAbsolutePath() + File.separator + "IMG_"+ timeStamp + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

The gallery app scans the folders for Media contents and populates them in gallery.
If you wish not to display your captured images in gallery follow below methods-

*

*Creating A .Nomedia File

*Adding A Dot Prefix

A: try this
private void captureCameraImage() {

        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFilename());

        startActivityForResult(chooserIntent, CAMERA_PHOTO);

    }

method to return file name that you can specify whre you want to save
public String getFilename() {
    File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
    return uriSting;

}

A: I faced the same problem and implemented several workarounds similar to this one.
I tried also to keep the file hidden adding the . prefix to the filname and to put a .nomedia file (see MediaStore.MEDIA_IGNORE_FILENAME) within the folder where I stored the images but in some cases, calling the camera app via intent as usual
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
    Uri fileUri = FileProvider.getUriForFile(getContext(), getString(R.string.file_provider_authority), file);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(intent, CAMERA_REQUEST_CODE);
} else {
    showToastMessage(getString(R.string.no_camera_activity), Toast.LENGTH_LONG);
}

depending on the device and the camera app, this latter might store the picture also within the gallery (usually saving a file with a timestamp as the filename) even if you are providing an Uri associated to a file you are storing within your application private partition.
So I found that the most reliable way of doing what I needed was to control the camera directly by your own or to adopt cwac-cam2 library provided by CommonsWare within YourActivity in this way (note the commented .updateMediaStore() line)
Uri fileUri = FileProvider.getUriForFile(getContext(), getString(R.string.file_provider_authority), file);
CameraActivity.IntentBuilder builder = new CameraActivity.IntentBuilder(this); // this refers to the activity instance
    Intent intent = builder
            .skipConfirm()
            .facing(Facing.BACK)
            .to(fileUri)
            //.updateMediaStore() // uncomment only if you want to update MediaStore
            .flashMode(FlashMode.AUTO)
            .build();
    startActivityForResult(intent, CAMERA_REQUEST_CODE);


text:
Q: Firebase Worker Crash on failWithError I have spent time debugging my code in hopes of a solution, but this crash only happens when I'm not connected to the debugger.
I have set up a Firebase Singleton that manages four firebases with different paths.  Each firebase is setup using a snippet of code like this:
-(void)connectFirebaseForMatch:(NSNumber*)matchId{

if(status == FireBaseStatusConnected){

    if(matchFirebase){
        [matchFirebase removeAllObservers];
        matchFirebase = nil;
    }

    NSString *baseURL = [NSString stringWithFormat:@"%@matches/%@",kFirechatNS,matchId];
    matchFirebase = [[Firebase alloc] initWithUrl:baseURL];
    if(!matchFirebase){
        return;
    }

    __weak FirebaseClient *bSelf = self;

    void(^messages_block_with_connection)(FDataSnapshot*) = ^(FDataSnapshot* snapshot){

        if(snapshot){
            [[LACoreDataStore sharedStore] updateMessageWithSnapshot:snapshot forMatchId:matchId dateFormatter:writingDateFormatter withCompletion:^(BOOL newMessages, NSNumber *matchIdFromBlock, NSError *error) {

                //Tell Message View to Refresh TableView using Notification Center

                [[NSObject class] cancelPreviousPerformRequestsWithTarget:bSelf selector:@selector(reloadMessagesForMatch:) object:matchIdFromBlock];
                [bSelf performSelector:@selector(reloadMessagesForMatch:) withObject:matchIdFromBlock afterDelay:.1];

            }];
        }

    };

    void(^no_messages_block_with_connection)(FDataSnapshot*) = ^(FDataSnapshot* snapshot){

        //Tell Message View to Refresh TableView using Notification Center

        [bSelf performSelector:@selector(reloadMessagesForMatch:) withObject:matchId afterDelay:.05];

    };

    [matchFirebase observeEventType:FEventTypeChildAdded withBlock:messages_block_with_connection];

    [matchFirebase observeSingleEventOfType:FEventTypeValue withBlock:no_messages_block_with_connection];

    NSLog(@"Registered Messaging View with Firebase: %@",baseURL);

    }
}

Each firebase simply reads the new data from firebase into Core Data and uses the notification center to refresh whichever views are necessary.
All seems to work fine while using the app, but after a day or so I get this crash on the Firebase Worker and I am unable to find the source:
FSRWebSocket.m line 716
__31-[FSRWebSocket _failWithError:]_block_invoke_2

From Crashlytics:
Crashed: FirebaseWorker
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0xb0000010

Thank you in advance for your help :)

A: Sorry you ran into this.  It's a bug in the Firebase SDK.  It should be fixed in the very latest version, which you can grab here: https://cdn.firebase.com/ObjC/Firebase.framework-LATEST.zip
If you still have issues, shoot us an email at support@firebase.com.  Thanks!


text:
Q: Connecting two devices to one phone So I have been trying to connect my microphone to my iPhone 5s while connecting another device(a speaker) simultaneously. Is this possible in anyway? Also can I speak on the mic and hear from the speaker when I'm on a phone call. I know we have car headsets and car hands free speakers with built-in mic these days but I was just wondering if it's possible to use two different devices sinultaneously for a phone call.

A: Yes you can do this by buying a bluetooth speaker and a pluggable microphone. I would recommend using the Ultra Slim Bluetooth Speaker as the bluetooth speaker (it is available for $50, pretty affordable) and the Zoom iQ7 as your microphone ($99.99). In Zoom iQ7, there is a headphone plug so you might not even need the speaker if you have the Zoom iQ7.


text:
Q: Choose file with the most current Date Modified from directory I'm using a basic Directory.GetFiles to find the files i want to use.  But i only want to select only the most current file based on date modified.  Is there a  simple way to do that?
 string[] directoryFiles = Directory.GetFiles(@"\\networkShare\files", "*.bak");

A: new DirectoryInfo(path)
    .EnumerateFiles("*.bak")
    .OrderByDescending(f => f.LastWriteTime)
    .Last()

A: Rather than use a simple string list you want to use DirectoryInfo and FileInfo. These are classes that have the folder/file properties (date/time modified, accessed etc.) on them.
You can then sort the lists that these produce as in SLaks example
new DirectoryInfo(path)
    .EnumerateFiles("*.bak")
    .OrderByDescending(f => f.LastWriteTime)
    .Last()


text:
Q: retaining dropdown selection on page reload in html I have a dropdown list on a page like this:

 Add Dosen

 Data Dosen

Picture 1
When a user makes a selection, the current page is refreshed like this Picture 2, but how do I keep the user's selection visible in the list after the page refresh? In other words, I don't want the list to rollback to its default selected value.
Please Help Me.

A: try this example
first choose car from the list, and then click "choose" button
after that reload the page or close it and open it again, the car you have choosed in first part has a orang background
<!DOCTYPE html>

  <select name="cars" id="cars">
    <option id="volvo" value="volvo">Volvo</option>
    <option id="saab" value="saab">Saab</option>
    <option id="fiat" value="fiat">Fiat</option>
    <option id="audi" value="audi">Audi</option>
  </select>
  <button onclick="getname()">choose</button>

A: You can do this by getting the URL path and selecting the appropriate a tag which has that path in its href and settings its parent li class to active.
Sample code is given below.
   $(function(){
         $('ul.nav').find('li').removeClass('active'); // to remove hardcoded active class
         var activeAnchor = $('ul.nav').find('a[href="' + location.pathname + location.search + '"]');
         $(activeAnchor ).parent('li').addClass('active');

         //below script is if at all you have sub menus too
         if ($(activeAnchor).closest(".submenu").length > 0) {
           $(activeAnchor).closest('ul').parent('li').addClass('active').addClass('open').closest('ul').parent('li').addClass('open');
           $(activeAnchor).parent('li').addClass('active');
           $(activeAnchor).closest('ul').removeAttr('style').removeClass('nav-hide');
          }
   });


text:
Q: date function in PHP - applies timezone? I came across something I found a bit confusing when using the date() function.
// Set up unix timestamp 03:34
$t = (3 * 60 * 60) + (34 * 60); // 12840 seconds
echo date('Y-m-d H:i',$t);
// displays Thu, 01 Jan 1970 13:34:00 not
//          Thu, 01 Jan 1970 03:34:00

I was expecting date to return 03:34, but it looks like it might have applied my timezone to it (+1000). My questions are a) does date() apply the current timezone before formatting its output and b) is it possible in PHP to format a date without the application of the timezone? I need the 03:34 to stay that way, but I want to keep the simplicity of using unix-timestamps for my time maths, so would prefer not to use PHPs Date class. Not a huge problem, just something more for interests sake.
Thanks guys
Pete


text:
Q: Postfix setup for LAN only I have Ubuntu on which I installed Postfix.
Postfix packet is up and running.
I'm trying to make a simple e-mail system to work between a few LAN computers.
Basically, I need to have some outlook clients able to exchange e-mails between them. I don't mind using the server IP address in outlook.
What is the easiest way to setup a LAN-only e-mail system using postfix ?
I did read some tutorials but they are very confusing for me because I don't have experience with linux or e-mails.
Other probably important notes:
So far in the main.cf I have added as mydomain internal.tmp and the local IPs to the networks (although they are also public, which is technically absurd and kind of wrong, but this is the current configuration of my friends network).
So practically, next I want to add some users like user1@internal.tmp, user2@internal.tmp that I want to configure in outlook clients so they can mail between them. How can I do this ?
Thanks in advance for any helpful info.

A: This question is likely to be too broad for ServerFault, but I'll have a go at pointing you in the right direction.
Postfix is an MTA (Mail Transfer Agent) and as such will only transport email between systems - for example, receiving email from either clients and forwarding to destination servers, or receiving email intended for other servers and forwarding it on - the latter is called relaying.
What you need is a mail server such as Dovecot, which will store your mail and make it available to your clients over IMAP (or POP if you want to be really archaic).
As you've hinted, you will need to configure Dovecot (or your chosen mailserver) to authenticate users. Dovecot itself can integrate with a wide range of user authentication databases (for example: local (i.e. system) users, virtual users defined in files, MySQL, LDAP).
Postfix can be configured to use SASL and authenticate users using Dovecot - even if your server isn't publicly available I would still do this out of habit and best practice.


text:
Q: Как извлечь данные из HTML строки HtmlAgilityPack Получаю строку такого типа

Тип обложки: обл - мягкий переплет (крепление скрепкой или клеем)

Иллюстрации: Черно-белые + цветные

Мне нужно получить вот это Черно-белые + цветные.
причем вот это
Иллюстрации: Черно-белые + цветные
, может и отсутствовать или порядок, может быть другой. Единственный ориентир это слово Иллюстрации:.
Пробовал сделать вот так
 string illustration = `htmlDocument.DocumentNode.SelectNodes("//div[@class='popup']").Where(x=>x.InnerText.Contains("Иллюстрации:")).Select(s=>s.InnerText).FirstOrDefault();`

Все ок, но он выбирает весь текст
"Тип обложки: 7Бц - твердая, целлофанированная (или лакированная)Иллюстрации: Цветные"

,а мне нужен только Цветные, или пусть просто возьмет содержимое div? вот так
Иллюстрации: Черно-белые + цветные, дальше закрепленность слово не проблема.

A: Дело в том, что у вас находится первый узел div с классом popup и извлекается его содержимое. А оно берётся со всеми вложенными подузлами.
Исправьте ваше xpath-выражение следующим образом:
"//div[@class='popup']/*/div"

и будет извлекаться то, что нужно.
Так как у вас берутся данные только из одного узла - первого, то можно вместо SelectNodes использовать метод SelectSingleNode. А также предлагаю использовать мощь xpath:
string illustration = htmlDocument.DocumentNode
    .SelectSingleNode("//div[@class='popup']/*/div[contains(.,'Иллюстрации:')]")
    .InnerText;

A: Решил проблему следующим образом
  var illustration = htmlDocument.DocumentNode.SelectSingleNode("//*[contains(text(), 'Иллюстрации:')]").InnerText;

То есть выборка идет по тексту


text:
Q: Save DataFrame to next row in existing excel sheet Ideally I'm building a self-updating mechanism. The last thing I need to do is save content from "dff" to the next empty row in an existing excel sheet "test.xlsx".

book = load_workbook("test.xlsx")
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
dff.to_excel(writer, startrow=len(dff), header=None)
writer.save()

The issue is around the 2nd last row, the "startrow=" part.
So far I can make it enter the dataframe content to row 3, but it overwrites the contents.
Say I have content
08/09-2019 00, 00, 00, 00
How would I add it to the next empty row of my excel sheet?

A: Try this
dff.to_excel(writer, startrow=len(dff)+1, header=False, index=False)


text:
Q: how could I manage a bibliography in a world full of clouds (citeulike / mendeley)? I always used a single babel.bib BibTex file to keep a record of all my readings. Great. Then I managed it using a VCS (first SVN, then git). Super great. But at the same time, resources like CiteUlike or Mendeley (but also other services like orcid) allow for cloud-like services of having this data everywhere, anytime. Super super great!
But this fails if you have no connection to internet (remote conference, ...) or more importantly if these services change their policy (mendeley to citeulike sync disappeared at a sudden). The work you provide is not yours. These are mostly commercial services while all the open-source tools are there. Most importantly, the multiplicity of tools makes it difficult to share bibliographic data easily, while if we would have a tool to translate between them this would make it possible (without changing your habits).
As a consequence, I wish to build such a "BibCloud" service with the following features:

*

*bibcloud init : use with biblatex (but a format using bibjson is possible)

*CLI coded in python (widespread in the scientific community), all databases + configuration files being stored in plain text files.

*bibcloud commit -am' adding Sawyer14nature'; bibcloud push : CVS integration (git / hg / ...) - and storage in remote repositories (github, bitbucket)

*bibcloud pull citeulike, bibcloud push citeulike : easy conversion + pull and push to existing accounts (Citeulike, Mendeley) - including synchronization of PDFs

*bibcloud detect_dups records implementation of tools to detect and merge duplicate records, and duplicate fields (like bibcloud detect_dups authors:  an author with different versions, like eg Tom Sawyer, T Sawyer, T J Sawyer or for journal names with bibcloud detect_dups journals)

*bibcloud pull 2323422.pdf scan a pdf to extract its metadata (like the DOI) - allow to include the citation in the paper bibcloud push 2323422.pdf to simply send a file to colleagues.

*bibcloud citekey Sawyer14 : generate a citekey according to a given rule

*bibcloud edit Sawyer14 : edits one particular entry

*bibcloud file Sawyer14 : files the PDF corresponding to the entry according to some rule

*bibcloud push html easy conversion to some web format (github pages?) to read papers online.

Before attempting to put that together, I wish to know of the existing pieces the community may know.
Notes:

*

*it is different from this question "Workflow for managing references?" as existing solutions like zotero or  do not work for me. I wish to get the pieces of the puzzle together to build a command-line tool for managing bibliographies.

*it is different to this question or to this other as they ask more for a GUI solution.

A: I think that you could use cloud reference manager's APIs, such as Mendeley APIs (http://apidocs.mendeley.com). I'd simply "wrap" corresponding RESTful APIs into a command-line interface (of course, APIs should provide needed granularity of functionality).
In regard to your concerns about loss of Internet connectivity and ownership of your data, these issues can be solved, correspondingly, by 1) enabling offline mode via cloud service's synchronization APIs (where available) and 2) mirroring service's proprietary local database to local open source database via export APIs (where available).