text:
Q: CrudRepository not reading data from schema.sql Setup: I have a spring-boot application with a simple @Entity Customer object and CustomerRepository. I want to pre-load the database with test-data described here in my other question so I created schema.sql and data.sql files to load the database.
Problem: The CrudRepository seems to be using a different database than the one created with schema.sql and data.sql. I have not explicitly defined a datasource anywhere because I'm hoping that spring-boot can default everything for me (i.e., did not define spring.datasource in application.properties), and even if I do it doesn't do anything.
@Autowired
CustomerRepository r;
r.findAll(); // nothing but it should return the row "John Doe"

I don't get any errors it just returns nothing when I invoke findAll() on the repository.
schema.sql
drop table customer if exists;

create table customer (
    id bigint auto_increment,
    firstname varchar(80) null,
    lastname varchar(80) null
);

data.sql
insert into customer (firstname, lastname) values ('John', 'Doe');

Customer.java
package sample.jsp;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
public class Customer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

CustomerRepository.java
package sample.jsp;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
    List<Customer> findAll();
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.8.RELEASE</version>
    </parent>
    <artifactId>TestApp</artifactId>
    <packaging>war</packaging>
    <name>Spring Boot Web JSP Sample</name>
    <description>Spring Boot Web JSP Sample</description>
    <url>http://projects.spring.io/spring-boot/</url>
    <organization>
        <name>Pivotal Software, Inc.</name>
        <url>http://www.spring.io</url>
    </organization>
    <properties>
        <main.basedir>${basedir}/../..</main.basedir>
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: Change the name of data.sql to import.sql.
Spring Boot Database Initialization

A: I had the same problem and manage to fix it.
the problem wasn't the SQL files location (the log displayed the scripts execution).
It was the default behavior of DDL generation of Springboot with In-memory DB like H2 and the fact that the SQL files are executed before the DDL generation ('create-drop' by default for in-memory DB).
add this line in application.properties :
spring.jpa.hibernate.ddl-auto=validate

and you will be good.

A: I had a similar problem and achieved solving it.
To making it work, I had to put this annotation for every test method I need test data:
@Sql("classpath:data.sql")

I'm using spring-boot-starter-data-jpa with H2. In my case, I run a test that depends on some initial data (created in data.sql).
When I ran the test, the schema was created correctly but, like in you case, the CrudRepository seems to use different data).
note: I understand it might be late to answering this question, but I hope this helps someone who has the same problem.

A: This part of the Spring Boot docs describes how this work:
http://docs.spring.io/spring-boot/docs/1.2.2.RELEASE/reference/htmlsingle/#howto-intialize-a-database-using-spring-jdbc
In particular you have to make sure that both sql files are in the root of the classpath. Alternatively you could specify (even just to see if it works this way) the exact location/filename in your application.properties.
spring.datasource.schema=file:scripts/my-schema.sql


text:
Q: WCF Service, Windows Authentication we wrote a WCF service, deployed on IIS. we chose Integrated Windows Authentication. service can not be used in this case but if we can set the authentication method of the IIS virtual directory to "Anonymous" for WCF services, then the error will go away. But "Anonymous" is not acceptable for our WCF service. We have to use Integrated Windows Authentication to authenticate the client. Any one knows how to fix this problem?
Thanks in advance,
Ashish

A: You have to do a few things:

*

*Uncheck the anonymous access from your Virtual forlder and check Integrated windows security.

*Create the following binding configuration:
  <basicHttpBinding>
 <binding name="Binding1">
    <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows"  />
    </security>
 </binding>
 </basicHttpBinding>

*Apply the above configuration to your service and mex:
   <endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" contract="IService">
</endpoint>

   <endpoint address="mex" binding="basicHttpBinding" bindingConfiguration="Binding1" contract="IMetadataExchange">
</endpoint>

*

*Create a client and use NetworkCredential to pass your credentials:
       ServiceReference.MyClient proxy = new ServiceReference.MyClient();
       proxy.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("MACHINENAME\\USERACCOUNT", "passwrd");
       proxy.YourServiceOperation();

There are other ways to set username & password indivdually but it didn't work in .Net 4.0.
USERACCOUNT is a domain account or LDAP to which your WCF host computer is joined to.
If server isnt joined to a domain then create an account locally by running "lusrmgr.msc"

A: There are two main things that you need to watch out for:

*

*Is your configuration aligned: IIS, web.config (system.web and WCF)

*Is your client sending windows authentication information with the request

It is probably the second that is giving you problems. The IIS log should contain which user is making the call.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change Contact Owner for Profile I have a case in which a certain user with profile that should be able to transfer a contact even the contact is still not his own. I tried using the 'Transfer Record' in both the profile and permission set but it doesn't work if the contact is not associated with an account.
Question/Problem:
Is it possible to transfer a record not associated with the user and an account?
Is using the 'Transfer Record' a standard in developing a salesforce application?

A: It sounds to me as though you have a systemic problem and perhaps some security issues in terms of your OWD and other related settings in configuring your org that you may need to resolve in order to permanently solve your problem. First, I would advise against arbitrarily editing these contacts and assigning them to a dummy account. There could be a number of unpredictable consequences of taking such action at this time.
You've not said why you need to transfer the contact record by someone who doesn't currently own the record, nor what your OWD are Contacts. Knowing that information would be helpful in giving you a more complete answer to your questions. If you've enabled Account Roles and Contact Roles you'll have more flexibility in how you deal with the relationships between the two. Traditionally, Contacts have had their OWD set to Private which sounds like the source of your problem.
If you go under the assumption that every Contact is associated with an Account, you could potentially change your OWD settings to Controlled by Parent.  In that manner, whomever owns the Account or in some cases a Custom Object a Contact is related to, also owns all the Contacts associated with that Account or Custom Object. It really depends on your org's particular needs in terms of what the least amount of access level needs to be set at for the OWD as to which way to go in addition to how you set up security on the Parent as that's the setting that will primarily control access on the Contact object if you go that route.
Records can normally have their ownership changed in one of the following ways:

*

*By the existing owner of a record transferring to someone else

*Someone in the hierarchy above the existing owner reassigning it (if using roles)

*An admin or someone with delegated admin permissions transferring ownership of the record

Exceptions to the above would include:
 - Where you've set up a sharing group or have Apex sharing rules
 - Objects whose records are disseminated through a queue (usually via a pre-determined set of rules), the most common of which would be leads and cases
With all that having been said, it sounds as though the first thing you need to do is set up validation rules for Contacts such that no new contacts can be created unless they're associated with an Account. If you don't do that, this problem will never go away and 6 months from now, you'll be right back where you are today.
What you could do next, as an interim step as an Admin, is to take ownership of all contacts not associated with an Account. Once you do that, presumably you could query to search for related records and find out what account they need to be connected with. You could also create a sharing group and a sharing rule that would allow you to share them with those who might need to transfer ownership of them. Making this work would depend on what you've determined your OWD actually needs to be set at for Contacts. If Contacts not associated with an Account behave as though their OWD is set to Private as @ RobinDeBondt suggests, I believe this would work for you. What I would also do is create a validation rule that requires a Contact be associated with an Account in order for it to change Ownership so that whomever is trying to transfer ownership is required to associate it with an Account at the time of transfer. In doing so, you'll slowly solve your data problem.
I hope this helps provide some guidance and useful suggestions both short term and long term for resolving your issues. As references, I'd refer you to the Force. com Platform Fundamentals Workbook, the Security Workbook and the Security Implementation Guide.


text:
Q: How to get ALL LFU (Least Frequently Used) keys from Redis? Is it possible to retrieve all LFU keys from Redis database? If yes, please advice with a sample command-line.
Thanks a million,
Mughrabi

A: You can use OBJECT IDLETIME to get the number of seconds for which a key is not requested by a read or write operation. Then sort the idletimes for all keys to find LFU keys. Redis doesn't ship with a command which can print LFU keys as such. You probably have to write a script to do this.
https://redis.io/commands/OBJECT


text:
Q: Split a list inside a list Say that I have this list
List=[['this' ],['is'],['a'],['sentence']]

And I want  to split the inside lists so the output look like this
List=[['t','h','i','s'],['i','s'],['a'],['s','e','n','t','e','n','c','e']]

I tried
print([j  for i in list for j in i ])

but the output came as  ['this','is','a','sentence ']

A: There are 2 adjustments you need:

*

*You have sublists of length 1. Therefore, you need to access index 0 of each sublist.

*Your desired result has sublists within your results list. So you need inner list comprehensions within your outer list comprehension.

Here's an example:
lst = [['this'],['is'],['a'],['sentence']]

res = [[i for i in sublist[0]] for sublist in lst]

print(res)

[['t', 'h', 'i', 's'],
 ['i', 's'],
 ['a'],
 ['s', 'e', 'n', 't', 'e', 'n', 'c', 'e']]

The inner sublist comprehensions can be written more succinctly by feeding strings directly to list:
res = [list(sublist[0]) for sublist in lst]

A: Calling list on a string will return a list of the characters that make it up. This can be done, e.g., in a list comprehension:
lst = [['this'], ['is'], ['a'], ['sentence']]
result = [list(x[0]) for x in lst]

A: You can call list() on a string to get a list of composing characters as:
>> list("anmol")
>> ['a', 'n', 'm', 'o', 'l']

Similarly, you need to convert each of your string to a list as:
>> l = [['this' ],['is'],['a'],['sentence']]
>> [list(i[0]) for i in l]
>> [['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 'e', 'n', 't', 'e', 'n', 'c', 'e']]


text:
Q: How do I commit my working copy back to my repository without committing the subfolders in my working copy? I have a working copy that I checked out from my repository.  Now I want to commit it back to the repository but I don't want the subfolders in my working copy to be committed back any longer.  For example, my working copy file path is Z:\school\ and I don't want Z:\school\2011_2012\ to be committed back.  How would I implement this in a batch file for Windows?

A: Either commit the specific altered files, or use the --depth argument:

--depth ARG              : limit operation by depth ARG ('empty', 'files',
                              'immediates', or 'infinity')

Another option is of course the adding only the files in question to a changelist and commit those with --changelist


text:
Q: Split text according to size of stackpanel On a windows store app project, i have 2 StackPanels one with 200x200 and another with 200x500 and a scrollviewer inside it(just the second one), i also have a string with some text.
what i want is to split the string so that i get 2 strings, and the first one fits on the 200x200 area, and the rest will go to the second stackapanel with the scrollviewer.
How can i split a string according to the dimensions?
i tried using some functions like this one but dindt quite get it.
private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
        textBox1.Width = size.Width;
        textBox1.Height = size.Height;
    }

A: What you need is FormattedText class. TextRenderer is for WinForms, not WPF.
You can find sample implementation here: WPF equivalent to TextRenderer. You may need to asjust code to apply width and height of the box.
There're also methods for WinRT: How can I calculate the width of a string in Metro (without displaying it)?, but they depend on creating a TextBlock which isn't rendered.


text:
Q: Adding checkbox selected values in multi-dimensional array I am working on this demo. How can I add each selected row as an array into the data [] so that it looks like this:
[{"Cell phone":"BlackBerry Bold 9650","Rating":"2/5","Location":"UK"},
{"Cell phone":" Samsung Galaxy","Rating":"3/5","Location":"US"}]

Here is the code I have:
var data = [];
function myfunc(ele) {

 var values = new Array();
       $.each($("input[name='case[]']:checked").closest("td").siblings("td"),
              function () {
                   values.push($(this).text());
              });

       alert("val---" + values.join (", "));
 }

$(document).ready(function() {
    $("input.case").click(myfunc);
});

A: check if this works,
here is the fiddle demo
var data = [];
function myfunc(ele) {

 var values = [];
 var keys = [];
   $.each($("input[name='case[]']:checked").closest("table").find('th'),
          function () {
              keys.push($(this).text());
          });

 keys.shift(); // to remove the first key
 var len = keys.length, obj={}, ctr=0;
   $.each($("input[name='case[]']:checked").closest("td").siblings("td"),
          function () {
                obj[keys[ctr]]=$(this).text();
                ctr++;
                if(ctr==len){
                    values.push(obj);
                    obj={};
                    ctr=0;
                }

          });

   alert("val---" + JSON.stringify(values));
 }

$(document).ready(function() {
    $("input.case").click(myfunc);
});

A: http://jsfiddle.net/ugdas2em/
Try this:
var data =  {};
function myfunc(ele) {

    //var values = new Array();
    var k = 0;
    var j = 0;
    data[k] =  {};
    $.each($("input[name='case[]']:checked").closest("td").siblings("td"),
                 function () {
                     if(j==3)
                     {
                          k = k+1;
                          data[k] =  {};
                          j = 0;
                     }
                     //values.push($(this).text());
                     data[k][j] = $(this).text();
                     j=j+1;

                  });

           console.debug(data);
           //alert("val---" + values.join (", "));
     }

$(document).ready(function() {
    $("input.case").click(myfunc);
});

Note: If you want then you can use [] with data variable in place of {} in my code. You need to replace at three place. Thanks.


text:
Q: Name in alphabetic order I have two models in my project those are Supplier and Address models.
I am storing Supplier address information in address table like first_name,last_name..etc.
class Supplier < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

Now I want all suppliers in alphabetic order based on his name,Can any one knows?

A:  Supplier.includes(:address).order("addresses.name")

A: You'll need to use the order ActiveRecord method (which invokes the ORDER_BY function in SQL):
@suppliers = Supplier.joins(:address).order(name: :desc)


text:
Q: R Markdown: Create PDF in a folder A and save PDF in another folder B I have a problem with R Markdown:
I've created an PDF-File (out of the file: "example.Rmd") in a folder called A.
In the folder A there is another folder called B.
So my example.Rmd is in folder A, but now I want to have the created PDF-File in folder B, so when I hit the knit-Button, the PDF-File will go to the folder B.
How can I do this? Is there any code for that?
Thank you already for an answer!

A: There is no direct way of specifying .pdf output folder. However, you can change the working directory of the document. Hit down arrow beside Knit button and check knit directory.
Some more discussion can be found on this link


text:
Q: Unsupported major.minor version 49.0 I am getting the following exception whenever I login to my application ...

javax.servlet.ServletException:
  com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl
  (Unsupported major.minor version 49.0)

What does this mean and how can I resolve the problem?

A: Your code was compiled with Java 1.5 and your trying to run it with Java 1.4 ( or lower )
The solution is
a) Run it with Java1.5 ( perhaps using WAS 6+ )
b) Recompile it with Java 1.4

or
c) Recompile it with Java.15 but specifying the -target flag ( javac -target 1.4 .... )

The point is, you are trying to run 1.5 bytecode in a 1.4 vm

A: You have some code compiled with Java 5 features that you're trying to run on a 1.4 or earlier JVM. Check your JAVA_HOME variable is pointing at a 1.5 or later JDK.
Update: In your comment you say you are using WAS 5.1. WAS 5.1 doesn't support Java 5, from memory you need to be on WAS 6.1 to use Java 5 (looking for reference...)

A: You have a mismatch between your JVM that you're using to run the .class, and the version of Java used to compile the .class. The JVM running it is an earlier version of the JVM used to compile that class.
As detailed here, you have a version 1.5 class that you're trying to run on an earlier JVM.
EDIT : WAS 5.1 uses JDK 1.4, it would appear.

A: If you do build your classes with a higher version of the JDK for a minor version of JAVA use the -source and -target switches of the javac compiler. Some customers do need a minor version of Java, e.g. 1.4, while you're developing with 1.6. -source and -target are is remedy for this szenario. You might read the very good paper about byte code vs. source code versioning issues from Alex Buckley.
But since TransformerFactoryImpl is a Sun internal class, check your JAVA_HOME for your container, ut this is container specific.

A: This happens when you have compiled your code in a machine that uses a different JDK version to the one you end up running the code in.
Make sure you use the same JDK version in these different boxes.

A: Use sudo update-alternatives --config java and set the version you may want to use.


text:
Q: SELinux - CentOSx86_64: User command limitation SELinux - CentOSx86_64: User command limitation
Is SELinux the right tool for this job? If so, what is the best way to do it?
I would like to limit a particular user to only running some list of pre-defined commands/scripts (perhaps in their home directory). In addition the users scripts could have permission to run commands that the user cannot run directly (e.g. the user script test.sh could call 'ping localhost' but the user could not call 'ping localhost' directly from the command line). It is worth mentioning that I think these limitations are only required for one user account (I will not need multiple different configurations for different user accounts).
The OS is CentOSx86_64 and SELinux is enabled as follows:
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 24
Policy from config file:        targeted

I am very new to SELinux but have experimented with the following:
(1) I thought that the MLS policy would perhaps be best suited (This link looked promising: http://www.centos.org/docs/5/html/Deployment_Guide-en-US/sec-mcs-getstarted.html) for this task so I first attempted to switch this on. The 'SELinux Admin GUI' does not provide any option to change the policy from targeted so I attempted to directly change /etc/selinux/config. This ended with 'kernel panic' after rebooting so I decided to use the original installed policy (i.e. targeted).
(2) From the SELinux Admin GUI I created a new policy with a policy type of 'Minimal Terminal User Role'. For the 'name' I called it 'limiteduser'. I selected no roles that it would be transitioned to. I selected no additional roles. I selected 'All' TCP and UDP ports for binds/connects. I added no booleans to the policy. After running the generated .sh the new SELinux User and Role were created. I then assigned a login name to the 'limiteduser'. As expected this gave me a user with very limited privileges.
(3) Initially this new user could create a script in its home directory but could not execute it. After I set a boolean called 'allow_guest_exec_content' the user was able to execute the script. Initially the script just contained an 'echo' but once I changed this to ping it failed again. In an attempt to allow 'ping' for this new user I deselected the boolean user_ping (although I think this only applies to user_u rather than guest_u). To do what I want, I think an alternative might be to define a 'user_u' based type and then remove permissions (rather than go with the approach I have taken which is to go with a guest_u based type and add permissions - However I don't know how to do that either!).
(4) A number of online sources discuss policy files from a src directory but this was not installed and I could not figure out which package to install that would add this. I have the following selinux related packages installed:
libselinux.x86_64                   2.0.94-5.3.el6                     installed
libselinux-devel.x86_64             2.0.94-5.3.el6                     installed
libselinux-python.x86_64            2.0.94-5.3.el6                     installed
libselinux-utils.x86_64             2.0.94-5.3.el6                     installed
selinux-policy.noarch               3.7.19-126.el6_2.4                 @updates
selinux-policy-targeted.noarch      3.7.19-126.el6_2.4                 @updates
setools-console.x86_64              3.3.7-4.el6                        @base
setools-devel.x86_64                3.3.7-4.el6                        @base
setools-gui.x86_64                  3.3.7-4.el6                        @base
setools-libs.x86_64                 3.3.7-4.el6                        @base
setools-libs-java.x86_64            3.3.7-4.el6                        @base
setools-libs-python.x86_64          3.3.7-4.el6                        @base
setools-libs-tcl.x86_64             3.3.7-4.el6                        @base

(5) I looked at an alternative limited shell such as http://lshell.ghantoos.org/ but my company requirement is either to use SELinux -or- if all fails to use something already provided by the os (e.g. bash restricted) but this may not be as secure.
I think that I need to define a custom policy and within that:
(a) Allow the user to execute files in its home directory.
(b) Allow the user scripts to transition into different types in order to run commands that the user does not have permissions for.
Using the SELinux admin GUI (and the configuration files I am aware of) I have not idea how to do this.
Thanks for any help you can provide.

A: From the versions of the packages that is CentOS 6.
The approach to this problem I'm currently implementing, whose main advantages are auditing capabilities (through sudo), simplicity (not requiring MLS/MCS) and confinement, is the following:

*

*Users are provided a HOME directory using pam_namespace

*Users are given rbash login shell

*HOME is mounted noexec,ro, with things like HISTFILE pointing outside of their homes to a controlled place elsewhere

*Users are mapped to user_u seuser

*Users have their PATH set readonly and limited to ~/bin, where symlinks to allowed (basic) binaries exist

*Use of sudo is mandatory for any other command not in ~/bin

*/etc/sudoers file contains rules that take into account the role and type enforcement of the target user/command using the SELinux_Spec to specify the role and type sudoers options.

This blog post describes a use case.
This thread refers the state of things with regards to RHEL5/CentOS5 and RHEL6/CentOS6


text:
Q: AWS SAM, reference function name in Globals section I'm using a yaml AWS SAM file for CI/CD purposes.I need to add a new tag with the functionName as a value for that tag in each lambda function in that file.
Is it possible to do this without the need to define that tag separately in each function, knowing that I already have a functionName property already set for each lambda?
So Instead of this
 Resources:
  Function1:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: function1
      Tags:
        MyTag: function1         # << check this
  Function2:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: function2
      Tags:
        MyTag: function2        #  << check this

Im wondering if I can do this:
Globals:
  Function:
    Tags:
      MyTag: <FunctionName> # << reference to function name

Resources:
  Function1:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: function1
  Function2:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: function2

A:
Two ways to do this, check which one works for you

*

*Using reference for instance in your case if you want to refer "Function1" you should use Ref: "Function1" or Ref: "Function1LambdaFunction" (incase its defined using function tag)

*Get Attribute function - for instance in your case it would be (you can replace "Function1" to "Function1LambdaFunction" if you are using a direct function tag
    - Fn::GetAtt: [Function1, FunctionName]


text:
Q: How do I extract the last string of a csv file and append it to the other? I have csv file of many rows, each having 101 columns, with the 101th column being a char, while the rest of the columns are doubles. Eg.
1,-2.2,3 ... 98,99,100,N
I implemented a filter to operate on the numbers and wrote the result in a different file, but now I need to map the last column of my old csv to my new csv. how should I approach this?
I did the original loading using loadcsv but that didn't seem to load the character so how should I proceed?

A: In MATLAB there are many ways to do it, this answer expands on the use of tables:
Input
test.csv
1,2,5,A
2,3,5,G
5,6,8,C
8,9,7,T

test2.csv
1,2,1.2
2,3,8
5,6,56
8,9,3

Script
t1 = readtable('test.csv'); % Read the csv file
lastcol = t{:,end}; % Extract the last column
t2 = readtable('test2.csv'); % Read the second csv file
t2.addedvar = lastcol; % Add the last column of the first file to the table from the second file
writetable(t2,'test3.csv','Delimiter',',','WriteVariableNames',false) % write the new table in a file

Note that test3.csv is a new file but you could also overwrite test2.csv
'WriteVariableNames',false allows you to write the csv file without the headers of the table.
Output
test3.csv
1,2,1.2,A
2,3,8,G
5,6,56,C
8,9,3,T


text:
Q: How does iAd choose ads based on the country? There's a list of countries where iAds are available, but how do I check if the user's device is in that country?
In particular, does iAd choose ads based on the country:

*

*The device was bought in?

*The App Store the app was downloaded from (based on StoreKit receipts perhaps)?

*The current physical location of the device (presumably based on its IP address)?

I'd like to enable or disable certain non-iAD functionality based on whether iAd is available in that country.

A: iAd choose ads based on the user The current physical location of the device. Apple tracks user location and ads more based on location + interest + type of application (your app).
User can disable location based iAd from settings.
For more details you can also see this guide for advertiser although not for the developers but give you better idea how apple advertise.


text:
Q: AVAsset writer failed when app goes to background my [AVAssetWriter startWriting] gets called when the application enters background and it fails with following error:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x13c6cac20 {Error Domain=NSOSStatusErrorDomain Code=-16980 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-16980), NSLocalizedDescription=The operation could not be completed}
And this can happen even before applicationDidEnterBackground is called. I just need to pause the video recording when the application enters background and resume recording when the application comes to foreground later.
I also tried the beginBackgroundTaskWithExpirationHandler around my [AVAssetwriter startWriting] to buy sometime but it still fails.
What is the correct way of handling video recording when the app goes to background and comes to foreground later.
Thanks.

A: On iOS, if the status of an AVAssetWriter is AVAssetWriterStatusWriting when the client app goes into the background, its status will change to AVAssetWriterStatusFailed and appending to any of its inputs will fail.
You may want to use -[UIApplication beginBackgroundTaskWithExpirationHandler:] to avoid being interrupted in the middle of a writing session and to finish writing the data that has already been appended.
For more information about executing code in the background, see the iOS Application Programming Guide.


text:
Q: jQuery Div attr (width = $('#immagineCont').attr('clientWidth'); = undefined im no expert javascript coder.
i used like 5 hours now trying alot of different stuff. and i noticed some things that i cant figure out
im trying to get this to work
width = $('#immagineCont').attr('clientWidth');

but it returns undefined
i tried doing
width = $('#immagineCont').attr('id');

witch returned #immagineCont i guess is correct.
when i use
 $('#immagineCont')

i get this in firebug 1)
http://bildr.no/view/1325119 2)
http://bildr.no/view/1325120
so what im trying to do is get the damn clientWidth witch seems impossible. i even tryed children("0") and children("#0")
im going blow my brains soon ^^

A: attr would only work if there was an attribute with this name.
You may simply use
width = $('#immagineCont').get(0).clientWidth;

but you more probably need
width = $('#immagineCont').width();

which is more reliable when you want to do something that works the same across browsers (but doesn't include padding and borders).
You might also be interested by outerWidth.
A note about what happens and the need for get(0) : a jQuery collection (like $('#immagineCont')) wraps one or more standard DOM objects that you can get using get(i) or [i]. If you want to access native properties of the DOM object, when jQuery doesn't offer a proxy function, you need to get this native object first.

A: Use jQuery width() for this purpose:
var width = $('#immagineCont').width();

Also there is no attribute set to the element called clientWidth. This is a javascript property so it can be retrieved by dereferencing the jQuery object:
var width = $('#immagineCont')[0].clientWidth;


text:
Q: Modal de materialize no abre en hosting te agradezco por entrar!
Sucede que todo lo que esté dentro del while desaparece, si tengo un boton dentro del while y otro fuera del while, solo se muestra el que esta fuera del while, este es el codigo que tengo:
El HTML es este:
<?php
  include("php/conexion.php");
  while($v = mysqli_fetch_array($resultado)){
?>

<a href="#modal<?php echo $v['id'] ?>" class="modal-trigger"><?php echo $v['titulo'] ?>

<?php
  }
?>

El PHP:

<?php
    $host_name = 'asd';
 $database = 'db7185617051';
 $user_name = 'dbo7185617051';
 $password = 'dsa';
 $connect = mysqli_connect($host_name, $user_name, $password, $database);

 if (mysqli_connect_errno()) {
  die('
Failed to connect to MySQL: '.mysqli_connect_error().'
');
 } else {
  $query = "SELECT * FROM informacion";
  $resultado = mysqli_query($conexion,$query);
 }
?>

Desde ya muchas gracias!

A: Intenta esto en tu js
$(document).ready(function(){
        $("#btnTriggerModal").on("click", function() { //Agrega un ID a tu botón
            $('.modal').modal();
            $('#modal2').modal('open');
        });
    });
});

A: No puedes asignar el mismo id a varios elementos, los id deben ser únicos no se pueden repetir. Dentro del while siempre generas el el mismo ìd por lo que que cada modal que se genera repite el id:
<?php
  include("php/conexion.php");
  while($fila = mysqli_fetch_array($resultado)){
?>

  ...

<?php
}
?>

Podrías generar el link y el modal a la vez:
<?php
  include("php/conexion.php");
  while($fila = mysqli_fetch_array($resultado)){
?>

<a class="waves-effect waves-light btn modal-trigger" href="#modal<?= $fila['id'] ?>">Modal <?= $fila['id'] ?>

<div id="modal<?= echo $fila['id'] ?>" class="modal">

<?php echo $fila['titulo'] ?>

touch_app¿Qué es esto?

<?php echo $fila['que-es'] ?>

help¿Para que sirve?

<?php echo $fila['para-que-sirve'] ?>

build¿Cómo se usa?

<?php echo $fila['como-se-usa'] ?>

dvrMás comandos

<?php echo $fila['mas-comandos'] ?>

burst_modeMás imágenes

<?php echo $fila['imagenes'] ?>

      Tengo un problema
      ¡Gracias! :D

<?php
 }
?>

Quedando algo así:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">

  Modal 1

modal 1

touch_app¿Qué es esto?

<?php echo $fila['que-es'] ?>

help¿Para que sirve?

<?php echo $fila['para-que-sirve'] ?>

build¿Cómo se usa?

<?php echo $fila['como-se-usa'] ?>

dvrMás comandos

<?php echo $fila['mas-comandos'] ?>

burst_modeMás imágenes

<?php echo $fila['imagenes'] ?>

        Tengo un problema
        ¡Gracias! :D

  Modal 2

    <img class="info-img" src="<?php echo $fila['img'] ?>">

modal 2

modal2

<?php echo $fila['que-es'] ?>

help¿Para que sirve?

<?php echo $fila['para-que-sirve'] ?>

build¿Cómo se usa?

<?php echo $fila['como-se-usa'] ?>

dvrMás comandos

<?php echo $fila['mas-comandos'] ?>

burst_modeMás imágenes

<?php echo $fila['imagenes'] ?>

    Tengo un problema
    ¡Gracias! :D


text:
Q: Storing and comparing time for multiple timezones I have this table:
CREATE TABLE IF NOT EXISTS `config` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `time` time NOT NULL,
  `zone` char(64) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `time_zone` (`time`,`zone`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Looking like this:
ID  TIME        ZONE
-----------------------------
3   00:07:36    Pacific/Apia
1   10:01:50    Europe/London
2   12:07:20    Asia/Thimbu
4   00:01:50    US/Hawaii

The table shows different times in different countries, I need to know which ones are happening now.
How can I return all the IDs for which the time is now?
Example Result:
If the current UTC time is 10:01:50 I would want to return the following rows:
ID  TIME        ZONE
-----------------------------
1   10:01:50    Europe/London
4   00:01:50    US/Hawaii

London is UTC +0, and Hawaii is UTC -10, so both are happening now.

I know MySQL has all the timezone information built-in, but I don't know how to query it.

A: SELECT CONVERT_TZ(CONCAT(CURDATE(),' ',time),zone,'GMT') FROM config;
+---------------------------------------------------+
| CONVERT_TZ(CONCAT(CURDATE(),' ',time),zone,'GMT') |
+---------------------------------------------------+
| 2013-10-31 10:01:50                               |
| 2013-10-31 11:07:36                               |
| 2013-10-31 10:01:50                               |
| 2013-10-31 06:07:20                               |
+---------------------------------------------------+

Note that this makes assumptions about the dateline that are going to be incorrect in terms of both date and (at specific times of year) time.


text:
Q: Memory Efficient Way to Remove Kth Node from End of Linked List This is a known problem with several known solutions, but my current struggle is to try and find the most efficient way to solve it, considering memory usage (and not time-complexity).
The problem: Given a singly-linked-list of unknown (but potentially quite large) size N, remove the Kth member from the end of the list. 0 <= K < N.
If K is 0, remove the last node of the list. If K = N-1, remove the first node in the list.
My initial approach was recursion - it's the simplest to write, and its time complexity is O(N) - going over the list twice, to the end and back.
public int removeKLast(Node<T> node, int k) {
    if (node.getNext() == null) {
        return k;
    } else {
        int current = removeKLast(node.getNext(), k);
        if (current == 0) {
            node.setNext(node.getNext().getNext());
        }
        return current - 1;
    }
}

It had some end-cases that needed solving (like removing the first node from the list) but was otherwise simple enough.
My issue is that this implementation means the entire linked list is stored in memory, with the overhead associated with objects. I wanted to know if a more efficient solution (still in O(N) time, running over the list twice at most) could be found, using at most K primitive ints in memory at any given time.

A: Start list traversal. After K steps start the second iterator and then walk in parallel. When the first iterator reaches the end, the second one stands on the node to delete.
This approach cannot change O(n) complexity and performs about 2n (2n-k) step operations, but excludes "delay" between end finding and deletion

A: Consider retrieving the list size first:
public int size(Node<T> node) {
   int size = 0;
   if(node != null) {
   for(; node.getNext() != null; node = node.getNext())
       size++;
   }
   return size;
}

Then you can remove the k-th before last in one go:
public int removeKLast(Node<T> node, int size, int k) {
    for(int i = 0; node = node.getNext() && i < size - k - 1; ++i) {}
    node.setNext(node.getNext().getNext());
}

Additional memory needed: 1 variable of type int (size).
Time complexity: O(n).
You missed to explain how you store your head node, so this implementation will not work when you try to remove the first node. The modification needed to fix this would be something like:
public void removeKLast(Node<T> node, int size, int k) {
    if(k == size - 1) {
        node.setHead(node.getHead().getNext());
    } else {
        for(int i = 0; node = node.getNext() && i < size - k - 1; ++i) {}
        node.setNext(node.getNext().getNext());
    }
}


text:
Q: Bind DataGrid CellTemplate with AutoGenerateColumns=true I've got the DataGrid with Auto generated columns
Xaml:
<DataGrid
ItemsSource="{Binding MyCustomViewModel.DataTable, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, ConverterCulture='en-US', StringFormat={}{0:F3}, IsAsync=True}"
VerticalScrollBarVisibility="Auto" />

Parts of the view model:
public class MyCustomViewModel
{
    public CustomGridDataSource DataTable {get; set; }
}

The table data source - consists of custom data rows :
internal sealed class CustomGridDataSource : ObservableCollection<CustomGridDataSourceRow>, ITypedList
    {
private readonly PropertyDescriptorCollection _descriptors;

    public CustomGridDataSource( int rows, int columns )
    {
        Rows = rows;
        Columns = columns;

        for(int i = 0; i < rows; i++)
        {
            var row = new CustomGridDataSourceRow( this, i );
            row.PropertyChanged += Row_PropertyChanged;
            for(int j = 0; j < columns; j++)
            {
                row.Add( "0.0" );
            }
            this.Add( row );
        }

        List<PropertyDescriptor> pds = new List<PropertyDescriptor>();
        for(int i = 0; i < columns; i++)
        {
            PropertyDescriptor pd = new CellPropertyDescriptor( i );
            pds.Add( pd );
        }

        _descriptors = new PropertyDescriptorCollection( pds.ToArray() );
    }

    public int Columns { get; }

    public int Rows { get; }

    public event ListChangedEventHandler OnCellChanged;

    private void Row_PropertyChanged( object sender, PropertyChangedEventArgs e )
    {
        OnCellChanged?.Invoke( this, new ListChangedEventArgs( ListChangedType.ItemChanged, (sender as CustomGridDataSourceRow).RowIndex ) );
    }
    public PropertyDescriptorCollection GetItemProperties( PropertyDescriptor[] listAccessors )
    {
        return _descriptors;
    }

    public string GetListName( PropertyDescriptor[] listAccessors )
    {
        return "array";
    }
}

And row data source - each row has the index that returns string (c sharp):
internal sealed class CustomGridDataSourceRow : CustomTypeDescriptor, INotifyPropertyChanged
    {

        private readonly CustomGridDataSource _parent;
        private readonly List<string> _cellValues;

        public CustomGridDataSourceRow( CustomGridDataSource owner, int rowIndex )
        {
            _parent = owner;
            RowIndex = rowIndex;
            _cellValues = new List<string>();
        }

        internal int RowIndex { get; }

        public void Add( string value )
        {
            _cellValues.Add( value );
        }

        public string this[int index]
        {
            get { return _cellValues[index]; }
            set
            {
                string proposedValue = value;

                if(_parent.NeedCellChangingEvent)
                {
                    var args = new CellChangingEventArgs( RowIndex, index, value );
                    _parent.RaiseCellChanging( args );
                    proposedValue = args.ProposedValue;
                }

                _cellValues[index] = proposedValue;
                PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( index.ToString() ) );
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string GetClassName()
        {
            return "CustomGridDataSourceRow";
        }

        public override string GetComponentName()
        {
            return "CustomGridDataSourceRow";
        }

        public override PropertyDescriptorCollection GetProperties()
        {
            return GetProperties( null );
        }

        public override PropertyDescriptorCollection GetProperties( Attribute[] attributes )
        {
            return _parent.GetItemProperties( null );
        }
    }

Some of the logic is omitted - user can edit cells, that logic is partly omitted.
It works just fine like this. However, I need to have the icon to be showable in each cell and attach additional flag to each cell's value that will control icon's visibility.
My original idea was using cell templates. However, I don't get it how can that be done with AutoGeneratedColumns=true.
Is it possible to bind cells like that?


text:
Q: How to access two elements at once in a for loop without duplicates in python? I have a table that looks like this:

Celebrity
Username

A
user1

B
user1

C
user2

A
user3

A
user2

D
user2

D
user3

I wrote a function to find the overlaps of users between two celebrities:
def num_of_fans_overlap(cel1,cel2,data,Celebrity,Usernames):
    l = [cel1,cel2]
    Res = len(data.loc[data['Usernames'].map(data.groupby('Usernames').agg(set)['Celebrity'].eq(set(l)))])/2
    return print(int(Res))

for example, if I run num_of_fans_overlap(A,B,data,"Celebrity","Username"), I will get 1, which means one user has followed both celebrities.
Now I want to run a for loop, and the output should look like this:
("A", "B", 1)
("A", "C", 1)
("A", "D", 2)
("B", "C", 0)
("B", "D", 0)
("C", "D", 1)

I have been stuck here. Hope someone can help.

A: Check with crosstab then dot
s = pd.crosstab(df.Celebrity,df.Username)
s = s.dot(s.T)
out = s.mask(np.triu(np.ones(s.shape)).astype(bool)).stack()
Out[301]:
Celebrity  Celebrity
B          A            1.0
C          A            1.0
           B            0.0
D          A            2.0
           B            0.0
           C            1.0
dtype: float64

A: First, the function num_of_fans_overlap shouldn't return a print().
def num_of_fans_overlap(cel1,cel2,data):
    l = [cel1,cel2]
    Res = len(data.loc[data['Usernames'].map(data.groupby('Usernames').agg(set)['Celebrity'].eq(set(l)))])/2
    return int(Res)

Second, if the variable celebrities is a list of unique values on the Celebrity column.

from itertools import combinations
celebrities = list(data.Celebrity.unique())
for (cel1, cel2) in combinations(celebrities, 2):
   fans_overlap = num_of_fans_overlap(cel1, cel2, data)
   print((cel1, cel2, fans_overlap))

A: The naive way to do this:
celebs = ["A", "B", "C", "D"]
for i in range(len(celebs)):
    for j in range(i+1, len(celebs)):
        celeb_pairs = (celebs[i], celebs[j])
        run_your_function_here(*celeb_pairs, other, parameters)

You can also do this elegantly by using the itertools.combinations function:
import itertools

celebs = ["A", "B", "C", "D"]
for celeb1, celeb2 in itertools.combinations(celebs, 2):
    run_your_function_here


text:
Q: How to cast  to List? I have a record class to parse objects coming from Firestore.  A stripped down version of my class looks like:
class BusinessRecord {
  BusinessRecord.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        name = map['name'] as String,
        categories = map['categories'] as List<String>;

  BusinessRecord.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  final String name;
  final DocumentReference reference;
  final List<String> categories;
}

This compiles fine, but when it runs I get a runtime error:
type List<dynamic> is not a subtype of type 'List<String>' in type cast
If I just use categories = map['categories']; I get a compile error: The initializer type 'dynamic' can't be assigned to the field type 'List<String>'.
categories on my Firestore object is a List of strings. How do I properly cast this?
Edit: Following is what the exception looks like when I use the code that actually compiles:

A: final list = List<String>.from(await value.get("paymentCycle"));
I have use this when i am getting data from Firebase

A: Imho, you shouldn't cast the list, instead cast its children one by one, for example:
UPDATE
...
...
categories = (map['categories'] as List)?.map((item) => item as String)?.toList();
...
...

A: Easier answer and as far as I am aware also the suggested way.
List<String> categoriesList = List<String>.from(map['categories'] as List);

Note the "as List" is probably not even needed.

A: Just to put this out there, if you want to cast dynamic to String:
List dynamiclist = ['hello', 'world'];

List<String> strlist = dynamiclist.cast<String>();

A: Easy Answer:
You can use the spread operator, like [...json["data"]].
Full example:
final Map<dynamic, dynamic> json = {
  "name": "alice",
  "data": ["foo", "bar", "baz"],
};

// method 1, cast while mapping:
final data1 = (json["data"] as List)?.map((e) => e as String)?.toList();
print("method 1 prints: $data1");

// method 2, use spread operator:
final data2 = [...json["data"]];
print("method 2 prints: $data2");

Output:
flutter: method 1 prints: [foo, bar, baz]
flutter: method 2 prints: [foo, bar, baz]

A: The accepted answer doesn't actually work if you have 'implicit-dynamic' enabled.
It's also not easy to read.
A fully typed version of the conversion is:

List<String> categories = jsonToList(json['categories']);

Place the following functions in a helper library and you have a solution that is type safe, reusable and easy to read.
Set<T> jsonToSet<T>(Object? responseData) {
    final temp = responseData as List? ?? <dynamic>[];
    final set = <T>{};
    for (final tmp in temp) {
      set.add(tmp as T);
    }
    return set;
  }

  List<T> jsonToList<T>(Object? responseData) {
    final temp = responseData as List? ?? <dynamic>[];
    final list = <T>[];
    for (final tmp in temp) {
      list.add(tmp as T);
    }
    return list;
  }


text:
Q: 'Connection Refused' EXCEPT filezilla I have a rather strange problem, I am unable to connect to a host using any other ftp client or putty EXCEPT filezilla.
This was not the case two weeks back. The error I am now getting is "Connection Refused". The issue is reproduced on several machines.
Is filezilla using some other protocol?

A: Well I found the issue, it seems that the hosting has disabled SSH access. Filezilla uses FTP protocol so it was working. WinSCP was set to use SSH instead of FTP so that wasn't working as well.


text:
Q: ZF3: ServiceNotFoundException while creating a class with Abstract Factory registered in ServiceManager I got problem with the Abstract Factories example.
I get ServiceNotFoundException while creating a class with Abstract Factory registered in the ServiceManager.
First I download zend-servicemanager with composer
composer require zendframework/zend-servicemanager

Then I run the ServiceManager example in the single file (for simplicity).
<?php
require_once 'vendor/autoload.php';

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;

Class that should be obtained with ServiceManager.
class A
{
    public $text;

    public function __construct()
    {
        $this->text = "Default text";
    }
}

I use MyAbstractFactory from documentation.
class MyAbstractFactory implements AbstractFactoryInterface
{
  public function canCreate(ContainerInterface $container, $requestedName)
  {
    return in_array('Traversable', class_implements($requestedName), true);
  }

  public function __invoke(ContainerInterface $container,
                           $requestedName,
                           array $options = null)
  {
    return $requestedName();
  }
}

I create ServiceManager with registered Abstract Factory.
$serviceManager = new ServiceManager([
    // Neither works
  //'abstract_factories' => array('MyAbstractFactory')
  'abstract_factories' => array( new MyAbstractFactory() )
  //'abstract_factories' => array( MyAbstractFactory::class )
  /*
    'abstract_factories' => [
        MyAbstractFactory::class => new MyAbstractFactory()
    ]
  */
]);

Finally I try to obtain the instance of class A.
$a = $serviceManager->get(A::class);
var_dump($a);

I get
Fatal error: Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException: Unable to resolve service "A" to a factory; are you certain you provided it during configuration?
with the stack trace
.\vendor\zendframework\zend-servicemanager\src\ServiceManager.php(763): Zend\ServiceManager\ServiceManager->getFactory('A') #1
.\vendor\zendframework\zend-servicemanager\src\ServiceManager.php(200): Zend\ServiceManager\ServiceManager->doCreate('A') #2
.\script.php(53): Zend\ServiceManager\ServiceManager->get('A') #3

A: My formulation of the problem was wrong. @rkeet's comment made it clear.
As my objective was the working example of the Abstract Factory registration within ServiceManager, I post the single-file script where canCreate() is simplified just to check if the class exists.
<?php
// composer require zendframework/zend-servicemanager

require_once 'vendor/autoload.php';

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;

class A
{
    public $text;

    public function __construct()
    {
        $this->text = "Default text";
    }
}

class MyAbstractFactory implements AbstractFactoryInterface
{
    public function canCreate(ContainerInterface $container, $requestedName)
    {
        return class_exists($requestedName);
    }

    public function __invoke(ContainerInterface $container,
                             $requestedName,
                             array $options = null)
    {
        return new $requestedName();
    }
}

$serviceManager = new ServiceManager([
  //'abstract_factories' => array('MyAbstractFactory') // works
  //'abstract_factories' => array( new MyAbstractFactory() ) // works
  'abstract_factories' => array( MyAbstractFactory::class ) // also works
]);

try {
    $a = $serviceManager->get(A::class);
    var_dump($a);
    echo "
\n";
    $b = $serviceManager->get(B::class);
    var_dump($b);
} catch (Exception $e) {
    echo $e->getMessage() . "
\n";
    echo "{$e->getFile()}  ({$e->getLine()})";
}
?>

As @rkeet pointed, if someone needs the original example working, class A should implement Traversable.


text:
Q: How to define super user concept in MySQL DB for web application I am developing the application in which i have a super user concept. Super user is the user who has all the access for the application. So what my initial thinking is in user table the user with id 1 will be my super user. but how safe is this in terms of security concern ? is there any other logic which i can use to define super user ?
I have done more emphasis in coding side. I also implemented the roles and other access permissions, But what i need to to do is something like ghost user. Whenever he logged in he could be able to access everything like he is a father of application. for his access i shouldn't need to check any role conditions or access condition. is it possible ?
Thanks.

A: Why not work with roles? Make a column in your user table where you have 'SuperUser', 'Admin', 'ReadOnly',... Or perhaps just 0, 1, 2... and match it with a constant/enumerable in your code. Now you can easily change your super user, make multiple super users, give someone temporary super user rights, define other roles...

A: From the database point of view it is valid to define two or more users and grant more or less permissions to them, work with roles etc.. But as you said - it's about the application. So in parallel to the database security you need to consider application security in terms of:

*

*which user may get which functions, menu items, web pages etc.

*how can this be configured and parameterized, etc.

I personally put a bit more emphasis on the application side and less on the DB side. So thinking of e.g. PHP + MySQL, I have 2 DB users (operator, admin), but a database table within my application for each (application) user, assigning to them the operator or admin login for the DB and defining which parts of the application they get.

A: As a complement to the other answers:
Don't forget you could create users and grant/revoke permissions at DB level. I would not push for a 1-1 mapping between your application users and the DB users, but you could use that to implement "roles" and enforce permissions at DB level as an extra level of protection. This might be especially interesting if you have some users with "read-only" and/or "anonymous" access. This would prevent "escalation of privilege" due to a bug in you application code.

Super user is the user who has all the access for the application. So
  what my initial thinking is in user table the user with id 1 will be
  my super user.

In the Unix tradition, super-user is generally ID 0. This might improve code (maybe) and more important make it more understandable by programmers familiar with kernel/security coding.

But what i need to to do is something like ghost user [...] for his
  access i shouldn't need to check any role conditions or access
  condition. is it possible ?

I don't think this is a good idea to somehow "deactivate" all your security checks for one particular user. In order to improve maintainability and not clutter the code with permission-checking, as of myself, I would encapsulate all the code that need to check permissions in wrapper functions or objects, then I would use that wrapper in the rest of the application. Based on that, and if you implement "roles" at application level as someone else suggested, handling the "ghost user" shouldn't be too much of an issue.


text:
Q: Error running jest react test, jest not recognized I'm trying to run some jest tests but keep getting the error:
'jest' is not recognized as an internal or external command, operable program or batch file.
Here is my package.json, can anyone please help get my test framework setup?
{
 "name": "lac-react",
 "version": "0.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
 "test": "jest"
},
 "author": "",
 "license": "ISC",
 "devDependencies": {
  "browserify": "^9.0.8",
  "gulp": "^3.8.11",
  "gulp-concat": "^2.5.2",
  "gulp-cssmin": "^0.1.7",
  "gulp-react": "^3.0.1",
  "gulp-rename": "^1.2.2",
  "gulp-streamify": "0.0.5",
  "gulp-uglify": "^1.2.0",
  "gulp-watch": "^4.2.4",
  "reactify": "^1.1.0",
  "vinyl-source-stream": "^1.1.0",
  "watchify": "^3.2.1"
},
"jest": {
  "scriptPreprocessor": "./preprocessor.js",
  "unmockedModulePathPatterns": [
    "react"
  ],
  "testPathDirs": [
    "./src/components/__tests__/"
  ]
},
"dependencies": {
  "moment": "^2.10.2",
  "react": "^0.13.2",
  "react-datepicker": "^0.6.2",
  "react-message": "^1.3.0",
  "react-router": "^0.13.3",
  "react-skylight": "^0.2.0",
  "superagent": "^1.2.0",
  "react": "*",
  "react-tools": "*",
  "jest-cli": "*"
}
}

A: Looking closer at the errors, I had this:
error MSB8020: The build tools for Visual Studio 2010 (Platform Toolset = 'v100') cannot be found. To build using the v100 build tools, p lease install Visual Studio 2010 build tools.

I fixed this with adding the version of the build tools when doing an npm install:
--msvs_version=2013

All works fine now.
You can also fix this by adding a system variable

A: Install jest-cli. It worked for me.
Just npm i jest-cli
Test script should remain same "jest


text:
Q: Localize php website using mo files and locale problems I would like to localize my php website using mo files but I have encountered some problems using gettext.
This is the example I've used:
<?php

   putenv('LC_ALL=de_DE');
   setlocale(LC_ALL, 'de_DE');
   bindtextdomain("myPHPApp", "./locale");
   textdomain("myPHPApp");

   echo _("Have a nice day");

?>

My problem is that locales installed on my server is only en_GB.utf8, so
setlocale(LC_ALL, 'de_DE');

Always returns FALSE.
I found a workaround using the library "php-gettext" (https://launchpad.net/php-gettext/) that simulates the real php gettext functions and seems to works fine also if needed locales are not present on the system.
Anyone has experience with this library? It works fine? Is this the only solution if I can't add locales to my web server but I want to use mo files?
Thanks!


text:
Q: How can I change the color and action of my button in JS (p5)? I'm trying to not only change the color of my button, but also be able to call an onClick() function that links it to the next GUI. How do I do this? I'm using p5 as my IDE.
//Load the GUI
let img;
function preload() {
  img = loadImage('assets/main_menu.PNG');
}

//Call the GUI
function setup() {
  createCanvas(img.width, img.height);
  img.resize(img.width, img.height)
  image(img, 0, 0);
}

//Button 1
let button;
function draw() {

  image(img, 0, 0);
  button = createButton('Type Planet!');
  button.position(100, 855);
  button.size(200,50);
  button.color('red');
}


text:
Q: Does scrapy-crawlera handle a 429 status code? Wondering if anyone knows if scrapy-crawlera middleware handles the 429 status code when using scrapy, or if I need to implement my own retry logic?
I can't seem to find it documented anywhere

A: To answer your question: NO, The scrapy-crawlera Middleware doesn't handle 429 status, it actually doesn't "handle" any status, it just handles communication between Crawlera and Scrapy.
Now, about Crawlera, they do handle status 429 by default, meaning that when they get a 429 response status, they will mark it as a ban and retry the same request.
If Crawlera didn't succeed after several retries, it will return a 503 status to the client (Scrapy in this case).

A: You can extend list of retry codes with:
from scrapy.settings.default_settings import RETRY_HTTP_CODES

(check documentation here: https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:setting-RETRY_HTTP_CODES)
And then in you spider:
custom_settings = {
    'RETRY_HTTP_CODES': RETRY_HTTP_CODES + [429],
}


text:
Q: Change Mozilla settings globally on internal network We have a network in our company and I want to set network.automatic-ntlm-auth.allow-non-fqdn parameter to True in Mozilla FireFox for all clients,how can I do this?

A: Find the required registry setting, and push it out with Group Policy Preferences. Or search for a Firefox GPO administrative template that has the setting defined.

A: Firefox doesn't really want to be managed this way, to be honest.
It may be possible to bodge a solution by using a lock file (a mozilla.cfg file, configured as per this mozilla KB article). You can then use a startup/login script in a GPO to push that setting out to all your machines.
However, I personally think this will not be a satisfactory solution in the end. Mozilla simply don't appear interested in creating a system that can be reasonably managed in an enterprise.

A: MozillaGPO project provides mozilla autoconfig.js module that allow managing mozilla software wia Group Policy.


text:
Q: "To have " vs "Having " as perfect infinitive and gerund
Paceman Rubel Hossain was also recalled to the side
  after an injury-plagued season, as was left-arm spinner
  Taijul Islam having last played an ODI against New
  Zealand in the World Cup last year. ( this sentence is collected from an Australian cricket website)

I think it could be correct too if I write -

Paceman Rubel Hossain was also recalled to the side
  after an injury-plagued season, as was left-arm spinner
  Taijul Islam to have last played an ODI against New
  Zealand in the World Cup last year.

If both are correct, then what's the problem with  the following sentence of my last post which is wrong according to a commenter?

Jones is the latest player having signed with
  Barcelona.

A: No, "to have last played" is not a participial phrase but an infinitive phrase, and it cannot modify a verb phrase, as participle phrase can.

John, having played 90 minutes without rest, was winded.
John, to have played 90 minutes without rest, was winded.ungrammatical

John was winded, having played 90 minutes without rest.
John was winded, to have played 90 minutes without rest.ungrammatical
You ask:

what's the problem with the following sentence of my last post which
  is wrong according to a commenter?
Jones is the latest player having signed with Barcelona.

The correct form is
Jones is the latest player to have signed with Barcelona.
So what is the difference between the following sentences?

John was winded, to have played 90 minutes without
  rest.ungrammatical
Jones is the latest player to have signed with
  Barcelona.grammatical

The difference lies in the type of adjective phrase.

Jones is the player to have signed with Barcelona.
  ungrammatical
Jones is the {first, latest, third, tenth, only} player to have signed
  with Barcelona. grammatical
Jones is the least|most skilled player to have signed with Barcelona.
  grammatical
Jones is the skilled player to have signed with Barcelona.
  ungrammatical (unless there's some context which establishes two players, one of them skilled, the other unskilled, so that "the skilled player" refers to one of them)


text:
Q: Confusion using C# parallel and sequential arrays I'm taking an intro course and haven't had much trouble until we were introduced to methods and arrays. I'm having difficulty figuring out how to run a sequence search for an array that allows me to take a user input Zip Code, see if it is inside a Zip Code text file.
If it is, I need to see what index subscript it is inside another text file "AGI Text File" and output the the AGI number to my agiOutputLabel.
If anyone can clear up my misunderstanding or explain parallel to me that makes better sense than my textbook I would appreciate it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace AGI_Florida
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        // Creating an array method
        private void SetZipArray(int[] zips)
        {

        }
        private void SetAGIArray(double[] agi)
        {

        }

        private void FindAGI(int[] zips, int agi)
        {
            bool found = false;
            int index = 0;
            int position = -1;

            while (!found && index < zips.Length)
            {
                if (zips[index] == agi)
                {
                    found = true;
                    position = index;
                }
                index++;
            }
            return;
        }

        private void getAgiButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Initializing the array with 917 spaces
                int[] zips = new int[917];
                int[] agi = new int[917];

                // Pulling array from text file
                StreamReader inputFile = File.OpenText("AGI_FL_ZipCodes-               1.txt");
                // Setting index to 0 so the loop knows to stop at 917 spaces
                int index = 0;
                // Running loop
                while ((index < zips.Length) && (!inputFile.EndOfStream))
                {
                    // Creating the index from the zip and parsing it
                    zips[index] = int.Parse(inputFile.ReadLine());
                    index++;
                }
                inputFile.Close();

                int zipInput;

                if (int.TryParse(zipInputTextBox.Text, out zipInput))
                {
                    if (zipInput > 32003 && zipInput < 34997)
                    {
                        if (zipInput != -1)
                    {
                            MessageBox.Show(agi.ToString());

                    }

                    }
                    else
                    {
                        MessageBox.Show("Please enter a valid zip code");
                    }

                }

                else
                {
                    MessageBox.Show("Please enter a valid zip code");

                    zipInputTextBox.Text = " ";
                    zipInputTextBox.Focus();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void getAverageAgiButton_Click(object sender, EventArgs e)
        {
            // initialize new array
            double[] agi = new double[917];

            StreamReader inputFile = File.OpenText("AGI_FL-1-1.txt");
            // Setting index to 0 so the loop knows to stop at 917 spaces
            int index = 0;

            while ((index < agi.Length) && (!inputFile.EndOfStream))
            {
                // Creating the index from the zip and parsing it
                agi[index] = double.Parse(inputFile.ReadLine());
                index++;
            }
            inputFile.Close();

            // create a variable sum
            double sum = 0;

            // create a loop to read through the text file
            for (index = 0; index < agi.Length; index++)
            {
                // sum the index of values
                sum += agi[index];
            }

            // perform calculations
            double averageAgi = sum / (double) agi.Length;
            // print to label
            agiLabel.Text = averageAgi.ToString("c");

        }
    }
    }

A: First, welcome to coding!
There are lots of opportunities for improvement here. Lets make some of the code a bit cleaner
Magic numbers.
Lets get rid of that magic number 917. Instead of creating an array of known length and then going to a file with unknow data in it and hoping they line up, why not just use the length of the data in the file
var filePath = "AGI_FL_ZipCodes-1.txt";
var allLines = File.ReadAllLines(filePath); //Nicer version of File.OpenText +ReadLine+EndOfStream+whileloop
int[] zips = new int[allLines.Length];  //instead of hard coded magic value of 917;

Parsing and loops
However now you still have to read and parse all of the values.
for (int i = 0; i < allLines.Length; i++)
{
    var line = allLines[i];
    zips[i] = int.Parse(line);  //Chance of an error here is the file is invalid :-/
}

Conditional checks
You have a conditional check if (zipInput > 32003 && zipInput < 34997) which is fine. However considering our code is read more often than it is written, it is nice to format this in a way that is visually obvious what is happening. By moving the boundary values to the edge of the statement and having all the comparison operators pointing the same way, we can see that we want zipInput value between 32003 and 34997 (exclusive)
if (32003 < zipInput && zipInput < 34997)

Dead code
Next you check if the zipInput is not equal to -1. This is unnecessary due to the check immediately before it. All values between 32003 and 34997 are not equal to -1.
You also declare the agi variable and never use it. You can delete this line
int[] agi = new int[917];

Finding values in an array
Your FindAGI method look pretty good. However I would "upgrade" it to be a function that returns the value you are looking for.
private int IndexOf(int[] source, int value)
{
    for (int i = 0; i < source.Length; i++)
    {
        if (source[i] == value)
        {
            return i;
        }
    }
    return -1;
}

Note that it will terminate as soon as it finds the element. If no match is made, then it will return -1 (which is pretty standard behaviour).
This may help you get on your way, but right now I dont see where any of this code is actually used i.e. the FindAGI (now IndexOf) doesn't appear to be referenced.


text:
Q: How to make series stationary when dependent variable is log(y) I need some help in understanding the following:
I have a time series data (y) that I am using to run regression models. However, my dependent variable is log(y).

*

*Should I test for stationarity of y or log(y)?

*If say y or log(y) turn out to be non-stationary and I need to make the sure that my dependent variable is stationary, I need to difference it. Should I take first difference of y and then take log(first diff of y) as my dependent variable or take first diff of log(y)?

A: *

*If your dependent variable in the regression is log($y$), then do the stationarity testing on log($y$) because typically stationarity requirement arises from statistics (assumption of a statistical model) rather than the subject-matter domain.

*First take logs, then difference. This transformation can be interpreted as (or indeed is) log-return of the original variable. It approximately equals percentage returns for small changes in $y$. Also, you cannot difference first and then take logs due to a technical reason; the differences will most likely include some negative values, and logs are defined on positive values only.


text:
Q: Javascript Filter childNodes by CSS Class In my code I am using querySelectorAll to create a nodeList.
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)')

This array contains ~17 elements and I want to be able to filter these results where the childNode has a certain class.
I am currently using a[0].childNodes but this just displays all the children. I only want it to return the specific ones that contain a class .P-xs

A: According to this, you should be able to then call a[0].querySelectorAll('.P-xs')

A: You can use Function.prototype.call to borrow Array.prototype.filter and be able to use it on your NodeList:
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)');
var b = [].filter.call(a, function(el) {
  return el.classList.contains('P-xs');
});

A: You can use a for loop on your initial query selector result to create an array only containing those elements with a given descendant. See the example below.

var a = document.querySelectorAll('#one');
var b = [];
for (var i = 0; i  tr.editable:not(.empty-bench)');
var afterFilter = [].concat.apply([], [].map.call(a, function (el) {
    return [].filter.call(el.childNodes, function (ch) {
        return ch.nodeType === 1 && ch.classList.contains('P-xs');
    });
}));

But if you want the parent then try below:
var a = document.querySelectorAll('tbody > tr.editable:not(.empty-bench)');
var afterFilter = [].map.call(a, function(el) {
    return [].filter.call(el.childNodes, function (ch) {
        return ch.nodeType === 1 && ch.classList.contains('spec');
    });
});


text:
Q: ## macro argument concatenation not working as I expected Shouldn't this:
#define MOGSH_CONCAT (x,y) x##y
#define MOGSH_DOUBLE (a,b) MOGSH_CONCAT(a,b)
#define MOGSH_DEFINEPROC (p) MOGSH_DOUBLE(_gt,p) options_dialog::p;

MOGSH_DEFINEPROC(AssignMainForm);

happily expand to:
_gtAssignMainForm options_dialog::AssignMainForm;

Given that _gt is not defined, _gtAssignMainForm is:
typedef void (__stdcall *_gtAssignMainForm)();

and options_dialog is just a class where AssignMainForm is a static member.
Instead, in MSVC9, I get the error:
'a' : undeclared identifier

on the line containing
MOGSH_DEFINEPROC(AssignMainForm);

A: In the definition of a function-like macro there can be no whitespace between the macro name and the ( beginning the parameter list.
#define MOGSH_CONCAT(x,y) x##y
//                  ^ no whitespace allowed here

As you have it now (with whitespace), MOGSH_CONCAT is an object-like macro with a replacement list of (x,y) x##y, which is why you are getting such strange results.


text:
Q: Tadpole diagram and vacuum This statement may be well-known. For many massless theories, these tadpole diagram graphs vanish in dimensional regularization (by dimensional analysis and the absence of any inherent mass scale in the loop integral).

How can one show this is QFT statement is true(tadpole diagram graphs vanish) regardless the coupling, say by Yukawa-Higgs via $\lambda \bar{\Psi} \phi \Psi$ or by gauge field $g \bar{\Psi} \gamma^\mu A_\mu \Psi$, etc? i.e. does not depend on $\lambda,g$ or an energy cutoff $\Lambda$?

A: If there is a soliton background (of dashed lines), then this tadpole diagram with extended legs like

shall not be zero due to Jackiw-Rebbi or Goldstone-Wilczek effect; the soliton background (dashed lines) will induce nontrivial (fractionalized) induced quantum numbers (or simply the charge or vacuum expectation value) for the scalar bosons (solid line); even if the original scalar bosons(solid line) are massless.
For example. see the bosonic anomaly in arxiv-1403.5256 - Bosonic Anomaly, Induced Fractional Quantum Number and Degenerate Zero Modes.
Interestingly, such an effect takes place on the surface of Symmetry Protected Topological(SPT) States as noticed in this Ref. And see Reference therein, e.g. about J. Goldstone and F. Wilczek, Phys. Rev. Lett. 47, 986 (1981) and R. Jackiw and C. Rebbi, Phys. Rev. D 13, 3398 (1976).


text:
Q: jQuery Validation plugin: add validation rules but need to hide message on focus The following method is called to make controls mandatory based on some conditions
addRequired = function ($ele, msg, min, minMsg) {
    $ele.rules('add', {
        required: true,
        min: min,
        messages: {
            required: msg,
            min: minMsg
        }
    });

    $.validator.unobtrusive.parseElement($ele.get(0));
}

And the calling code
if (requiredOptions["CompanyName"]) {
    addRequired($('#CompanyName'), 'Company is required');
}
if (requiredOptions["SiteName"]) {
    addRequired($('#SiteNameDD'), 'Enter a Site');
}

The validation is working perfectly. But the requirement is when controls (e.g. CompanyName) are focused, the required message should disappear. Basically, whenever the required control focused, the error message appears. The requirement is to show the message on focusout or form submit events. How could i achieve that?
Updated
From the solution mentioned by @Praveen_Kumar I came up with the following changes
addRequired = function ($ele, msg, min, minMsg) {
        $ele.rules('add', {
           ... ... ...
        });

        // Remove the validator message on focus.
        $ele.on("focus", function () {
            var thisRule = $.validator.staticRules($ele.get(0));
            thisRule.required = false;
         });

        // Add the validator message on blur.
        $ele.on("blur", function () {
            var thisRule = $.validator.staticRules($ele.get(0));
            thisRule.required = true;
        });
       ...
}

A: Just add a bit of code here:
addRequired = function ($ele, msg, min, minMsg) {
    $ele.rules('add', {
        required: true,
        min: min,
        messages: {
            required: msg,
            min: minMsg
        }
    });

    // Remove the validator message on focus.
    $ele.one("focus", function () {
        $.validator.hideMessage($ele.get(0)); // Replace this with the right method.
        $ele.off("focus");
    });

    $.validator.unobtrusive.parseElement($ele.get(0));
}

Here $.validator.hideMessage($ele.get(0)); is a pseudo function, that takes in the element that was parsed and deemed invalid. You have not provided the validator plugin URL to correctly guide you what the exact hide function is.


text:
Q: Fill raster to shapefile boundary I created TIN from contour lines, then I convert this TIN to Raster.
After that I clipped the raster by Extract by Mask tool,
now the problem is raster does not fill whole boundary.
Below image show the problem, how can I figure out this?

A: I just had to do this myself. I followed another post as guidance How to extend raster data for larger boundary?
What you're looking for is a Euclidean Allocation.
Make sure you specify the shapefile boundary in the processing extent.


text:
Q: Having trouble understanding Prolog DCG

This is a new following up question of https://stackoverflow.com/questions/34170191/confused-about-how-to-use-in-prolog?noredirect=1#comment56112107_34170191
I tried to make the code in 9.7 more powerful. So I decide to add a new grammar
every,man,that,a,woman,loves,dance

the answer should be
all(man(X)&exists(woman(Y)&loves(Y, X)))->dance(1)))

at least I believe it is the answer.
I tried some approach but it does not work. This is my final Wrong solution:
rel_clasue(X,P1,P3)-->[that],determiner(X,P1,P2,P3),noun(X,P1),trans_verb(X,P2,?).

? means that I do not know what to write.
and I believe I has other bugs too.
Rest code are exactly as book above.
of course I add "dance" part
Can some one help me fix it or write a correct one?

A: Looking at rel_clause//3 it looks like you basically have two rules: an empty base case and another case that accepts a verb phrase. So it works when you give it [that,loves,a,woman] for instance:
?- phrase(rel_clause(X, P1, Y), [that,loves,a,woman]).
Y = P1&exists(_G1990, woman(_G1990)&loves(X, _G1990))

But it doesn't work when you give it a more complex phrase:
?- phrase(rel_clause(X, P1, Y), [that,a,woman,loves]).
false.

So I think you need to add a rule to rel_clause//3 to handle that. It seems clear to me that [that,a,woman,loves] and [that,loves,a,woman] is really just inverting the relationship, and in the former case we actually get a transitive verb without a noun following it to be the direct object. In other words [that,a,woman,loves] is somehow like man(M) & (exists(woman(W)) & loves(W, M) where [that,loves,a,woman] is more like man(M) & (exists(woman(W)) & loves(M, W), where the M and W are swapped in the love/2 structure.
I venture this as a guess:
rel_clause(X, P1, (P1&P3)) -->
    [that], noun_phrase(Y, P2, P3), trans_verb(Y, X, P2).

This seems to produce the parse we want:
?- phrase(sentence(X), [every,man,that,a,woman,loves,lives]).
X = all(_1, man(_1)&exists(_2, woman(_2)&loves(_2, _1))->lives(_1)) ;

Apart from that, dance should be dances and you will need to make an intransitive verb rule for that:
intrans_verb(X, dances(X)) --> [dances].


text:
Q: How to filter scalars in a Tensorboard event file and access them programmatically? I have a big tensorboard event file that I want to access programmatically. I used the code below to do this but I have so many scalars in my event file that it's very slow. Is there a way to  accumulate only a few scalars that I'm interested in and not the complete file ?
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
event_acc = EventAccumulator('/path/to/summary/folder')
event_acc.Reload()
# Show all tags in the log file
print(event_acc.Tags())

# E. g. get wall clock, number of steps and value for a scalar 'Accuracy'
w_times, step_nums, vals = zip(*event_acc.Scalars('Accuracy'))


text:
Q: Need to output a data file in a specific format using download handler in Rshiny I have a basic shiny app and I want the user to select a data set and then be able to download the selected data set without the column names. In addition, I want to add a header and a footer record to the data set being downloaded.
The header record = 0, MYFILE, 20200917.
Footer record = 9, [Number of rows in the selected data set], [sum the first column of the selected data set].
Below is the code I have so far:
ui
library(shiny)

shinyUI(fluidPage(
  titlePanel('File download'),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose a dataset:",
                  choices = c("Rock", "Pressure", "Cars")),
      radioButtons("filetype", "File type:",
                   choices = c("csv", "tsv")),
      downloadButton('downloadData', 'Download')
    ),
    mainPanel(
      tableOutput('table')
    )
  )
))

Server:
library(shiny)
library(tidyverse)

shinyServer(function(input, output) {
  datasetInput <- reactive({

    switch(input$dataset,
           "Rock" = rock,
           "Pressure" = pressure,
           "Cars" = cars)
  })

  output$table <- renderTable({
    datasetInput()
  })

  output$downloadData <- downloadHandler(

    filename = function() {
      paste("myfile", input$dataset, gsub("-", "", Sys.Date()), "_01_res.dat_00000002", sep = ".")
    },

    content = function(file) {
      # Write to a file specified by the 'file' argument
      write.table(datasetInput(), file,
                  row.names = FALSE, col.names = F, sep = ",")

    }
  )
})

The above code works so far but without the header and footer record. when i try to add the header and footer record to the data set, it doesn't work.
I only need to change the downloadHandler part to add the footer and header record but when i do i get an error. Below is what i have tried:
  output$downloadData <- downloadHandler(

    filename = function() {
      paste("myfile", input$dataset, gsub("-", "", Sys.Date()),"_01_res.dat_00000002", sep = ".")
    },

    content = function(file) {
      # Write to a file specified by the 'file' argument
      a = paste0("0,","MYFILE,",gsub("-", "", Sys.Date()))
      z = paste0("9,",nrow(datasetInput), ",", sum(datasetInput))
      write.table(x = a, quote = F, sep = ",", col.names = F, row.names = F, file, sep = sep)
      write.table(x = datasetInput(), quote = F, sep = ",", col.names = F, row.names = F, append = T, file, sep = sep)
      write.table(x = z, quote = F, sep = ",", col.names = F, row.names = F, append = T, file, sep = sep)

    }
  )

I can achieve this in a normal R file without Shiny. the way i do it there is by writing a function and then calling the function as shown below:
Function
write_output <- function(a, df, z){
  filename = paste("myfile", "Rock", gsub("-", "", Sys.Date()) ,"_01_res.dat_00000002",sep = "") %>% gsub( "-", "", .)
  write.table(x = a, file = filename, quote = F, sep = ",", col.names = F, row.names = F)
  write.table(x = df, file = filename, quote = F, sep = ",", col.names = F, row.names = F, append = T)
  write.table(x = z, file = filename, quote = F, sep = ",", col.names = F, row.names = F, append = T)
}

Apply the function:
write_output(a =  paste0("0,","MyFILE,",gsub("-", "", Sys.Date())),
             df = datasetInput,
             z = paste0("9,",nrow(datasetInput), ",", sum(datasetInput[,1])))

So, in short i need to output a data set with a header and footer record which is not the same size as the data set.
Here is an example of the output - first row being the header record, followed by 3 rows from rock data set and last row is the footer
0,MyFILE,20200917
4990,2791.9,0.0903296,6.3
7002,3892.6,0.148622,6.3
7558,3930.66,0.183312,6.3
9,48,345011
Any help will be greatly appreciated :). Thanks

A: I had multiple separators in my code which was confusing it. I took out one of the argument and it worked. Here's the new code for download Handler.
output$downloadData <- downloadHandler(
filename = function() {
  paste("myfile", input$dataset, gsub("-", "", Sys.Date()), sep = ".")
},

content = function(file) {
  # Write to a file specified by the 'file' argument
  a = paste0("0,","MYFILE,",gsub("-", "", Sys.Date()))
  z = paste0("9,",nrow(datasetInput()), ",", sum(datasetInput()[,1]))
  write.table(x = a, quote = F, sep = ",", col.names = F, row.names = F, file)
  write.table(x = datasetInput(), quote = F, sep = ",", col.names = F, row.names = F, append = T, file)
  write.table(x = z, quote = F, sep = ",", col.names = F, row.names = F, append = T, file)

}

)


text:
Q: Missing right parenthesis when running on Oracle sql live CREATE TABLE Enrollment
(
    OfferNo  NUMBER(10)  NOT NULL,
    StdNo    CHAR(11)    NOT NULL,
    EnrGrade NUMBER(3,2) NULL,

    CONSTRAINT EnrollmentPK
        PRIMARY KEY (OfferNo, StdNo),
    CONSTRAINT OfferingFK
        FOREIGN KEY (OfferNo) REFERENCES Offering
                ON DELETE CASCADE
                ON UPDATE CASCADE,
    CONSTRAINT StudentFK
        FOREIGN KEY (StdNo) REFERENCES Student
                ON DELETE CASCADE
                ON UPDATE CASCADE
);

A: You're missing the columns the constraints refer to:
CREATE TABLE Enrollment(
    OfferNo       NUMBER(10)       NOT NULL,
    StdNo         CHAR(11)      NOT NULL,
    EnrGrade      NUMBER(3,2)  NULL,
    CONSTRAINT EnrollmentPK PRIMARY KEY (OfferNo, StdNo),
    CONSTRAINT OfferingFK FOREIGN KEY (OfferNo) REFERENCES Offering(OfferNo)
    -- Here --------------------------------------------------------^
                          ON DELETE CASCADE
                          ON UPDATE CASCADE,
    CONSTRAINT StudentFK FOREIGN KEY (StdNo) REFERENCES Student(StdNo)
    -- And here ------------------------------------------------^
                          ON DELETE CASCADE
                          ON UPDATE CASCADE
);


text: Q: how would i need to write a java script on keypress for Alt+2 and Alt+1? I am using secureCRT for my test execution, I would need to automate some functionalities such as to recognize keypress actions thru bash script. But i couldn;t make it possible. If there any way to create bash script for keypress please provide me a comment. Or using Javascript or Python script i can integrete with bash script.


text:
Q: MySQL/PHP GROUP BY day I have query that groups all records by day.
$query = mysql_query("SELECT DATE_FORMAT(date, '%d/%m/%Y') AS day, COUNT(id) AS total FROM invoices GROUP BY day");

How i do that it shows me all days, even if there is no records, until today
Omerimuni

A: I think it is best to just get all the records in the table, ordered by date and fill in the gaps using PHP.
It is difficult to generate a sequence of dates in MySQL. You often see solutions with stored procedures and temp tables, like here.
In PHP, create a loop that goes through each date until today. In the loop you can check for each record if a date exists in the results of the query. If not, you can just render an empty row or whatever you want.
This check is not so expensive, because you sort the results in the query by date as well, so you will only need to check if the current record has the same date as the current date in the loop.
If the date of the record is greater, you should not process this record yet. If the date is the same, process the record and fetch the next record.

A: Maybe this is not best solution, but i did it myself :D
$result = mysql_query("SELECT date_format(date, '%Y-%m-%d') AS date FROM invoices ORDER BY id ASC LIMIT 1");
    $first = mysql_fetch_array($result);

    $year = date('Y', strtotime($first['date']));
    $month = date('m', strtotime($first['date']));
    $day =  date('d', strtotime($first['date']));

    for ($i = strtotime($year.'-'.$month.'-'.$day); $i < strtotime('NOW'); $i=$i+24*60*60){
        $r = date('d/m/Y',$i);
        $res = mysql_query("SELECT DATE_FORMAT(date, '%d/%m/%Y') AS day, COUNT(id) AS total FROM invoices WHERE DATE_FORMAT(date, '%d/%m/%Y') LIKE '%$r%' GROUP BY day");
        $arr = mysql_fetch_array($res);

        if(mysql_num_rows($res)){
            echo "".$arr['day']." => ".$arr['total']."
";
        }else{
            echo date('d/m/Y',$i)."=>  0
";
        }
    }

A: There is no way to do this, unless you will have table with days. Than you can left join on it

A: In principle you could create a new table containing all days. Then you left join this table into "invoices" on days.
However, my suggestion for you is to instead handle this logic in PHP.


text:
Q: MySQL 5.7 Create Trigger Syntax Error? I've been trying to create a simple BEFORE INSERT trigger on a database table (MySQL v 5.7 ) but I keep receiving a vague "#1064 ... syntax error" message which doesn't help resolve the issue.
Here's the SQL:
CREATE OR REPLACE TRIGGER `CREATE_QUIZ_TRIG` BEFORE INSERT ON `quiz`
 FOR EACH ROW BEGIN
    SET NEW.ACTIVE = UPPER(NEW.ACTIVE);
    SET NEW.CREATED = NOW();
 END
/

All I'm trying to do is enforce a column to uppercase and then insert the current date & time into a timestamp column. I've been following the documentation from:
https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
and realise that for multi-statement expression I have to redefine the delimiter at the beginning of the trigger's creation but the same '#1064' error occurs.
This is made even more confusing because when I use phpmyadmin's interface for creating the same trigger it works fine - but won't when I export the generated SQL and try to create the trigger using that!?
Thanks for any help

A: I didn't realise that, by default, phpmyadmin adds a ; delimiter which was breaking the ; used to end a statement within the BEGIN END block.


text:
Q: How do I load a single image with multiple images on it? I have an image file that has multiple different images on it.  I was wondering how to make it so that I can load the individual images from the single one instead of breaking each into its own thing.  Sorry if I couldn't clarify what I am trying to ask.

A: You could load it all as one image and than draw the different segments onto the screen separately, or even define variables of the segments. This would effectively give you multiple images.


text:
Q: How to increase the number of posts in Soho blogger template Hi there I'm creating a blog in blogger, and the there is a problem in loading the posts in the main page.
I would like to appear 20 posts doesn't matter if the post is to old. It just show 3 posts per time.
Some one could help me please?

This blue squares are where I would like the posts to be
Again thanks a lot guys!

A: *

*Navigate to Layout menu in your blogger dashboard.

*In Layout menu you will see a section called blog posts.

*Click on edit and now you will see a popup window with several settings.

*Enter the number of posts to be displayed on main page and save.


text:
Q: XBase Language Rounding Weirdness I have a requirement to take legacy code in an XBase-style language (FoxPro, in this case) and convert it to C#.NET.  I want to get identical output from my rewrite, but rounding discrepancies are driving me nuts.  I tried Decimal.Round(MidpointRounding) stuff alone, but found that I also needed to write my own "round up" function for midpoint = 5 situations.
That would be fine, if it worked, but what I'm seeing is that the my "round up" method is needed to agree with FoxPro output in some cases, but actually creates discrepancies in others.  The database query is doing some multiplication and division, and I'm wondering whether math discrepancies between the two systems are accumulating.
Here is an example of what seems to me to be an inconsistency.  The initial value of each pair comes from the output of my LINQ query.  Given these, I want to generate a rounded result that is identical to the FoxPro result shown:
.NET LINQ Query result: 7.0477049103806673503597572093.
FoxPro rounding: 7.0

.NET LINQ: 7.2499596595318807183725770943.
FoxPro rounding: 7.3

Any suggestions as to how I can exactly duplicate the value from the legacy system without out resorting to a completely kludgey hack?

A: Your problem might have to do with floating point accuracy. Before the FoxPro program round, what type of variable does it store the value in ?  And what type do you use ?
If the FoxPro program uses a floating point number with less accuracy than you do in C# (or vice versa), this might be the reason for the discrepancies you are seeing.