text:
Q: Spring project using CAS for Authentication and LDAP for Authorities I had a Spring 3 project that was using LDAP for Authentication and Authorities. We know changed the project to use CAS for authentication but still work like to use LDAP for Authorities.  can someone please look at this XML file and tell me how to get LDAP Authorities back and working
  <?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns:b="http://www.springframework.org/schema/beans"
    xmlns="http://www.springframework.org/schema/security" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <http entry-point-ref="casEntryPoint" use-expressions="true">
        <intercept-url pattern="/" access="permitAll" />

        <intercept-url pattern="/index.jsp" access="permitAll" />
        <intercept-url pattern="/cas-logout.jsp" access="permitAll" />
        <intercept-url pattern="/casfailed.jsp" access="permitAll" />

        <intercept-url pattern="/secure/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/requests/**" access="hasRole('ROLE_MEMBER_INQUIRY')" />

        <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" />
        <custom-filter ref="singleLogoutFilter" before="CAS_FILTER" />
        <custom-filter ref="casFilter" position="CAS_FILTER" />

        <logout logout-success-url="/cas-logout.jsp" />
    </http>

    <authentication-manager alias="authManager">
        <authentication-provider ref="casAuthProvider" />
    </authentication-manager>

     <user-service id="userService">
        <user name="rod" password="rod" authorities="ROLE_SUPERVISOR,ROLE_USER" />
        <user name="cpilling04@aol.com.dev" password="testing"
            authorities="ROLE_MEMBER_INQUIRY" />
    </user-service>

    <!-- This filter handles a Single Logout Request from the CAS Server -->
    <b:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" />
    <!-- This filter redirects to the CAS Server to signal Single Logout should
        be performed -->
    <b:bean id="requestSingleLogoutFilter"
        class="org.springframework.security.web.authentication.logout.LogoutFilter"
        p:filterProcessesUrl="/j_spring_cas_security_logout">
        <b:constructor-arg
            value="https://${cas.server.host}/cas-server-webapp/logout" />
        <b:constructor-arg>
            <b:bean
                class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
        </b:constructor-arg>
    </b:bean>

    <b:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties"
        p:service="https://${cas.service.host}/MemberInquiry/j_spring_cas_security_check"
        p:authenticateAllArtifacts="true" />

    <b:bean id="casEntryPoint"
        class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"
        p:serviceProperties-ref="serviceProperties"
        p:loginUrl="https://${cas.server.host}/cas-server-webapp/login" />

    <b:bean id="casFilter"
        class="org.springframework.security.cas.web.CasAuthenticationFilter"
        p:authenticationManager-ref="authManager" p:serviceProperties-ref="serviceProperties"
        p:proxyGrantingTicketStorage-ref="pgtStorage"
        p:proxyReceptorUrl="/j_spring_cas_security_proxyreceptor">
        <b:property name="authenticationDetailsSource">
            <b:bean
                class="org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource" />
        </b:property>

        <b:property name="authenticationFailureHandler">
            <b:bean
                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
                p:defaultFailureUrl="/casfailed.jsp" />
        </b:property>

        <b:property name="authenticationSuccessHandler">
            <b:bean
                class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
                p:defaultTargetUrl="/requests/add.html" />
        </b:property>
    </b:bean>
    <!-- NOTE: In a real application you should not use an in memory implementation.
        You will also want to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup() -->
    <b:bean id="pgtStorage"
        class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl" />
    <b:bean id="casAuthProvider"
        class="org.springframework.security.cas.authentication.CasAuthenticationProvider"
        p:serviceProperties-ref="serviceProperties" p:key="casAuthProviderKey">
        <b:property name="authenticationUserDetailsService">
            <b:bean
                class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
                <b:constructor-arg ref="userService" />
            </b:bean>
        </b:property>
        <b:property name="ticketValidator">
            <b:bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator"
                p:acceptAnyProxy="true"
                p:proxyCallbackUrl="https://${cas.service.host}/MemberInquiry/j_spring_cas_security_proxyreceptor"
                p:proxyGrantingTicketStorage-ref="pgtStorage">
                <b:constructor-arg value="https://${cas.server.host}/cas-server-webapp" />
            </b:bean>
        </b:property>
        <b:property name="statelessTicketCache">
            <b:bean
                class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
                <b:property name="cache">
                    <b:bean class="net.sf.ehcache.Cache" init-method="initialise"
                        destroy-method="dispose">
                        <b:constructor-arg value="casTickets" />
                        <b:constructor-arg value="50" />
                        <b:constructor-arg value="true" />
                        <b:constructor-arg value="false" />
                        <b:constructor-arg value="3600" />
                        <b:constructor-arg value="900" />
                    </b:bean>
                </b:property>
            </b:bean>
        </b:property>
    </b:bean>

    <!-- Configuration for the environment can be overriden by system properties -->
    <context:property-placeholder
        system-properties-mode="OVERRIDE" properties-ref="environment" />

    <util:properties id="environment">
        <b:prop key="cas.service.host">wcmisdlin07.uftmasterad.org:8443</b:prop>
        <b:prop key="cas.server.host">wcmisdlin07.uftmasterad.org:8443</b:prop>
    </util:properties>

    <b:bean id="contextSource"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">

        <b:constructor-arg
            value="ldaps://dvldap01.uftwf.dev:636/dc=uftwf,dc=dev" />

        <b:property name="userDn" value="cn=Manager,dc=uftwf,dc=dev" />

        <b:property name="password" value="uftwf" />
    </b:bean>

        <b:bean id="ldapAuthProvider"
        class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">

        <b:constructor-arg>

            <b:bean
                class="org.springframework.security.ldap.authentication.BindAuthenticator">
                <b:constructor-arg ref="contextSource" />
                <b:property name="userDnPatterns">
                    <b:list>
                        <b:value>
                            uid={0},ou=webusers
                        </b:value>
                    </b:list>
                </b:property>
            </b:bean>
        </b:constructor-arg>
        <b:constructor-arg>
            <b:bean
                class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
                <b:constructor-arg ref="contextSource" />
                <b:constructor-arg value="ou=groups" />
                <b:property name="groupRoleAttribute" value="ou" />
            </b:bean>
        </b:constructor-arg>
    </b:bean>
    <ldap-server url="ldaps://dvldap01.uftwf.dev:636/dc=uftwf,dc=dev" />

</b:beans>

A: You need to replace the in-memory UserDetailsService bean (userService) with an LdapUserDetailsService. If you were previously using LDAP for authentication, then the configuration should be pretty much the same, assuming the user name returned by CAS can be easily mapped into the directory.
In more detail: You currently have a bean called userService which is created using the namespace:
<user-service id="userService">
    <user name="rod" password="rod" authorities="ROLE_SUPERVISOR,ROLE_USER" />
    <user name="cpilling04@aol.com.dev" password="testing"
        authorities="ROLE_MEMBER_INQUIRY" />
</user-service>

you need to replace it by one that looks something like this:
<ldap-user-service id="userService"
    server-ref="yourLdapServer"
    user-search-base="ou=people"
    user-search-filter="(uid={0})"
    group-search-base="ou=groups"
    group-role-attribute="cn"
    group-search-filter="(member={0})"
    role-prefix="ROLE_" />

but with the various attributes set to match your directory configuration. They should be similar to whatever you had in your <ldap-authentication-provider> configuration before you moved to CAS. You'll also need to declare an <ldap-server> element to point to the directory server. Again that should match what you had before.


text:
Q: Can I get a percent of number without using decimals? I am programming in a language that does not support decimal numbers. The language only supports positive or negative whole numbers. Is there a way to calculate the percent of a number only using whole numbers?
The language automatically rounds the number down in the case of a remainder. I.e. 97 / 33 = 2
I have two values:
The percent and the number I am trying to get the percent of.
For example, lets say I have the number 126,345 and I want to get 13 % of that number.
The result of that normally would be 16,424.85. If this is possible the language would cut off the .85 remainder which is fine.
Thanks for your time and help!

A: Somewhat related to the subject, here is an example of a floating-point division result using integer functions:
125 / 13 = 9  <-
125 Mod 13 = 8
80 / 13 = 6  <-
80 Mod 13 = 2
20 / 13 = 1  <-
20 Mod 13 = 7
70 / 13 = 5  <-
for 9.615 as 9.62 .
Or the actual problem: 126345 * 13 = 1642485; 1642485 / 100 = 16424; 1642485 Mod 100 = 85; 850 / 100 = 8; 850 Mod 100 = 50; 500 / 100 = 5; 500 Mod 100 = 0; 0 / 100 = 0;
for 16424.850 as 16424.85 .

A: As said by @magdiragdag in the comments, multiply by $13$ and then divide by $100$.
If your division rounds down (so that $160/100=1$) and you want to round to the nearest whole number instead, multiply by $13$, then add $50$, and then divide by $100$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check a block if is realize? In my code, if I use the block directly:
- (IBAction)checkPendingAction:(UIButton *)sender {
    self.block(sender.titleLabel.text);  // if the block is no realize, there will report EXC_BAD_ACCESS(code=x, address=0x11xx)
}

If I use delegate, I can use the below code to check my delegate and delegate method if is realize:
if ([self.delegate respondsToSelector:@selector(myDelegateMethod:)]) {
    [self.delegate tabBarClickWriteButton:self];
}

So, can I check the block if is realize in iOS?

A: make your block a property with 'strong' reference. and use weak reference of self in it if needed.
before calling block just check
if(block) {
block(data);
}

A: You need check block as below
if (self.yourblock != nil) {
    self.yourblock(self.titleLabel.text);
 }


text:
Q: PHP Login form doesn't redirect to another page validation process works well but it won't redirect to the new "profile.php " page. Pls let me know where I am going wrong.
Here is the html form.
<form name = "fomu_kuingia" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">

 Barua pepe: <input type="text" name="baruapepe"  />
           <?php echo $tatizo;  ?>

 Neno la siri:  <input type="password" name="nenosiri" />
          <?php echo $tatizo1;  ?>

<input type="button" value="Nimesahau" name="nimesahau" /><input type="submit" value="Ingia " name="ingia "  />
           <?php //echo $jinaErr; ?>

        </form>

here is the php function to take data (email/ passed)
 <?php
           //$pepe = " ";
          // $siri = " ";

           function take_data()
        {    $pepe = "";
             $siri = "";

           if ($_SERVER["REQUEST_METHOD"] == "POST")
           {
               if (empty ($_POST["baruapepe"])||empty ($_POST["nenosiri"]))
                {  echo " TATIZO: Tafadhali ingiza barua pepe au neno siri " ;  }

                else {  $pepe = verify($_POST["baruapepe"]);
                        $siri = verify($_POST["nenosiri"]);

                        kuingia ($pepe, $siri); }
           }
         }

           ?>

here if the function to verify data ;php function;
 <?php
           //$pepe = " ";
          // $siri = " ";

           function verify ($data)
           {
               $data = trim ($data);
               $data = stripslashes($data);
               $data = htmlspecialchars($data);
               return $data;
           }

           ?>

and fınally ıs the functıon to check logın (email,paswd) detaıls and redırect to new page .
<?php
           //$pepe = " ";
          // $siri = " ";

           function kuingia ($pp, $sr)
           {
               $con = mysql_connect('localhost', 'root', 'root');

               if (!$con)
               { echo "Connection was not possible ";}

               else
               {
                   mysql_select_db('DalaliOnline', mysql_connect('localhost', 'root', 'root'));
                   $result = mysql_query("select jina1, jina2 from watumiaji where barua_pepe = '$pp' and neno_siri = '$sr' ");

                   if (!$result)
                   {    echo "Tatizo la mysql"; }

                   else if  (mysql_num_rows($result)== 0)
                   {    echo " TATIZO: Barua pepe au neno siri vimekosewa " ;   }

                   else
                   { header ("Location:profile.php");
                       echo "umefanikiwa kuingia"; }
               }
           }

           ?>

A: Your header() call is sending a relative path for the Location header.
According to the PHP documentation for header(), the HTTP/1.1 spec requires an absolute URL:

HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself

It looks like you are also missing a space between the colon (:) and the content of the header.
Another common gotcha (although I'm not seeing it in your code above) is that you can't call header() if you've already sent any output to the browser.

A: The header location should be an absolute url, and there should be a space between Location: and the url, ie;
header ("Location: http://yoursite.com/profile.php");

Also make sure there is nothing outputted to the browser before that header is sent.
Hope this helps.


text:
Q: In SSRS, a Date Time parameter on Preview is not matching the deployed report In SSRS, a Date Time parameter on Preview is not matching the deployed report. Is this something someone else has encountered?  The RDL code is identical.  Is it the fact that, sometimes, a local preview is just a simulation of functionality? Is it because the display in preview sometimes uses cached data?
I have a SSRS report that, when I preview it in Visual Studio locally, the date shows as 2/10/2019 but when the RDL code is deployed on the server, the date shows as 2/7/2019.
The date time variable is based on a parameter on the report, called rundate, and it has a Default Value of 2/10/2019.
So I think the same thing should happen on the Report Server that happens locally in preview mode.
The report has four datasets and, as a test,  I have set each four to have the SQL line that sets the rundate value like so:
SET @rundate = '2019-02-10'
but on the report server, when I load the report, it throws this error:
Must declare the scalar variable "@rundate". Must declare the scalar variable "@rundate".
It is in a cascading tabbed error message that looks like this:
An error occurred during client rendering.
An error has occurred during report processing.
Query execution failed for dataset 'ThirdDataset.
Must declare the scalar variable "@rundate". Must declare the scalar variable "@rundate".
So, why does it run locally and not on the server?  The "ThirdDataset" is a false name I have given here.  The actual name is redacted.  But, I have noticed that this would be the first dataset run if they are run alphabetically.  So this leads me to the question: why doesn't the report recognize this as a parameter and why does it complain that it is not declared?
============
UPDATE:
I have set the rundate to be part of a data-driven subscription in a report like so:
SELECT convert (date, DATEADD (DAY, -2 , SYSDATETIME())) as rundate

Which is two days ago.  Since it is 2/11/2019 today, the rundate parameter passed to the SSRS report on the server should be 2/9/2019.
For fun, to test this out, I set the Default Value rundate parameter to be 8/8/2018 in hopes that the data-driven report would set it properly.

In preview mode locally on Visual Studio, a textbox that set to show the [@rundate] Expression shows 8/8/2018 which is what I would expect, but the Datasets are designed to run off this parameter.  Since there is nothing that the sql should retrieve from the database that is that old, the graphs and charts in preview mode should turn up completely empty.  Why do they show data?!
Next, let's see what the emailed subscription alert says.  It had the date of 2/11/2019 12:00:00 AM.  If the data-driven subscription ran like it shouold ahve run, it should of had the date of 2/9/2019 from
SELECT convert (date, DATEADD (DAY, -2 , SYSDATETIME())) as rundate
Why did this not work?
On the SSRS server, the RDL file has a parameter default value of 2/11/2019 12:00:00 AM but why did the report get THIS default value?  What am I doing wrong and how can I fix this?

As a test, I set this default date/time parameter to 12:12:34 for its time to see what would happen.  It reveiled that, yes, this is the date time stamp that is being sent to the report.  So I unchecked the "Has Default" box

Then, I noticed in the Step 5 of the data-driven subscription I could not advance to Next > without making a small change:

So, what should happen?  Will it show the wacky 8/8/2018 value?  Will it show the date from two days ago?

A: Default values for report parameters are deployed only once to the report server, and then they keep their default value after subsequent deployments. This is so that default parameter values used in development don't overwrite the desired parameter defaults on the production server.
So it looks like when the report was first deployed, @rundate had the default value 2/7/2019 but has since been changed on the local report to 2/10/2019. Go into your report server, find the report and go into the Report Parameters section to edit the parameters and change the default value to what you want it to be (deleting the report from the report server and re-deploying it with the updated parameter will have the same effect, but note that the parameter will maintain that default value going forwards). Alternatively, set the report parameter using an expression so that it is continually up to date.
Regarding updating your parameter value in the Sql statement using the SET statement, you can't actually do it that way - you need to set it in the report's parameter list so that SSRS can set the parameter value. Consequently, your databse server is complaining that you are trying to set the value of a local variable that hasn't been defined in your Sql statement, and thus throws an error message.
So you need to set up the Report Parameters in the report parameters section in the report designer. Your Sql can then reference your parameters like so:
SELECT * FROM MyTable WHERE SomeDate >= @rundate

The parameters normally get mapped into your dataset automatically but you might want to check this by going into the Parameters settings on your dataset to make sure. If the parameter doesn't exist there, set it up.

A: After lengthy trial and error, I found that the answer was to NOT have the parameter set to have a default value on the SSRS Report Server.


text:
Q: double pointer question in C (single pointer for next, but double pointer for prev) In the code of table.h for mysql. There are the following code
typedef struct st_table_share
{
    ...
    struct st_table_share * next,       /* Link to unused shares */
      **prev;

in the text book, we usally have
sometype *next, *prev;

but here it use **prev instead of *prev. What the reason to use double pointer for prev?

A: It's not pointing to the previous structure, as next is, it's pointing to the pointer that's pointing to this structure.
The benefit of doing this is that it can point to either the 'next' member of the preceding structure, or it can point to the actual head pointer itself - in the case where this is the first item in the list. This means that removing the item involves "*prev = next" in both cases - there's no special case for updating the head pointer.
The downside is that you can't (easily) use it to traverse the structure backwards; so it's really designed to optimize the case where you only care about traversing forwards, but want to easily remove an arbitrary node.

A: it is not a "double pointer" as you mention. rather it is referred to as "de-referencing".
int x = 10;
int* prev = &x;

*prev is the address of variable x.
now lets say you need to pass the address of the pointer variable prev to another function named foo which accepts an address of a pointer as its parameter (pointer to a pointer).
void function foo(int** ptr)
{
   prinft("%p", ptr); //this would print the address of prev

   printf("%p", *ptr); //this would print the value (the address of x) contained inside address contained inside ptr.

   printf("%d", **ptr); //this would print the value (the value of x, 10) contained at the address(address of x) contained inside address (address of prev) contained inside ptr
}


text:
Q: How to boxplot time series data (xts object) in r I have some time series data (18841 obs, 3 variables) which i have imported into R and have made it a time series object using xts. see the code below
library(ggplot2)
library(tseries)
require(zoo)
require(xts)
dates=seq(as.Date("1960/06/1"), as.Date("2011/12/31"), "days")
mytimeseries1 = xts(mydataset, order.by = dates)

Now mytimeseries1 is an xts object having variables var1, var2 and var3.
I want to have boxplot of these variables in groups of months or years (any of them). Kindly help with R code to generate boxplots.
I have tried this:
boxplot(var1~months,data=mytimeseries1, xlab="Months", ylab="First variable", main="Box plot of variable 1")

boxplot(var1~dates$months,data=mytimeseries1, xlab="Months", ylab="First variable", main="Box plot of variable 1")

But to no success, Kindly help.


text:
Q: Bisect queryset around another model's queryset I'm writing an user-driven app with several zones to it. I want to allow users to customise their messaging settings so they only get emails on the parts and actions they care about. I've drawn up the following Class:
class EmailSetting(models.Model):
    user = models.ForeignKey(User, related_name="%(class)s_related_user")
    key = models.CharField(max_length=50)
    value = models.BooleanField()

This is to be used by a method called get_users(key, default), which should return a list of users. For example, if I ask for a list of users that are subbed in on a key="new_post", default=False,  I should get a list of Users where they have an EmailSetting  with a value of True for that key. That's simple enough because I can just use the EmailSetting model.
If the default is True, things appear to be harder. I've never done anything more complicated than basic look-ups with Models, so I need a hand.
From a full list of Users, I need to remove ones with a False EmailSetting. Short of doing another query on EmailSetting looking for False entries and iteratively cutting them out of the first queryset, I can't see how to do this...
... But there must be another way because that stinks.

A: Well here's how I did it:
def get_users(key, default):
    if not default:
        return [es.user for es in EmailSetting.objects.filter(key = key, value = True)]
    return User.objects.exclude(pk__in = [es.user.pk for es in EmailSetting.objects.filter(key = key, value = False)])

Blisteringly simple when you think about it! Gotta love the Python syntax some times =)

A: I changed your related name on the user field, as I don't think you want to refer to an EmailSetting with "user" in the name.
def get_users(key, default):
    if default:
        return User.objects.exclude(emailsetting__key=key, emailsetting__value=False)
    else:
        return User.objects.filter(emailsetting__key=key, emailsetting__value=True)


text:
Q: Calling an Onclick() function without clicking? A websites Button isn't rendering on my browser. I know it's there, when I'm in the view source I still see the button, and the onclick function. Can I still call this function by passing the url the function? Or in the console?
Even if it's not an onclick, is it possible to call functions by either URL or Console?

A: You can click any DOM element by selecting it and calling the click() function.
document.getElementById("yourElementId").click();

Works with Jquery as well.
$(selector).click();

A: To accomplish this, you can use the following line:
document.getElementById("element_id").click()

According to MDN, this simulates a full click on the element, including all it entails:

When click is used with elements that support it (e.g. one of the  types listed above), it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an  element to initiate navigation as if a real mouse-click had been received.

Alternatively, you can use jQuery to accomplish the same thing:
$("#trigger").click();

A: Here is the simplest way:
function fireClick(node){
    if ( document.createEvent ) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);
    } else if( document.createEventObject ) {
        node.fireEvent('onclick') ;
    } else if (typeof node.onclick == 'function' ) {
        node.onclick();
    }
}

So you can trigger the click event for an element like below:
fireClick(document.getElementById('id'));

Reference from here.


text:
Q: Masonry layout not centering I implemented a masonry layout but the div classes are not centering in the middle of the screen. 4 classes across the screen centered left and right width have to be the same. Im trying to center it perfectly in the middle of the wrapper div tag. Thanks for helping. Check my website live : www.problemsofnewyork.com/test.php
index.php
   <?php include_once('php/db.php'); ?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Welcome</title>
    <link rel="stylesheet" href="css/test.css"/>

            <?php
                $result = $db -> prepare ("SELECT * FROM news ORDER BY id DESC");
                $result->execute();

                while($row = $result->fetch(PDO::FETCH_ASSOC)){

                    $id = $row['id'];
                    $title = $row['title'];
                    $content = $row['content'];
                    $image = $row['image'];
                    $posted_by = $row['posted'];

                    echo "

                        ".$title."

".$id.") ". $content ."

                        Posted by: ".$posted_by."

                    ";

                }
            ?>

and the css
* {
margin: 0;
padding: 0;
}

body {
    background: #e9e9e9;
}
#wrapper {
    width: 90%;
    height: auto;
    overflow: hidden;
    margin: 0 auto
}
.grid {
    width: 90%;
    margin: 15px auto;
}
.grid-item {
    width: 340px;
    background: #fff;
    float: left;
    margin-right: 15px;
    margin-bottom: 15px;
    box-shadow: 0 1px 2px 0 rgba(0,0,0,0.22);
}
.grid-item b {
    padding: 5px;
    word-wrap: break-word;
}
.grid-item p {
    padding: 5px;
    font-size: 13px;
    word-wrap: break-word;
}
.grid-item span {
    float: right;
    padding: 5px;
    font-family: monospace;
}
.grid-item img {
    width: 100%;
}

A: Never mind. Adding isFitWidth: true did the trick.
This code :

to this :


text:
Q: Eigenvalue Equation Reference: Exercise 1.3.15 of Terry Tao's random matrix theory book at https://terrytao.files.wordpress.com/2011/02/matrix-book.pdf.
Let $A$ be an $n\times n$ Hermitian matrix with $A_{n-1}$ the leading $n-1\times n-1$ submatrix.  Let $\lambda$ be an eigenvalue of $A$ that is distinct from all of the eigenvalues of $A_{n-1}$.  Suppose that $A_{n-1}=\sum_{j=1}^{n-1}\lambda_{j}v_{j}v_{j}^{*}$ is the eigendecomposition of $A_{n-1}$, and let $X$ denote the vector $(a_{nj})_{j=1}^{n-1}$.  Then
$$a_{nn} - \lambda = \sum_{j=1}^{n-1}\frac{|v_{j}^{*}X|^{2}}{\lambda_{j} - \lambda}.$$
The hint is to look at a decomposition of $Au=\lambda u$ into the first $n-1$ components and the last component, but I don't see how to simplify the resulting mess.

A: Divide $u$ into the vectors $(u_1,z)$ with $u_1 \in \Bbb C^{n-1}$ and $z \in \Bbb C$.  We have
$$
Au = \lambda u \implies
\pmatrix{A_{n-1} & X\\X^* & a_{nn}} \pmatrix{u_1\\z} =  \lambda \pmatrix{u_1\\z} \implies\\
A_{n-1}u_1 + zX = \lambda u_1 ; \qquad X^*u_1 + a_{nn}z = \lambda z \implies\\
(a_{nn} - \lambda)z = -X^*u_1; \qquad zX = (\lambda I - A_{n-1})u_1
$$
We ultimately want an expression that makes no reference to $u_1$, so we use the second equation to make the substitution $u_1 = z(\lambda I - A_{n-1})^{-1}X$, noting that the matrix is invertible because $\lambda$ is not an eigenvalue of $A_{n-1}$.
We can now rewrite the first equation as
$$
(a_{nn} - \lambda)z = -zX^*(\lambda I - A_{n-1})^{-1}X.
$$
Note that $z \neq 0$ since if we had $z = 0$, we would conlcude that $\lambda$ is an eigenvalue of $A_{n-1}$. So, we can divide both sides by $z$.  Expanding the right side via
$$
(\lambda I - A_{n-1})^{-1} = \sum_{j=1}\frac 1{\lambda - \lambda_j} v_jv_j^*
$$
yields the desired expression.


text:
Q: Xamarin.Forms MergedDictionaries I have created few XAML styles and added them all into App.xaml.cs as MergedDictionaries
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Axon.Mobile.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ResourceDictionaries/Colors.xaml"/>
                <ResourceDictionary Source="ResourceDictionaries/GlobalStylesDictionary.xaml"/>
                <ResourceDictionary Source="ResourceDictionaries/KeyStylesDictionary.xaml"/>
                <ResourceDictionary Source="ResourceDictionaries/ReceptionStylesDictionary.xaml"/>
                <ResourceDictionary Source="ResourceDictionaries/PutAwayStylesDictionary.xaml"/>
                <ResourceDictionary Source="ResourceDictionaries/ViewModelLocatorDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

This soolution is working when I use style defined in any dictionary as StatisResouce i.e:
<Label TextColor="{StaticResource Test1}"/>

However I would like to create dynamic resources and in that case I need to replace the styles in C#. The problem is that

Application.Current.Resources

contains these 6 another dictionaries as MergedDictionary property. All of given dictionaries are empty.
Why can't I get the defined styles in C#?

A: That's strange but I've noticed  that we can only access resources located in MergedDictionaries using the TryGetValue method for the moment:
 if (Application.Current.Resources.TryGetValue("StyleResourceKey", out var objectStyle))
 {
     var style = (Style)objectStyle;

     //Edit your style
 }


text:
Q: Compare two dates by ignoring seconds value in pandas Dataframe Here is dataframe 1.
index                 date  Count
4      2021-01-08 07:52:18   1
3      2021-01-08 08:53:34   10
0      2021-01-09 07:56:54   12
5      2021-01-09 09:52:17   13
1      2021-01-12 07:55:58   5

Here is dataframe 2
date                  Count
2021-01-08 07:52:00    0
2021-01-08 07:53:00    0
2021-01-08 07:54:00    0
2021-01-08 07:55:00    0
2021-01-08 07:56:00    0
...                    ...
2021-01-14 08:45:00    0
2021-01-14 08:46:00    0
2021-01-14 08:47:00    0
2021-01-14 08:48:00    0
2021-01-14 08:49:00    0

[8698 rows x 1 columns]

I need to place 1st dataframe Count values to 2nd Dataframe count.
Read values from dataframe one and search in datagrame 2. If found replace the count value.
but the problem is "seconds" value in 1st dataframe. Is there anyway to ignore it while comparing. (I can make logic but i need some fast way maybe built-in function in python or pandas)

A: As @anky suggested, you can floor the date on df as this is a smaller dataframe. Then merge the data.
import pandas as pd
df1 = pd.DataFrame({'date':['2021-01-08 07:52:18','2021-01-08 08:53:34',
                            '2021-01-09 07:56:54','2021-01-09 09:52:17',
                            '2021-01-12 07:55:58'],
                    'count':[1,10,12,13,5]})
df2 = pd.DataFrame({'date':pd.date_range('2021-01-08 07:52:00',periods=9000,freq='T'),
                    'count':[0]*9000})

print (df2)

df1['date'] = pd.to_datetime(df1['date'])
df1['date_str'] = df1['date'].dt.floor('T')

df2 = df2.merge(df1[['date_str','count']],left_on='date',right_on='date_str', how='left')

df2.drop(columns=['date_str','count_x'],inplace=True)
df2.rename(columns={'count_y':'count'},inplace=True)
print (df2)

The output of this will be:
df1:
                 date  count            date_str
0 2021-01-08 07:52:18      1 2021-01-08 07:52:00
1 2021-01-08 08:53:34     10 2021-01-08 08:53:00
2 2021-01-09 07:56:54     12 2021-01-09 07:56:00
3 2021-01-09 09:52:17     13 2021-01-09 09:52:00
4 2021-01-12 07:55:58      5 2021-01-12 07:55:00

df2: after merging with df1
                    date  count
0    2021-01-08 07:52:00    1.0
1    2021-01-08 07:53:00    NaN
2    2021-01-08 07:54:00    NaN
3    2021-01-08 07:55:00    NaN
4    2021-01-08 07:56:00    NaN
...                  ...    ...
8995 2021-01-14 13:47:00    NaN
8996 2021-01-14 13:48:00    NaN
8997 2021-01-14 13:49:00    NaN
8998 2021-01-14 13:50:00    NaN
8999 2021-01-14 13:51:00    NaN

A: If you run df1 with resampling in minutes, it will upsample from the minimum date and time to the maximum date and time. If you re-index it by the index of df2, you will get the desired output. I borrowed some of the code to create the data from @Joe Ferndz
import pandas as pd
df1 = pd.DataFrame({'date':['2021-01-08 07:52:18','2021-01-08 08:53:34',
                            '2021-01-09 07:56:54','2021-01-09 09:52:17',
                            '2021-01-12 07:55:58'],
                    'count':[1,10,12,13,5]})
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)
df1 = df1.resample('min').sum()

d_range = pd.date_range('2021-01-08 07:52:00', '2021-01-14 08:49:00', freq='1min')
df2 = pd.DataFrame(index=d_range)

df1 = df1.reindex(df2.index, fill_value=0)
df1

    count
2021-01-08 07:52:00     1
2021-01-08 07:53:00     0
2021-01-08 07:54:00     0
2021-01-08 07:55:00     0
2021-01-08 07:56:00     0
...     ...
2021-01-14 08:45:00     0
2021-01-14 08:46:00     0
2021-01-14 08:47:00     0
2021-01-14 08:48:00     0
2021-01-14 08:49:00     0


text:
Q: Zend_Form setAttrib title not translating with Zend_Translate When setting the title attribute in Zend_Form, this is not being translated. (Label & errors are translated fine)
// form file
$email = new Zend_Form_Element_Text('username');
$email->setLabel('auth.form.login.username')
      ->setRequired(true)
      ->addFilter('StripTags')
      ->addFilter('StringTrim')
      ->addFilter('StringToLower')
      ->addValidator('NotEmpty')
      ->setAttrib('title', 'auth.form.login.username');

// resource file
...
<tu tuid='auth.form.login.username'>
   <tuv xml:lang="en"><seg>Username</seg></tuv>
</tu>
...

Current result: auth.form.login.username
Expected result: Username

A: This is a normal behavior, nothing wrong with it.
The setAttrib() method doesn't translate its value parameter, so you need to use a Zend_Translate adapter as follows:
$email->setAttrib('title', $this->getTranslator()->translate('auth.form.login.username'))
This should fix your problem.
See Standard I18n Targets for more information.

Now that you've attached a translation object to, what exactly can you
  translate by default?

*

*Validation error messages.

*Labels.

*Fieldset Legends.

*Form and Element Descriptions.

*Multi-option Values.

*Submit and Button Labels.


text:
Q: merge data frame: get first value from the top from pandas data frame Hi I have data frame "df" with columns names- a to i.

After merging -

*

*I need to merge records(sum column h values) together where account number(column i), date(column a), bank code(column g) are same. Example - Rows 21327 and 21328 should be merged into one with amount value in h = 3922.00; For this I use pivot table -

output = pd.pivot_table(data=df, index=['a','g','i'],values='h',aggfunc=['sum'])
output=output.reset_index()

Columns in output dataframe -
MultiIndex([(  'a',  ''),(  'g',  ''),(  'i',  ''),('sum', 'h')],)

*

*Now I need to get back all other columns b,c,d,e,f but but these will have multiple records for a single account code (column i).

*I need first value of these columns from original "df" under the
condition - a,g,i in original dataframe "df" = a,g,i in output dataframe.
Stuck here. I tried this but does not seem to help me. I tried grouypby also but still stuck.

output.columns = list(map("".join, output.columns))

df2 = output.merge(df.drop('h',axis=1), on='i', how='left')

df2.columns

Index(['d_x', 'e_x', 'g_x', 'i', 'sumh', 'a', 'b', 'c','d_y','e_y','f','g_y'],dtype='object')

P.S. "df" does not have unique values in any of the columns so I can not use them as index

A: Your meaning is a little unclear, but this is my best interpretation of what you're looking for.  If this isn't what you're looking for, please clarify.
import pandas as pd

df = pd.DataFrame(
    [
        [11012022, 'TT', '0000120461', 11012022, 'GUY A', 'GUY B', 'xxx', 3921.99, 'GD148001'],
        [11012022, 'TT', '0000130000', 11012022, 'GUY A', 'GUY B', 'xxx', 0.01,'GD148001'],
        [20012022, 'TT', '0000140000', 20012022, 'GUY A', 'GUY C', 'xxx', 6163.34, 'GD148001']
    ],
    columns=['a','b','c','d','e','f','g','h','i']
)

df_sum = df.groupby(['a','i'])['h'].sum().rename('sum_h')
df = df.merge(df_sum, left_on=['a', 'i'], right_index=True)

print(df)

This gives the output:
          a   b           c         d      e      f    g        h         i    sum_h
0  11012022  TT  0000120461  11012022  GUY A  GUY B  xxx  3921.99  GD148001  3922.00
1  11012022  TT  0000130000  11012022  GUY A  GUY B  xxx     0.01  GD148001  3922.00
2  20012022  TT  0000140000  20012022  GUY A  GUY C  xxx  6163.34  GD148001  6163.34

I think then you're saying that you're looking for only the first row per (a, g, i) group?  If so, then do this:
df_first = df.groupby(['a','g','i']).first().reset_index().sort_index(axis=1)

print(df_first)

Gives output:
          a   b           c         d      e      f    g        h         i    sum_h
0  11012022  TT  0000120461  11012022  GUY A  GUY B  xxx  3921.99  GD148001  3922.00
1  20012022  TT  0000140000  20012022  GUY A  GUY C  xxx  6163.34  GD148001  6163.34

If you want to output the data to a file readable by Excel, then
df_first.to_csv("FileName")

A: If I understood correctly; you are just looking to group your df by 3 columns and based on that grouping aggregate one column to sum and the rest to get the first values.
columns = ['a','b','c','d','e','f','g','h','i']

df.groupby(['a', 'g', 'i']) \
    .agg(
    b = ('b', 'first'),
    c = ('c', 'first'),
    d = ('d', 'first'),
    e = ('e', 'first'),
    f = ('f', 'first'),
    h = ('h', 'sum')
) \
.reset_index()[columns]

Output:

groupby gets the columns you want to group by, agg gets columns you want to aggregate and how you want to aggregate them (first and sum for your case) and left part of the equation is just how you want to name the column after aggregation. Then we reset_index to keep group by columns that are in the index and use [columns] to order the columns to your preference.
Let me know if I am missing something.


text:
Q: I can SSH into a remote host but get "Connection reset by peer" with SSHFS, what do I miss? I created a key pair to connect to a Synology disk from 12.04. Deployed, edit ~/.ssh/config to automatically use it. Tested:
ssh user@remotesynology

-> works like a charm. Tested on a second remote machine (running Ubuntu server) -> works.
Now tested:
sshfs user@theubuntuserver: /home/user/ubuntuserver

-> works
Finally:
sshfs user@remotesynology: /home/user/remotesynology

-> error:
read: Connection reset by peer

I had a look at this issue, but that doesn't seem to apply (I have the user in the fuse group, and it works for the other machine) and I don't get a permission denied error.
What do I miss?

A: In my case (I tried to connect to remote synology as well!) the problem was that SFTP was not enabled on server side. The symptoms were the same: I could ssh to server without any problems, but sshfs command failed.
To enable SFTP on Synology server go to Control Panel -> File Services -> FTP tab -> SFTP section.

A: I've had issues in the past where sshfs was acting weird.  First thing you really should do after installing sshfs is restart your machine, or at least X, once you've added yourself to the fuse group.
This error is typically seen when a user is not in the fuse group, or if allow_other in fuse is not enabled.
There have been times where my ssh key was causing issues.  I've had to explicitly tell sshfs what key file to use, even when ssh was configured for it (~/.ssh/config).

*

*sshfs -oIdentityFile=/full/path/to/id_rsa user@machine
Another solution is to use your /etc/fstab and add a new entry here:
sshfs#USER@MACHINE:/remote/path/ /mnt/local/path/      fuse    user,_netdev,auto_cache,reconnect,uid=1000,gid=1000,IdentityFile=/full/path/to/.ssh/id_rsa,idmap=user,allow_other    0       2

This tells your machine to mount /remote/path to /mnt/local/path.  It's saying that this mount will be a fuse filesystem.  There are a few other settings that allow things such as mounting when networking becomes available, automatically re-connecting if there is a disconnect, etc.
The idmap and allow_other portion allow users within the fuse group to mount the filesystem.  It will also help map the permissions to match up to the user and group also specified.
In this example, you could then run the following to get the filesytem mounted:

*

*mount /mnt/local/path/

*ls /mnt/local/path/

A: I just had the same problem. The reason was SFTP subsystem not being enabled on the server (SSHFS is using it). The solution was adding the following line to /etc/ssh/sshd_config on the server:
Subsystem sftp /usr/lib/openssh/sftp-server

A: If you have iptables firewall rules set up on your server, it might've locked you out while you've been tinkering with sshfs - which would also result in Connection reset by peer.


text:
Q: Getting child object of gameObject in unity I have Object "Unit" with sub Objects "Monster and Health.
I also have Object Tower that has sphere collider.
Also I have OnTriggerEnter(Collider co) function in Tower Object that detects Unit.
When it does I can for example print the name "Unit" by accessing it
co.gameObject.name, or even co.name, which I guess is the same.
But how can I get the first subobject of unit for example. I mean Monster object, but not by name but just the FIRST SUB OBJECT of Unit object ?
UPDATE
Using this code:
void OnTriggerEnter(Collider co)
{
    Debug.Log(co.gameObject.transform.GetChild(0));
}

Causes an exception:
UnityException: Transform child out of bounds
Tower.OnTriggerEnter (UnityEngine.Collider co) (at Assets/Scripts/Tower.cs:19)

UPDATE 2
print(co.transform.childCount); gives 2
And that's correct cause I have
Unit
>

Monster

HealthBar

subobjects
Update 3
Tower code.
    using UnityEngine;
    using System.Collections;
public class Tower : MonoBehaviour
{
    // The Bullet
    public GameObject Bullet;

    // Rotation Speed
    public float rotationSpeed = 35;

    void Update()
    {
        transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed, Space.World);
    }

    void OnTriggerEnter(Collider co)
    {

        print(co.transform.childCount);

        if (co.gameObject.name == "Unit(Clone)")
        {

            GameObject g = (GameObject)Instantiate(Bullet, transform.position, Quaternion.identity);
            g.GetComponent<Bullet>().target = co.transform;
        }
    }
}

This Code Somehow manages to print twice
2
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)
0
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)

A: You'll have to operate on GameObject's transform. You can use Transform.GetChild(int index) function.
You will probably first have to check if there are any children because GetChild throws exceptions if you get out of bounds of the array. For that you'll have to use Transform.childCount.
More info can be found here:
http://docs.unity3d.com/ScriptReference/Transform.GetChild.html
http://docs.unity3d.com/ScriptReference/Transform-childCount.html


text:
Q: Generating Bootstrapped Samples in T-SQL Does anyone have some ideas on how to generate a bootstrapped sample of rows in T-SQL? The problem with using something like NEWID() or RAND() then just sorting is that you end up generating a random sample without replacement. Bootstrapping should be done by sampling with replacement.

A: Here's one solution. It starts by assigning a row identifier to each row in the population table.
Next, a uniform random integer between 1 and the rowcount of the population, inclusive, is generated using a call to RAND() via a view and the RandMod() function, as described in Question 3531450.
These two queries are JOINed together to create a random sample with replacement.
To get a bootstrapped sample of size K < N, sort on NEWID() and grab the top K rows.
SELECT TOP K
    key
    , NEWID()
FROM
(
    SELECT CAST(1 + (SELECT COUNT(*) FROM table))*RandMod() AS int) AS rowchoice
    FROM table
) AS r
LEFT OUTER JOIN
(
    SELECT key
        , ROW_NUMBER() OVER(ORDER BY key) AS rowid
    FROM table
) AS t
ON rowchoice = rowid
ORDER BY 2


text:
Q: d3 ordinal scale that adjusts to cluster size How can I shift the start point of each nested group according to how much space that group requires in each cluster to mainatin a constant bar width?   The ordinal scale allocates the same space for each cluster and then decreases the bar width to accomodate more bars but I want to adjust in a linear fashion to maintain the bar size.  Any ideas?
Thanks

A: Have you tried swapping the 'ordinal' with 'linear'.. because you can specify multiple domain and range values just like in ordinal scales and d3 will use all of them like an ordinal scale, but keeps the smooth linear interpolation..  Check out how this behaves.
   var scale = d3.scale.linear().domain([1,2,3,4]).range([1,20,300,4000])

Ok so after gaining more insight, it looks like you do have to copy the original scale and alter it to make a new scale for each object that has a different... umm, scale. Funny that obvious clue never entered my mind till just now.
I copied that d3 example into jsfiddle and altered it a little and seems to work. Was this the effect you were going for?
http://jsfiddle.net/2ktVC/2/
I mostly just replaced the harmless forEach loop in the example with these here guns.
data.forEach(function(d,i){/*-=======================*/
  var myNames = d3.keys(d).filter(function(key) { ////
  if(key !== "State" && d[key]){ /*-==============-*/
    allAgeNames[key]
        = true;
    return true;
  } return false;

  //==========
  xScales[i] = d3.scale.ordinal();/*==========*/
  d.ages = myNames.reduce(function(arr, name) {
    if(+d[name]) arr.push({
    value:+d[name],
     x:xScales[i],
      name: name
    });/*===*/
     return arr;
   },[]);/*

 //||||||||||||||||||||||||||==========================----*/
 xScales[i].domain(myNames).rangeRoundBands([0, x.rangeBand()], 0);
    d.x = /*|_|_|_|_|_*/
   xScales[i];
  d.ages.x =
 xScales[i]
});

Im kidding, stack overflow wont let me link to jsfiddle without some reference code.... so out come the jokes.


text:
Q: Android Coroutines and WeakReferences To avoid activity leaks when using threads, handlers, etc, I always wrap the Activity, View, Context, etc., in a WeakReference, so:
val textViewRef = WeakReference(textView)

thread {
    .....
    val view = textViewRef.get() ?: return@thread
    .....
}

For coroutines, do we need to do also the same? I mean to always wrap with WeakReferences to avoid leaks?


text:
Q: Error connecting to Exchange 2019 EWS with PowerShell I migrated from Exchange 2016 to 2019.  I have a PowerShell script I use to connect into exchange using EWS to access the inbox of a user.  It keeps failing on connect.  I tried to see if there is anything different from 2016 to 2019 but am coming up empty.  Here is the code I was using to connect to 2016
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$User_Domain = "domain"
$Password = "user_pass"
$EWS = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013"
$EWS.Url = "https://mail19.server.com/EWS/Exchange.asmx"
$Username = "username"
$EWS.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $Username, $Password, $User_Domain

$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

When I run the last line I get this error:
Exception calling "Bind" with "2" argument(s): "The request failed. The underlying connection was closed: An unexpected error occurred on a send."
At line:1 char:1
+ $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Mic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

This worked fine on my old 2016 exchange server. I am wondering if there is something on exchange I need to tweak or if the code needs tweaked to be able to work with exchange 2019.  I am able to access the EWS url and log in with the username/password.

A: Ok after scouring the internet it seems to be an issue with Exchange 2019 enforcing TLS1.2. I added the following line to the powershell script and the error goes away
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;

Hopefully that helps someone else


text:
Q: Finding solutions to an inequality(releating to statistics) I am trying to solve the following problem. A person rolls 3 die, what is the probability that the sum of these die is less than or equal to 9? I have built the following inequality model
x1+x2+x3<=9 where the domain of x's are 1<=x1,x2,x3<=6.
Letting x1 = x1+1 , x2=x2+1 and x3 = x3+1 we have the new inequality 0<=x1,x2,x3<=5. Also creating a "slack variable let x4 = 9-(x1+x2+x3) and we have the new equation: x1+x2+x3+x4=6.
Now using the popular stars and bars technique we have
* *** * * and have 9 positions where we can place a bar and we have 3 bars thus (9 3) = 84 possible outcomes. Now of these I would presume that the possible outcomes to subtract (as dies cannot have 0's) would be (6,0,0,0) , (0,6,0,0),(0,0,6,0) and (0,0,0,6) = a probability of 80/6^3 = 80/216. However the apparent answer in my textbook is 84 - (6,0,0,0) (0,6,0,0) and (0,0,6,0) which is 81/216. Why is it that we do not subtract the outcome of (0,0,0,6). Also is there another model I could use for this problem as this stars and bars model my teacher taught me is quite confusing.

A: I agree that the stars/bars approach is tricky for this problem, but it does give you a quick way to get the right answer--if your are careful!
Your mistake is that while none of the dice can be 6, the slavck variable an acceptably be 6.  So you don't need to subtract off $(0,0,0,6)$.
The easiest approach is to cleverly split the three dice into a pair (because you know probabilities for a pair of dice) and one other.
To roll a $9$ or less:

*

*The pair can be 2 and the other die anything -- this is $\frac{1}{36}=\frac{6}{216}$

*The pair can be 3 and the other die anything -- this is $\frac{2}{36}=\frac{12}{216}$

*The pair can be 4 and the other die anything except a 6 -- this is $\frac{3}{36}\times \frac{5}{6} = \frac{15}{216}$

*The pair can be 5 and the other die anything except a 6 or 5 -- this is $\frac{4}{36}\times \frac{4}{6} = \frac{16}{216}$

*The pair can be 6 and the other die a 1, 2 or 3 -- this is $\frac{5}{36}\times \frac{3}{6} = \frac{15}{216}$

*The pair can be 7 and the other die a 1 or 2 -- this is $\frac{6}{36}\times \frac{2}{6} = \frac{12}{216}$

*The pair can be 8 (careful here, an 8 is $\frac{5}{36}$ not $\frac{5}{36}$) and the other die a 1 --  this is $\frac{5}{36}\times \frac{1}{6} = \frac{5}{216}$

And the
total probability is $\frac{6+12+15+16+15+12+5}{216}=\frac{81}{216}=\frac{3}{8}$.
Another easy approach (assuming you don't know about multinomial coefficients) is to enumerate how you can roll 9 or less. Out of 216 possible rolls:

*

*There is $1$ way to roll a $3 : 1+1+1$

*There are $3$ ways to roll a $4 : 1+1+2$. Note that we count a possibility with two dice matching and one different as 3 ways, since there are three choices for which is the different die. Similarly, a possibility with all three dice different will be counted as 6 ways (three choices for the first number, then two for the second).

*There are $6$ ways to roll a $5: 1+1+3, 1+2+2$

*There are $3+6+1=10$ ways to roll a $6: 1+4+1,1+3+2,2+2+2$

*There are $3+6+3+3=15$ ways to roll a $7:1+1+5, 1+2+4,1+3+3,2+2+3$

*There are $3+6+6+3+3=21$ ways to roll an $8: 1+1+6, 1+2+5, 1+3+4,2+2+4,2+3+3$

*There are $6+6+3+3+6+1=25$ ways to roll a $9: 1+2+6,1+3+5,1+4+4,2+2+5,2+3+4,3+3+3$
Add them up and you get $81$ and a probability of $\frac{81}{216}=\frac{3}{8}$

BTW, the number of ways to roll 3,4, up to 18 are
$$(1,3,6,10,15,21,25,27,27,25,21,15,10,6,3,1)$$
And with 4 dice, the number of ways to roll 4 through 24 are
$$(1,4,10,20,35,56,80,104,125,140,146,140,125,104,80,56,35,20,10,4,1)$$


text:
Q: How can I type "{0}" more quickly in Visual Studio? In C#, it's common to have to type {0}, {1}, etc. when formatting strings with string.Format() or Console.WriteLine(). Considering its frequency, it's an awkward set of key strokes. But despite my searches, I couldn't find any sort of shorthand or hotkey to automatically insert it in Visual Studio. Has anyone figured out something to expedite the process?

A: One of the benefits from string interpolation in C#6.0, which I find helps.
Instead of:
string s = String.Format("{0} and {1}", variable1, variable2);

You can do:
string s = $"{variable1} and {variable2}";

See a guide: http://www.informit.com/articles/article.aspx?p=2422807

A: You can create the following command (C#) with my Visual Commander extension to insert text and then assign a keyboard shortcut to it:
    EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
    ts.Text = "{0}";


text:
Q: Extract specific XML element in CDATA taken from SOAP::Lite Response Hash My code below is connecting to a .asmx web service to get data.
The code extractes the CDATA into %keyHash below.
Rather than parsing the entire CDATA, is it possible to grab a specific data element in the SOAP CDATA by calling out it's path?
I read that I could use $soap->valueof() to get the data, is that correct?  and that this would require use of XPATH?
I ask as I am unfamiliar with this and I do not know if I am on the right path, are there other ways to do this?
My  $soap->valueof('//Images/Front')  attempts have failed, saying that, my first time using XPATH, could be getting it wrong but at this point I am guessing if this is the right way to go.
Any direction on whether I am on the right or wrong path in using valueof() would be appreciated!
Here is the code, it works. I have also included the obscurated CDATA data extracted from %keyHash.
use SOAP::Lite +trace => 'all';

 $soap = SOAP::Lite
    -> uri('..../')
    -> on_action( sub { join '/', '.....', $_[1] } )
    -> proxy('......asmx');

 $method = SOAP::Data->name('methodName')
    ->attr({xmlns => ...../'});

 @params = (
            SOAP::Data->name(tran=> 765) ->type(''),
            SOAP::Data->name(token => 0)->type(''),
            SOAP::Data->name(type=> 1)->type('')
             );

%keyHash = %{ $soap->call($method => @params)->body->{'GetmethodNameResponse'}->{'GetmethodNameResult'} };

# iterate through all fields and print them
foreach my $k (keys %keyHash) {
        print "$k=$keyHash{$k}\n";
}

Example of the data output,  I want the data in the string "THIS_IS_THE_DATA_I_WANT" (unable to put the path here for some reason)
RequestResult=0
Xml=<?xml version="1.0" encoding="utf-8"?>
<Images>
    <Front>THIS_IS_THE_DATA_I_WANT</Front>
</Images>

Thank You,
A

A: I solved this by using the following, hope it helps someone...
use XML::Simple;
%keyhash = %{ $soap->call($method => @params)->body->{'GetCheckXmlResponse'}->{'GetCheckXmlResult'}};
$getxml= %keyhash->{Xml};
$parsexml = XMLin($getxml);
print Dumper($parsexml); # Use this to point to your data and then grab it as per the line below
$frontside = $parsexml->{Images}->{Front};


text:
Q: Iterate through nested dicts, retaining key names, in Ansible I have a data structure that looks like this:
all_vms:
  clusterA:
    group1:
      - vm-01
      - vm-02
    group2:
      - vm-03
      - vm-04
  clusterB:
    group1:
      - vm-05
      - vm-06

The key names are not known beforehand. There may be shared "group" key names between clusters.
I want to loop through that data structure and run a task with each of the arrays, but I need the names of the keys they're contained within. The looping task would look something like:
- task:
     vms: "{{ item.value }}"
     group: "{{ item.key }}"
     cluster: "{{ item.parentkey }}"
  loop: "{{ all_vms | ??? }}"

And that would unroll to:
- task:
    vms:
      - vm-01
      - vm-02
    group: group1
    cluster: clusterA
- task:
    vms:
      - vm-03
      - vm-04
    group: group2
    cluster: clusterA
- task:
    vms:
      - vm-05
      - vm-06
    group: group3
    cluster: clusterB

I cannot change the main cluster/group structure, but I can change the structure of the elements that are currently arrays. I have considered just duplicating the keys as values, like this:
all_vms:
  clusterA:
    group1:
      cluster: "clusterA"
      group: "group1"
      vms:
        - vm-01
        - vm-02
    group2:
      cluster: "clusterA"
      group: "group2"
      vms:
        - vm-03
        - vm-04
  clusterB:
    group1:
      cluster: "clusterB"
      group: "group1"
      vms:
        - vm-05
        - vm-06

I would rather not do that, because it's terrible, but I can. But I can't even figure out a way to pop each of those things out into an array. (Edit: Actually, I think figured that out right after posting: all_vms | json_query('*.* | []'). I guess I can go with that if there's not a way to use the tidier data structure.)
Or if I could just use a @!#$% nested loop, if ansible would let me:
- block:
  - task:
      vms: "{{ item.value }}"
      group: "{{ item.key }}"
      cluster: "{{ cluster.key }}"
    loop: "{{ cluster.value | dict2items }}"
  loop: "{{ all_vms | dict2items }}"
  loop_control:
    loop_var: cluster

(Yes, I could do this with include_tasks, but having to have a separate file for a nested loop is just ridiculous.)
Any ideas how to iterate over this data structure without having to resort to a separate file just to do nested looping?

A: Although this is definitely possible using several combinations of filters directly in Ansible/jinja2, my 2 cent: save you nerves and time using a custom filter.
Demo below is for a a filter in the dedicated filters_plugin folder adjacent to your playbook. See the roles and collections documentations for better ways to distribute your filter if need be. Note that this was written real quick to put you on track and although it is fully functional with your above data example, you will need to add some data and errors checks if you intend to use this for a larger audience.
filters_plugins/my_cluster_filters.py
def all_vms_list(vm_dict):
    """Return a list of dicts for all vms with their cluster an group information"""
    vms_list = []
    for cluster, groups in vm_dict.items():
        for group_name, hosts in groups.items():
            for host in hosts:
                current_vm = {
                    'cluster': cluster,
                    'group': group_name,
                    'host': host
                }
                vms_list.append(current_vm)

    return vms_list

class FilterModule(object):
    """my cluster data filters."""

    def filters(self):
        """Return the filter list."""
        return {
            'all_vms_list': all_vms_list
        }

Then the test playbook.yml:
---
- hosts: localhost
  gather_facts: false

  vars:
    all_vms:
      clusterA:
        group1:
          - vm-01
          - vm-02
        group2:
          - vm-03
          - vm-04
      clusterB:
        group1:
          - vm-05
          - vm-06

  tasks:
    - debug:
        msg: "Host {{ item.host }} belongs to group {{ item.group }} inside cluster {{ item.cluster }}"
      loop: "{{ all_vms | all_vms_list }}"

gives:
PLAY [localhost] **************************************************************************************************************************************************************************************************************

TASK [debug] ******************************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'cluster': 'clusterA', 'group': 'group1', 'host': 'vm-01'}) => {
    "msg": "Host vm-01 belongs to group group1 inside cluster clusterA"
}
ok: [localhost] => (item={'cluster': 'clusterA', 'group': 'group1', 'host': 'vm-02'}) => {
    "msg": "Host vm-02 belongs to group group1 inside cluster clusterA"
}
ok: [localhost] => (item={'cluster': 'clusterA', 'group': 'group2', 'host': 'vm-03'}) => {
    "msg": "Host vm-03 belongs to group group2 inside cluster clusterA"
}
ok: [localhost] => (item={'cluster': 'clusterA', 'group': 'group2', 'host': 'vm-04'}) => {
    "msg": "Host vm-04 belongs to group group2 inside cluster clusterA"
}
ok: [localhost] => (item={'cluster': 'clusterB', 'group': 'group1', 'host': 'vm-05'}) => {
    "msg": "Host vm-05 belongs to group group1 inside cluster clusterB"
}
ok: [localhost] => (item={'cluster': 'clusterB', 'group': 'group1', 'host': 'vm-06'}) => {
    "msg": "Host vm-06 belongs to group group1 inside cluster clusterB"
}

PLAY RECAP ********************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

A: And here is the solution using several combinations of filters directly in Ansible / Jinja.
It combines the first level keys and values with a zip filter, in order to have a know subelements name — 1 — on which we can then use a subelements.
The second level key / value pair is accessible thanks to a dict2items mapped on the first level values.
The task ends up being
- set_fact:
    tasks: "{{ tasks | default([]) + [_task] }}"
  loop: >-
    {{
      all_vms.keys()
      | zip(all_vms.values() | map('dict2items'))
      | subelements([1])
    }}
  loop_control:
    label: "{{ item.0.0 }} — {{ item.1.key }}"
  vars:
    _task:
      task:
        vms: "{{ item.1.value }}"
        group: "{{ item.1.key }}"
        cluster: "{{ item.0.0 }}"

Given the playbook:
- hosts: localhost
  gather_facts: no

  tasks:
    - set_fact:
        tasks: "{{ tasks | default([]) + [_task] }}"
      loop: >-
        {{
          all_vms.keys()
          | zip(all_vms.values() | map('dict2items'))
          | subelements([1])
        }}
      loop_control:
        label: "{{ item.0.0 }} — {{ item.1.key }}"
      vars:
        _task:
          task:
            vms: "{{ item.1.value }}"
            group: "{{ item.1.key }}"
            cluster: "{{ item.0.0 }}"
        all_vms:
          clusterA:
            group1:
              - vm-01
              - vm-02
            group2:
              - vm-03
              - vm-04
          clusterB:
            group1:
              - vm-05
              - vm-06

    - debug:
        var: tasks

This yields:
TASK [set_fact] ***************************************************************
ok: [localhost] => (item=clusterA — group1)
ok: [localhost] => (item=clusterA — group2)
ok: [localhost] => (item=clusterB — group1)

TASK [debug] ******************************************************************
ok: [localhost] =>
  tasks:
  - task:
      cluster: clusterA
      group: group1
      vms:
      - vm-01
      - vm-02
  - task:
      cluster: clusterA
      group: group2
      vms:
      - vm-03
      - vm-04
  - task:
      cluster: clusterB
      group: group1
      vms:
      - vm-05
      - vm-06


text:
Q: Is there a problem rounding numbers with the calculator package? I am using the calculator package to round a number and am having trouble in some cases. Is there an issue with what I am doing?
I have included a MWE, uncommenting the line which rounds 0.0 will prevent the document from compiling. Perhaps this is just my machine or set-up?
\documentclass[a4paper]{memoir}

\usepackage{calculator}

\begin{document}

    % This is OK
    \ROUND[2]{1.2}{\A}
    The value of A is: \A

    % This is also OK
    \ROUND[2]{0}{\B}
    The value of B is: \B

    % This line kills it
    %\ROUND[2]{0.0}{\C}
    %The value of C is: \C

\end{document}

The output of this is as expected:

Any ideas?

A: The bug is in the internal macro \@@TRUNCATE, which should use the parsed integer part when it is the same as the input value:
\documentclass[a4paper]{memoir}

\usepackage{calculator}
\makeatletter
\def\@@TRUNCATE[#1]#2#3{%
    \begingroup
    \INTEGERPART{#2}{\cctr@tempa}%
    \ifdim \cctr@tempa\p@ = #2\p@
       \expandafter\@@@TRUNCATE\cctr@tempa.00000)[#1]{#3}% Change here
    \else
       \expandafter\@@@TRUNCATE#200000.)[#1]{#3}%
    \fi
    \@OUTPUTSOL{#3}}
\makeatother
\begin{document}

    % This is OK
    \ROUND[2]{1.2}{\A}
    The value of A is: \A

    % This is also OK
    \ROUND[2]{0}{\B}
    The value of B is: \B

    % This line kills it
    \ROUND[2]{0.0}{\C}
    The value of C is: \C

\end{document}

(There are also stray spaces in the definition: I've removed them.)
An alternative using siunitx:
\documentclass[a4paper]{memoir}
\usepackage{siunitx}
\sisetup{round-mode = places, round-integer-to-decimal}
\begin{document}

    % This is OK
    The value of A is: \num{1.2}

    % This is also OK
    The value of B is:  \num{0}

    % This line kills it
    The value of C is:  \num{0.0}

\end{document}


text:
Q: Is there a library function to split file and parent directory in Oracle PL/SQL? Given a file path I am trying to separate file name and the parent directory in Oracle PL/SQL. I am wondering if there is already a function available in PL/SQL libraries

A: There's no real need, if you're in 10g or later it's just needs a bit of regular expression finessing, which, depending on your OS might look as follows:
with filepaths as (
  select '/home/oracle/somedir/blah.sql' as linux
       , 'c:\home\oracle\somedir\blah.sql' as windows
    from dual
         )
select regexp_substr(linux, '[^/]+', 1
                     , regexp_count(linux,'/')) as linux
     , regexp_substr(windows, '[^\]+', 1
                     , regexp_count(windows,'[^\]+')) as windows
  from filepaths
       ;

LINUX    WINDOWS
-------- --------
blah.sql blah.sql

A: The INSTR and SUBSTR string functions can be used to do this, as follows:
WITH filepaths AS
  (SELECT '/home/oracle/somedir/blah.sql' AS LINUX,
          'c:\home\oracle\somedir\blah.sql' AS WINDOWS
     FROM DUAL)
SELECT LINUX,
       SUBSTR(LINUX, 1, INSTR(LINUX, '/', -1)) AS LINUX_PATH,
       SUBSTR(LINUX, INSTR(LINUX, '/', -1)+1) AS LINUX_FILE,
       WINDOWS,
       SUBSTR(WINDOWS, 1, INSTR(WINDOWS, '\', -1)) AS WINDOWS_PATH,
       SUBSTR(WINDOWS, INSTR(WINDOWS, '\', -1)+1) AS WINDOWS_FILE
FROM filepaths;

LINUX         /home/oracle/somedir/blah.sql
LINUX_PATH    /home/oracle/somedir/
LINUX_FILE    blah.sql
WINDOWS       c:\home\oracle\somedir\blah.sql
WINDOWS_PATH  c:\home\oracle\somedir\
WINDOWS_FILE  blah.sql

Share and enjoy.


text:
Q: Does Apple allow the use of ad APIs other than its own? Will apple allow an application that uses only 3rd party ad APIs like the following:
https://github.com/mopub/mopub-client/wiki/IntegrationHowToIOS
http://code.google.com/mobile/ads/docs/ios/fundamentals.html
to pass into its App Store?

A: Yes, they do, plenty of apps use non-iAd ads. You may also want to check out Millenial Media and Moblix.
Edit: And yes, as W Dyson says, you can maximize your revenue by using several networks at once, so that you'll always have an ad (iAds fill rate isn't 100%, so if you use them only, you'll end up not having an ad quite often).
If you look at some popular apps - like Words With Friends - you'll see that they sometimes show an iAd, but sometimes (probably even more often times) they show non-iAd ads, or even their own house ads about their other games.

A: If you're going to use iAd, you can check to see if you're being served a banner. If not, you can go to the other ad networks and request an ad. This gives you the most chances of having a banner served at all times. Always choose the ad networks in order of what makes you the most money.

A: Apple allows you to use other ad services.  Some APIs, such as AdMob, will pull ads from multiple providers for you so you don't have to worry about finding a service that has an available ad.


text:
Q: How to get Salesforce user license details Is there a way to programmatically, through some of the existing Salesforce SOAP or RESTful APIs, get the following license details:

*

*type of license (enterprise, professional, developer)

*trial mode?

*trial expiration date

*is API access enabled?

...and similar.

A: Have a look at the Organization object via the API. In particular the fields:
OrganizationType

Edition of the organization, for example Enterprise Edition or
  Unlimited Edition.

TrialExpirationDate

The date that this organization's trial license expires.

If you try an establish an API session for a user without access enabled you will get an exception back that it isn't support. E.g. INVALID_LOGIN
You could also look at the Users Profile. Look for the fields PermissionsApiEnabled, PermissionsApiUserOnly.


text:
Q: php curl ubuntu 400 bad request i have a working curl script and was testing it at my windows pc with xampp
<?php

$username = '123';
$password = '123456';

$url = 'https://192.168.0.100/test';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$exec = curl_exec($ch);

curl_close($ch);
echo $exec;
?>

Now I want to transfer it to my raspberry pi but i get an 400 error.
Whats the difference with the code ?
Can you help me ?
Thanks


text:
Q: Replace symbols in python script on distribution I have a python script that outputs the program name, version number and the author when called with command line arguments like --help or --version. Currently this information is hardcoded in the python script itself. But I use distutils for building/packaging the application so all this information is already present in the setup.py. Is it possible to let distutils write metadata like version and author name/email to the built python script so I only need to maintain this data in the setup.py file? Or is there another standard mechanism to handle stuff like that?

A: Do it the other way around.  Add the version number, the author name and other metadata you need in the script to the script itself.  Then import or execfile() the script in setup.py, and use the metadata defined in the script as arguments to the setup() function.

A: Have a file __version__.py in your package's root, create it on build with setup.py and fetch version information from it for --help or --version. That's how Mercurial rolls.

A: You could always use sed. The man page for sed is Here.
Do get that for windows (if you're using windows) it is right Here. It usually comes pre-installed on Linux, Unix, and OS X.


text:
Q: How to preserve user input data when Jeditable ajax post fails I'm using Jeditable in order to post some textarea data to the server. When an ajax post fails for some reason (network problem, server error etc.) it is necessary to leave the form visible and preserve the data that user has entered. Is it possible to do that thing with Jeditable? Thanks!

A: I don't have jeditable, but by reading their documentation it appears you need to override their onerror event.
onerror: function (settings, original, xhr) {
var error = eval('(' + xhr.responseText + ')');
//original.reset();
}


text:
Q: Replicating category/location page heirarchy Looking for advice, recommendations or suggestions for the most appropriate page structure for a website.
I am migrating a website which has about 1000 pages in the structure of /service/location/ – There are 4 services and about 250 locations
I leaning away from creating them as pages as it will just clog up the Pages section of the site making it cumbersome to find and edit core pages.
I was thinking of using categories and posts but this customer wants to do some blogging so I'm leaning away from clogging up the posts section as well.
I was thinking of a custom post type BUT the custom post type will add a slug at the beginning (e.g. /custom-slug/service/location/ ) which will mean that I will need to 301 redirect the 1000 URLs on the new site from /service/location/ to /custom-slug/service/location/).
I am leaning towards creating 4 custom post types (the 4 services) and then creating the 250 custom posts per customer post type – but I don't like the thought of having 4 extra menus/sections in admin (I could probably get over it – but I'm thinking that there's got to be a cleaner way)
OR
Just dealing with Categories and posts and ignoring over the "clogging up" issue…
Does anyone have any recommendations or suggestions? Is there a more appropriate way to do this?

A: You can make CPT's have "slugless" permalinks fairly easily:
register_post_type( 'service', [
    'hierarchical' => true,
    'public'       => true,
    // Other args, no need for "rewrite"
]);

// Change service to top-level permalink.
add_permastruct( 'service', '%service%', [
    'with_front' => false,
    'paged'      => false,
    'feed'       => false,
]);

// Remove all default service rewrite rules.
add_filter( 'service_rewrite_rules', '__return_empty_array' );

... which should be wrapped in a function and hooked to init. Then to "catch" these post types, we need a little pre_get_posts magic:
add_action( 'pre_get_posts', function ( $wp_query ) {
    if (
        $wp_query->is_main_query() &&
        $wp_query->is_singular() &&
        $wp_query->get( 'pagename' )
    ) {
        if ( ! $post_type = $wp_query->get( 'post_type' ) )
            $post_type = [];
        elseif ( ! is_array( $post_type ) )
            $post_type = [ $post_type ];

        $wp_query->set( 'post_type', array_merge( $post_type, [
            'page',
            'service',
        ]));
    }
});

Make sure to then flush your rewrite rules (just load Settings > Permalinks in the admin).


text:
Q: How to toggle visibility of several divs separately I have a series of text links that toggle visibility of a div element. The text links are styled to look like buttons and the text is being changed when the div is visible or invisible.
The problem is that when the first link is pressed, it toggles the visibility of it's own div plus all the other hidden divs and what is needed is that each link toggles the visibility of it's own div.
My question is what is the best way to solve this problem using only one function. Below is my code. Thanks!
The code can be also tested here:
http://jsfiddle.net/Bradg/eBfxB/
HTML:

        See all

Content One

        See all

Content Two

JS:
$(document).ready(function(){

   $(".slidingDiv").hide();
   $(".show_hide").show();

   $('.show_hide').toggle(function(){
       $(".slidingDiv").slideDown(
         function(){
           $("#plus").text("Hide all")
         }
       );
   },function(){
       $(".slidingDiv").slideUp(
       function(){
           $("#plus").text("See all")
       }
       );
   });
});

CSS:
.show_hide {
  display: none;
}

A: The version of toggle() that accepts two callbacks have been deprecated and removed, so you'll have to use click instead and do something like this
$(document).ready(function(){

   $(".slidingDiv").hide();
   $(".show_hide").show();

   $('.show_hide').on('click', function(e){
       e.preventDefault();

       var self    = this,
           sliding = $(this).closest('div').next('.slidingDiv').slideToggle(function(){
               $(self).text(function(_,txt) {
                    return txt == "Hide all" ? "See all" : "Hide all";
               });
           });
    });
});

FIDDLE
Note the use of the classes only (ID's must be unique) and the this keyword


text:
Q: add_custom_target not executing with multiple executable in a CMakeLists file I got a situation where another Makefile is executed from a CMakeLists.txt file.
Here is my root directory structure.
.
├── client.cpp
├── CMakeLists.txt
├── proto_lib
│   ├── Makefile
│   └── math.proto
└── server.cpp

This is a simple grpc test code where I am trying to compile a proto files using a Makefile create a static library. And then link that library to the final targets in the CMakefile. Makefile is working fine. CMakefile is also working fine with one executable.
Here is the CMakefile:
cmake_minimum_required(VERSION 3.5)

project(client-server)
message(STATUS "Compiling Network Function : ${PROJECT_NAME}")
set(CMAKE_CXX_STANDARD 11)

message(STATUS "Project Directory: ${PROJECT_SOURCE_DIR}")

set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)

set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
set(LIB_FILE ${CMAKE_CURRENT_SOURCE_DIR}/proto_lib/libmylib.a)

add_custom_target(libmylib.a ALL
                    COMMAND make
                    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/proto_lib
                    COMMENT "grpc headers and libraries are generating..."
)

add_executable(server server.cpp)

set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -g")
set(BASIC_LIBRARIES "-lpthread")
set(CMAKE_LINK_WHAT_YOU_USE ON)

set(LIBDIR "/usr/local/lib")

find_library(proto_location NAMES protobuf PATHS ${LIBDIR})
find_library(grpc_location NAMES grpc++ PATHS ${LIBDIR})
find_library(grpc_reflection_location NAMES grpc++_reflection PATHS ${LIBDIR})
find_library(dl_location NAMES dl PATHS ${LIBDIR})
find_library(grpc_location2 NAMES grpc PATHS ${LIBDIR})

if(proto_location)
  message(STATUS "protobuf library found at " ${proto_location})
endif()
if(grpc_location)
  message(STATUS "grpc++ found at " ${grpc_location})
endif()
if(grpc_reflection_location)
  message(STATUS "grpc_reflection found at " ${grpc_reflection_location})
endif()
if(dl_location)
  message(STATUS "dl found at " ${dl_location})
endif()
if(grpc_location2)
  message(STATUS "grpc found at " ${grpc_location2})
endif()

target_link_libraries(server ${proto_location}
                            ${LIB_FILE}
                            ${grpc_location}
                            ${grpc_reflection_location}
                            ${dl_location}
                            ${grpc_location2}
                            ${BASIC_LIBRARIES}
)

When I enter the command make after CMake . in the root directory.
it starts with following output...
Scanning dependencies of target libmylib.a
[ 33%] grpc headers and libraries are generating...
[ 33%] Built target libmylib.a
etc.. etc..

and it succeeds.(The internal Makefile creates header files and static objects using proto and grpc libraries. After that server.cpp can include the headers from inside the proto_lib/ folder and CMake build succeeds)
But when I add one more executable at the end of CMakeLists.txt,
add_executable(client client.cpp)
target_link_libraries(client ${proto_location}
                            ${LIB_FILE}
                            ${grpc_location}
                            ${grpc_reflection_location}
                            ${dl_location}
                            ${grpc_location2}
                            ${BASIC_LIBRARIES}
)

and then cmake . && make
does not start with internal Makefile build. Instead, it starts with client build.
Scanning dependencies of target client
[ 20%] Building CXX object CMakeFiles/client.dir/client.cpp.o
/home/deka/Academic/gemini/learning/client_server_async/advanced1/client.cpp:10:10: fatal error: proto_lib/math.grpc.pb.h: No such file or directory
 #include "proto_lib/math.grpc.pb.h"

Because proto_lib/Makefile is not executed first in this case therefore math.grpc.pb.h is not generated and that is what the above error is showing.
My question is: Why adding one more executable does not trigger the internal Makefile build at the start?
Thanks!


text:
Q: Node.js VSCode Debugger Missing Env Variables When I run the debugger in vscode I get this error:
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

I realized this was because the debugger isn't getting access to my .env file. My database uri is stored in my .env file. So the debugger can't see it.
How can I give my debugger access to the my .env file variables?

A: I fixed it by adding this to my launch.json file in my .vscode workspace folder. I added two values to the configurations object:
"env": { "PORT": "4000" },
"envFile": "${workspaceFolder}/backend/.env"


text:
Q: How to define an empty, "uninitialized" keypath and set it later? I made a program to calculate the total width/height of views (sometimes I want the total width, sometimes I want the total height). The only catch is: If I'm calculating the width, I want to add an extra 10 to the total. Here's my current code:
func calculateLengthOfAllViews(calculatingWidth: Bool) {
    let views = [
        UIView(frame: CGRect.zero),
        UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)),
        UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    ]

    var totalLength: CGFloat = 0

    if calculatingWidth {
        totalLength += 10 /// add extra 10 if calculating width
    } else {
        totalLength += 0
    }

    for view in views { /// add each view's width/height
        let length: CGFloat
        if calculatingWidth {
            length = view.frame.width
        } else {
            length = view.frame.height
        }
        totalLength += length
    }

    print("Total length is \(totalLength)")
}

calculateLengthOfAllViews(calculatingWidth: true) /// Total length is 160.0
calculateLengthOfAllViews(calculatingWidth: false) /// Total length is 100.0

This works fine. But, I'm repeating if calculatingWidth { in 2 places, to determine:

*

*Whether to add extra padding 10 padding

*Whether to use view.frame.width or view.frame.height as the length

The second if-statement is unnecessary, because it always evaluates to the same thing in every iteration.
So, I think keypaths are the way to go -- I can store a reference to either .width or .height from the first if-statement. However, how do I define a keypath without "initializing" it? I would like to do something like this:
let keyPath: KeyPath /// Reference to generic type 'KeyPath' requires arguments in <...>

if calculatingWidth {
    totalLength += 10
    keyPath = \UIView.frame.width
} else {
    totalLength += 0
    keyPath = \UIView.frame.height
}

for view in views {
    let length = view[keyPath: keyPath] /// Type of expression is ambiguous without more context
    totalLength += length
}

However, this gives me Reference to generic type 'KeyPath' requires arguments in <...>. How can I fix this?

A: class KeyPath<Root, Value>

is a generic type with two type parameters: the root type and the result value type, and those must be specified in the declaration of the variable. In your case it would be
let keyPath: KeyPath<UIView, CGFloat>

With that definition, the remaining code compiles as well.

A: You are using if at the start of the function, and if on every iteration of the loop. I think a better way to do this would be to use reduce(into:_:), to reduce the number of conditional branches.
Code:
func calculateLengthOfAllViews(calculatingWidth: Bool) {
    let views = [
        UIView(frame: CGRect.zero),
        UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)),
        UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    ]

    let totalLength: CGFloat

    if calculatingWidth {
        totalLength = views.reduce(10, { $0 + $1.frame.width })
    } else {
        totalLength = views.reduce(0, { $0 + $1.frame.height })
    }

    print("Total length is \(totalLength)")
}


text:
Q: Processing not working I'm trying to run this code in processing:
This is the simple code..
void setup()
{
  size(400,400);
  background(255,255,0);
}
void draw()
{
  ellipse(mouseX,mouseY,40,40);
  fill(0,255,255);
  strokeWeight(5);

}

But when i click run button i see no output,but get this:
java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at processing.app.contrib.ContributionManager.download(ContributionManager.java:62)
at processing.app.contrib.ContributionListing$2.run(ContributionListing.java:362)
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at processing.app.contrib.ContributionManager.download(ContributionManager.java:62)
at processing.app.contrib.ContributionListing$2.run(ContributionListing.java:362)
at java.lang.Thread.run(Unknown Source)

I have downloaded java jdk for windows 7 x64,processing 2.2.1...please help me!

A: I ran your code with processing 2.2.1 both Java and Javascript mode.. and working ._.
Since I saw that: "java.net.SocketException: Permission denied: connect"
I recommend to Check Firewall, antivirus, install Javascript mode, reboot computer, re-create the sketch, move the sketch directory...

A: The code is valid.
Do you have any sketches working, or is this the first. If so, I would suggest uninstalling and reinstall. Sounds as though something is missing. Also, processing 3 is now out with debug added.


text:
Q: topologies on $C(X,Y)$ Let $X,Y$ be two topological spaces. One can define various topologies on $C(X,Y),$ the space of continuous functions from $X$ to $Y.$ Let us take the group $G=Hom(X),$ the homeomorphisms of $X.$ Let $G_1$ be a subgroup of $G.$
Now, given $G_1$ and a $f\in C(X,Y),$ I am looking for "useful" nontrivial topologies $\tau$ on $C(X,Y)$ so that the set $\left\{f\circ h\colon h\in G_1\right\}$ has some nice properties with respect to $\tau.$
For example, when $X=Y=\mathbb{R}$ and $G_1$ is the group ,say, generated by $x\mapsto 2x,$ I want to say that $\left\{f(x),f(2x),f(4x),\ldots; f(x/2),\ldots\right\}$ satisfy a topological property. Or, if $G_1=F$ and $f\colon I\rightarrow X$ then $F$ operates on $C(I,X),$ so , what I want is a topology $\tau$ on $C(X,Y)$ such that the embedding $F\hookrightarrow Hom(C(I,X))$ has nice properties. Thank you.

A: The compact-open topology on $C(X,Y)$ has the virtue that it is complete (under various reasonable hypotheses on $X$ and $Y$).
A typical situation in which a group $G$ acts is that $G$ acts continuously on $X$. Without loss of generality, we can have $G$ acting on the right on $X$. There is the associativity $x(gh)=(xg)h$ for $x\in X$ and $g,h\in G$. Then $G$ acts on $f\in C(X,Y)$ by $gf(x)=f(gx)$.
One large class of examples is with $Y$ a real or complex vector space. Then $C(X,Y)$ is naturally a vector space, and for "representation theory" you'd want $C(X,Y)$ to have a topology so that $G \times C(X,Y) \rightarrow C(X,Y)$ is (jointly continuous).
It is easy to mess up this continuity requirement, even tho' one might imagine that it is somehow automatic. For example, with $G=X=Y={\mathbb R}$ and $C(X,Y)$ replaced by $L^\infty({\mathbb R})$, it is false. Similarly, for $X$ non-compact (and $Y=\mathbb R$), the plain sup-norm will cause the action of (big...) groups to fail to be continuous.
The simplest situation is when continuous _compactly_supported_ functions on $X$ are dense in the space of functions being considered. With $Y=\mathbb R$ and the uniform-convergence-on-compacts topology on $C(X,Y)$, this does hold, happily.
For $Y$ an abelian topological group, a similar situation holds, with similar caveats for $Y$ non-compact (like $\mathbb R$).
In summary, one almost always does want the compact-open topology on $C(X,Y)$, or else various things get weird.


text:
Q: axWindowsMediaPlayer1_PlayStateChange event not working i want to play automatically next song in my player. I have use windows media player object.
this is my code.
 private void timer2_Tick(object sender, EventArgs e)
    {
        if (songList.SelectedIndex < files.Length - 1)
        {
            songList.SelectedIndex++;
            timer2.Enabled = false;
        }
        else
        {
            songList.SelectedIndex = 0;
            timer2.Enabled = false;
        }

    }

    private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
    {
        if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
        {
            timer2.Interval = 100;
            timer2.Enabled = true;
        }

    }

but it's not working i have chacked timer code it is working but i think axWindowsMediaPlayer1_PlayStateChange event not working and in the designer code when i wrote this line for axWindowsMediaPlayer
 this.axWindowsMediaPlayer1.PlayStateChange += new System.EventHandler(this.axWindowsMediaPlayer1_PlayStateChange);

it shows this error:

No overload for axWindowsMediaPlayer1_PlayStateChange matches delegate System.EventHandler

is there any solution?

A: Take a look at the documentation for PlayStateChange. It gives you a clear example.
Rather than using what you have, simply use this event assignment instead:
axWindowsMediaPlayer1.PlayStateChange +=
      new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(axWindowsMediaPlayer1_PlayStateChange);


text:
Q: Contact form specific to a certain page/post Im using wordpress to display courses where the visitor can book a place if interested using a contact form (contactform7).
What Im doing today is letting the costumer write the name of the course so that I know which course to sign him/her up to. Ive had several complaints about this and some misses where I accidentally signed a customer on to the wrong course.
What I need to know is if there is a way in which I can make a contact form that is specific to the post/course that the customer wants to sign up on.
A friend told me to create a contact form for every post/course (contact form A has the same name as course A)
This wont work for me as I have new content often and it would mean that Ide have to spend my days creating contact forms.
Thank you!

A: in html it is called id or if you want name of the form, div, etc.
and then you just assign your form to that id then you extract them from $_POST and you're done
I think there you can find some answers:
http://bytes.com/topic/php/answers/9986-get-form-name-id
How to access the form's 'name' variable from PHP